1
0
Fork 0
mirror of synced 2024-11-22 08:45:34 -05:00

Updated plugins

This commit is contained in:
amix 2016-06-11 15:56:50 +02:00
parent cc0e8a9907
commit 0228ad0e9e
60 changed files with 1341 additions and 784 deletions

View file

@ -0,0 +1,7 @@
*.markdown
*.zip
note.txt
tags
tags-cn
.hg*
tmp/*

View file

@ -315,11 +315,11 @@ fu! s:Open()
cal s:setupblank() cal s:setupblank()
endf endf
fu! s:Close() fu! s:Close(exit)
cal s:buffunc(0) cal s:buffunc(0)
if winnr('$') == 1 if winnr('$') == 1
bw! bw!
el elsei a:exit
try | bun! try | bun!
cat | clo! | endt cat | clo! | endt
cal s:unmarksigns() cal s:unmarksigns()
@ -908,7 +908,7 @@ endf
fu! s:PrtExit() fu! s:PrtExit()
if bufnr('%') == s:bufnr && bufname('%') == 'ControlP' if bufnr('%') == s:bufnr && bufname('%') == 'ControlP'
noa cal s:Close() noa cal s:Close(1)
noa winc p noa winc p
en en
endf endf
@ -1754,7 +1754,7 @@ fu! ctrlp#syntax()
en en
sy match CtrlPNoEntries '^ == NO ENTRIES ==$' sy match CtrlPNoEntries '^ == NO ENTRIES ==$'
if hlexists('CtrlPLinePre') if hlexists('CtrlPLinePre')
sy match CtrlPLinePre '^>' exe "sy match CtrlPLinePre '^".escape(get(g:, 'ctrlp_line_prefix', '>'),'^$.*~\')."'"
en en
if s:itemtype == 1 && s:has_conceal if s:itemtype == 1 && s:has_conceal
@ -1941,7 +1941,7 @@ fu! s:isabs(path)
endf endf
fu! s:bufnrfilpath(line) fu! s:bufnrfilpath(line)
if s:isabs(a:line) || a:line =~ '^\~[/\\]' if s:isabs(a:line) || a:line =~ '^\~[/\\]' || a:line =~ '^\w\+:\/\/'
let filpath = a:line let filpath = a:line
el el
let filpath = s:dyncwd.s:lash().a:line let filpath = s:dyncwd.s:lash().a:line
@ -1956,9 +1956,10 @@ fu! s:bufnrfilpath(line)
endf endf
fu! ctrlp#normcmd(cmd, ...) fu! ctrlp#normcmd(cmd, ...)
let buftypes = [ 'quickfix', 'help' ]
if a:0 < 2 && s:nosplit() | retu a:cmd | en if a:0 < 2 && s:nosplit() | retu a:cmd | en
let norwins = filter(range(1, winnr('$')), let norwins = filter(range(1, winnr('$')),
\ 'empty(getbufvar(winbufnr(v:val), "&bt")) || s:isneovimterminal(winbufnr(v:val))') \ 'index(buftypes, getbufvar(winbufnr(v:val), "&bt")) == -1 || s:isneovimterminal(winbufnr(v:val))')
for each in norwins for each in norwins
let bufnr = winbufnr(each) let bufnr = winbufnr(each)
if empty(bufname(bufnr)) && empty(getbufvar(bufnr, '&ft')) if empty(bufname(bufnr)) && empty(getbufvar(bufnr, '&ft'))
@ -2533,7 +2534,7 @@ if has('autocmd')
aug CtrlPAug aug CtrlPAug
au! au!
au BufEnter ControlP cal s:checkbuf() au BufEnter ControlP cal s:checkbuf()
au BufLeave ControlP noa cal s:Close() au BufLeave ControlP noa cal s:Close(0)
au VimLeavePre * cal s:leavepre() au VimLeavePre * cal s:leavepre()
aug END aug END
en en

View file

@ -520,8 +520,8 @@ Oops! We forgot the cool mark for the branch component! (work with the patched f
```vim ```vim
function! LightLineFugitive() function! LightLineFugitive()
if exists("*fugitive#head") if exists("*fugitive#head")
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? '⭠ '._ : '' return branch !=# '' ? '⭠ '.branch : ''
endif endif
return '' return ''
endfunction endfunction
@ -596,8 +596,8 @@ endfunction
function! LightLineFugitive() function! LightLineFugitive()
if &ft !~? 'vimfiler\|gundo' && exists("*fugitive#head") if &ft !~? 'vimfiler\|gundo' && exists("*fugitive#head")
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? '⭠ '._ : '' return branch !=# '' ? '⭠ '.branch : ''
endif endif
return '' return ''
endfunction endfunction
@ -691,8 +691,8 @@ function! LightLineFugitive()
try try
if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head') if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head')
let mark = '' " edit here for cool mark let mark = '' " edit here for cool mark
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? mark._ : '' return branch !=# '' ? mark.branch : ''
endif endif
catch catch
endtry endtry

View file

@ -2,7 +2,7 @@
" Filename: autoload/lightline.vim " Filename: autoload/lightline.vim
" Author: itchyny " Author: itchyny
" License: MIT License " License: MIT License
" Last Change: 2016/05/14 13:20:45. " Last Change: 2016/06/11 14:05:27.
" ============================================================================= " =============================================================================
let s:save_cpo = &cpo let s:save_cpo = &cpo
@ -276,7 +276,7 @@ function! lightline#highlight(...) abort
let rs = has_key(get(c, d, {}), 'right') ? c[d].right : has_key(f, d) && has_key(get(c, f[d], {}), 'right') ? c[f[d]].right : c.normal.right let rs = has_key(get(c, d, {}), 'right') ? c[d].right : has_key(f, d) && has_key(get(c, f[d], {}), 'right') ? c[f[d]].right : c.normal.right
for [p, l, zs] in [['Left', len(left), ls], ['Right', len(right), rs]] for [p, l, zs] in [['Left', len(left), ls], ['Right', len(right), rs]]
for [i, t] in map(range(0, l), '[v:val, 0]') + types for [i, t] in map(range(0, l), '[v:val, 0]') + types
if i != l if i < l || i < 1
let r = t ? (has_key(get(c, d, []), i) ? c[d][i][0] : has_key(get(c, 'tabline', {}), i) ? c.tabline[i][0] : get(c.normal, i, zs)[0]) : get(zs, i, ms) let r = t ? (has_key(get(c, d, []), i) ? c[d][i][0] : has_key(get(c, 'tabline', {}), i) ? c.tabline[i][0] : get(c.normal, i, zs)[0]) : get(zs, i, ms)
exec printf('hi LightLine%s_%s_%s guifg=%s guibg=%s ctermfg=%s ctermbg=%s %s', p, mode, i, r[0], r[1], r[2], r[3], s:term(r)) exec printf('hi LightLine%s_%s_%s guifg=%s guibg=%s ctermfg=%s ctermbg=%s %s', p, mode, i, r[0], r[1], r[2], r[3], s:term(r))
endif endif

View file

@ -4,7 +4,7 @@ Version: 0.0
Author: itchyny (https://github.com/itchyny) Author: itchyny (https://github.com/itchyny)
License: MIT License License: MIT License
Repository: https://github.com/itchyny/lightline.vim Repository: https://github.com/itchyny/lightline.vim
Last Change: 2016/05/08 13:56:19. Last Change: 2016/05/26 21:57:34.
CONTENTS *lightline-contents* CONTENTS *lightline-contents*
@ -175,14 +175,18 @@ OPTIONS *lightline-option*
|g:lightline.component_expand|. The types are used to specify |g:lightline.component_expand|. The types are used to specify
the color. Specifically, the type raw is used to specify a the color. Specifically, the type raw is used to specify a
component which should not be wrapped by item group: %(...%). component which should not be wrapped by item group: %(...%).
> The default value is: >
let g:lightline.component_type = { let g:lightline.component_type = {
\ 'tabs': 'tabsel', \ 'tabs': 'tabsel',
\ 'close': 'raw' } \ 'close': 'raw' }
< <
g:lightline.tab_component *g:lightline.tab_component* g:lightline.tab_component *g:lightline.tab_component*
A dictionary for components in one tab. A dictionary for components in one tab.
The default value is: >
let g:lightline.tab_component = {}
<
g:lightline.tab_component_function *g:lightline.tab_component_function* g:lightline.tab_component_function *g:lightline.tab_component_function*
Another dictionary for components in one tab. Another dictionary for components in one tab.
A function specified as a tab component takes one argument: A function specified as a tab component takes one argument:
@ -286,8 +290,8 @@ nice.
endfunction endfunction
function! LightLineFugitive() function! LightLineFugitive()
if exists('*fugitive#head') if exists('*fugitive#head')
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? ''._ : '' return branch !=# '' ? ''.branch : ''
endif endif
return '' return ''
endfunction endfunction
@ -311,8 +315,8 @@ look nice.
endfunction endfunction
function! LightLineFugitive() function! LightLineFugitive()
if exists('*fugitive#head') if exists('*fugitive#head')
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? '⭠ '._ : '' return branch !=# '' ? '⭠ '.branch : ''
endif endif
return '' return ''
endfunction endfunction
@ -337,7 +341,7 @@ Exposed functions for lightline.vim.
Returns the mode of the Vim using |g:lightline.mode_map|. Returns the mode of the Vim using |g:lightline.mode_map|.
lightline#init() *lightline#init()* lightline#init() *lightline#init()*
Initializes the variable |g:lightline|. Initializes the internal state from |g:lightline|.
lightline#colorscheme() *lightline#colorscheme()* lightline#colorscheme() *lightline#colorscheme()*
Initializes the colorscheme and the highlight groups. Initializes the colorscheme and the highlight groups.
@ -741,8 +745,8 @@ A nice example for |vim-powerline| font users:
endfunction endfunction
function! LightLineFugitive() function! LightLineFugitive()
if &ft !~? 'vimfiler' && exists('*fugitive#head') if &ft !~? 'vimfiler' && exists('*fugitive#head')
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? '⭠ '._ : '' return branch !=# '' ? '⭠ '.branch : ''
endif endif
return '' return ''
endfunction endfunction
@ -802,8 +806,8 @@ For users who uses lots of plugins:
try try
if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head') if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head')
let mark = '' " edit here for cool mark let mark = '' " edit here for cool mark
let _ = fugitive#head() let branch = fugitive#head()
return _ !=# '' ? mark._ : '' return branch !=# '' ? mark.branch : ''
endif endif
catch catch
endtry endtry

View file

@ -3,9 +3,6 @@ let s:assert = themis#helper('assert')
function! s:suite.before_each() function! s:suite.before_each()
hi clear hi clear
let g:lightline = {}
call lightline#init()
call lightline#colorscheme()
endfunction endfunction
function! s:hi(name) function! s:hi(name)
@ -22,6 +19,9 @@ function! s:pattern(xs, ...) abort
endfunction endfunction
function! s:suite.highlight() function! s:suite.highlight()
let g:lightline = {}
call lightline#init()
call lightline#colorscheme()
let palette = lightline#palette() let palette = lightline#palette()
call s:assert.match(s:hi('LightLineLeft_normal_0'), s:pattern(palette.normal.left[0])) call s:assert.match(s:hi('LightLineLeft_normal_0'), s:pattern(palette.normal.left[0]))
call s:assert.match(s:hi('LightLineLeft_normal_1'), s:pattern(palette.normal.left[1])) call s:assert.match(s:hi('LightLineLeft_normal_1'), s:pattern(palette.normal.left[1]))
@ -34,6 +34,9 @@ function! s:suite.highlight()
endfunction endfunction
function! s:suite.insert() function! s:suite.insert()
let g:lightline = {}
call lightline#init()
call lightline#colorscheme()
call lightline#highlight('insert') call lightline#highlight('insert')
let palette = lightline#palette() let palette = lightline#palette()
call s:assert.match(s:hi('LightLineLeft_insert_0'), s:pattern(palette.insert.left[0])) call s:assert.match(s:hi('LightLineLeft_insert_0'), s:pattern(palette.insert.left[0]))
@ -48,6 +51,9 @@ endfunction
function! s:suite.visual() function! s:suite.visual()
let g:lightline = {}
call lightline#init()
call lightline#colorscheme()
call lightline#highlight('visual') call lightline#highlight('visual')
let palette = lightline#palette() let palette = lightline#palette()
call s:assert.match(s:hi('LightLineLeft_visual_0'), s:pattern(palette.visual.left[0])) call s:assert.match(s:hi('LightLineLeft_visual_0'), s:pattern(palette.visual.left[0]))
@ -61,6 +67,9 @@ function! s:suite.visual()
endfunction endfunction
function! s:suite.replace() function! s:suite.replace()
let g:lightline = {}
call lightline#init()
call lightline#colorscheme()
call lightline#highlight('replace') call lightline#highlight('replace')
let palette = lightline#palette() let palette = lightline#palette()
call s:assert.match(s:hi('LightLineLeft_replace_0'), s:pattern(palette.replace.left[0])) call s:assert.match(s:hi('LightLineLeft_replace_0'), s:pattern(palette.replace.left[0]))
@ -97,6 +106,27 @@ function! s:suite.left_right()
call s:assert.match(s:hi('LightLineMiddle_normal'), s:pattern(palette.normal.middle[0])) call s:assert.match(s:hi('LightLineMiddle_normal'), s:pattern(palette.normal.middle[0]))
endfunction endfunction
function! s:suite.no_components()
let g:lightline = {
\ 'active': {
\ 'left': [],
\ 'right': []
\ },
\ 'inactive': {
\ 'left': [],
\ 'right': []
\ },
\ }
call lightline#init()
call lightline#colorscheme()
let palette = lightline#palette()
call s:assert.match(s:hi('LightLineLeft_normal_0'), s:pattern(palette.normal.left[0]))
call s:assert.match(s:hi('LightLineLeft_normal_1'), 'E411: highlight group not found\|cleared')
call s:assert.match(s:hi('LightLineRight_normal_0'), s:pattern(palette.normal.right[0]))
call s:assert.match(s:hi('LightLineRight_normal_1'), 'E411: highlight group not found\|cleared')
call s:assert.match(s:hi('LightLineMiddle_normal'), s:pattern(palette.normal.middle[0]))
endfunction
function! s:suite.subseparator() function! s:suite.subseparator()
let g:lightline = { let g:lightline = {
\ 'active': { \ 'active': {

View file

@ -280,7 +280,7 @@ function! s:findAndRevealPath()
else else
call g:NERDTree.CursorToTreeWin() call g:NERDTree.CursorToTreeWin()
endif endif
call b:NERDTree.setShowHidden(g:NERDTreeShowHidden) call b:NERDTree.ui.setShowHidden(g:NERDTreeShowHidden)
call s:chRoot(g:NERDTreeDirNode.New(p.getParent(), b:NERDTree)) call s:chRoot(g:NERDTreeDirNode.New(p.getParent(), b:NERDTree))
else else
if !g:NERDTree.IsOpen() if !g:NERDTree.IsOpen()

View file

@ -37,13 +37,19 @@ function! syntastic#util#system(command) abort " {{{2
let $LC_MESSAGES = 'C' let $LC_MESSAGES = 'C'
let $LC_ALL = '' let $LC_ALL = ''
let cmd_start = reltime()
let out = system(a:command) let out = system(a:command)
let cmd_time = split(reltimestr(reltime(cmd_start)))[0]
let $LC_ALL = old_lc_all let $LC_ALL = old_lc_all
let $LC_MESSAGES = old_lc_messages let $LC_MESSAGES = old_lc_messages
let &shell = old_shell let &shell = old_shell
if exists('g:_SYNTASTIC_DEBUG_TRACE')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'system: command run in ' . cmd_time . 's')
endif
return out return out
endfunction " }}}2 endfunction " }}}2

View file

@ -19,7 +19,7 @@ if has('reltime')
lockvar! g:_SYNTASTIC_START lockvar! g:_SYNTASTIC_START
endif endif
let g:_SYNTASTIC_VERSION = '3.7.0-137' let g:_SYNTASTIC_VERSION = '3.7.0-144'
lockvar g:_SYNTASTIC_VERSION lockvar g:_SYNTASTIC_VERSION
" Sanity checks {{{1 " Sanity checks {{{1
@ -522,7 +522,7 @@ function! SyntasticMake(options) abort " {{{2
let env_save = {} let env_save = {}
if has_key(a:options, 'env') && len(a:options['env']) if has_key(a:options, 'env') && len(a:options['env'])
for key in keys(a:options['env']) for key in keys(a:options['env'])
if key =~? '\m^[a-z_]\+$' if key =~? '\m^[a-z_][a-z0-9_]*$'
execute 'let env_save[' . string(key) . '] = $' . key execute 'let env_save[' . string(key) . '] = $' . key
execute 'let $' . key . ' = ' . string(a:options['env'][key]) execute 'let $' . key . ' = ' . string(a:options['env'][key])
endif endif

View file

@ -91,6 +91,7 @@ function! g:SyntasticChecker.getExecEscaped() abort " {{{2
endfunction " }}}2 endfunction " }}}2
function! g:SyntasticChecker.getLocListRaw() abort " {{{2 function! g:SyntasticChecker.getLocListRaw() abort " {{{2
let checker_start = reltime()
let name = self._filetype . '/' . self._name let name = self._filetype . '/' . self._name
if has_key(self, '_enable') if has_key(self, '_enable')
@ -128,6 +129,8 @@ function! g:SyntasticChecker.getLocListRaw() abort " {{{2
call self._populateHighlightRegexes(list) call self._populateHighlightRegexes(list)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, name . ' raw:', list) call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, name . ' raw:', list)
call self._quietMessages(list) call self._quietMessages(list)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE,
\ 'getLocList: checker ' . name . ' run in ' . split(reltimestr(reltime(checker_start)))[0] . 's')
return list return list
endfunction " }}}2 endfunction " }}}2

View file

@ -28,7 +28,9 @@ endfunction
function! SyntaxCheckers_ansible_ansible_lint_GetLocList() dict function! SyntaxCheckers_ansible_ansible_lint_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args_after': '-p' }) let makeprg = self.makeprgBuild({ 'args_after': '-p' })
let errorformat = '%f:%l: [ANSIBLE%n] %m' let errorformat =
\ '%f:%l: [EANSIBLE%n] %m,' .
\ '%f:%l: [ANSIBLE%n] %m'
let env = syntastic#util#isRunningWindows() ? {} : { 'TERM': 'dumb' } let env = syntastic#util#isRunningWindows() ? {} : { 'TERM': 'dumb' }

View file

@ -10,19 +10,41 @@ if exists('g:loaded_syntastic_cuda_nvcc_checker')
endif endif
let g:loaded_syntastic_cuda_nvcc_checker = 1 let g:loaded_syntastic_cuda_nvcc_checker = 1
if !exists('g:syntastic_cuda_config_file')
let g:syntastic_cuda_config_file = '.syntastic_cuda_config'
endif
let s:save_cpo = &cpo let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_cuda_nvcc_GetLocList() dict function! SyntaxCheckers_cuda_nvcc_GetLocList() dict
if syntastic#util#var('cuda_arch') !=# '' let arch_flag = syntastic#util#var('cuda_arch')
let arch_flag = '-arch=' . g:syntastic_cuda_arch if arch_flag !=# ''
else let arch_flag = '-arch=' . arch_flag
let arch_flag = '' call syntastic#log#oneTimeWarn('variable g:syntastic_cuda_arch is deprecated, ' .
\ 'please add ' . string(arch_flag) . ' to g:syntastic_cuda_nvcc_args instead')
endif endif
let makeprg =
\ self.getExecEscaped() . ' ' . arch_flag . let build_opts = {}
\ ' --cuda -O0 -I . -Xcompiler -fsyntax-only ' . let dummy = ''
\ syntastic#util#shexpand('%') . ' ' . syntastic#c#NullOutput() if index(['h', 'hpp', 'cuh'], expand('%:e', 1), 0, 1) >= 0
if syntastic#util#var('cuda_check_header', 0)
let dummy = expand('%:p:h', 1) . syntastic#util#Slash() . '.syntastic_dummy.cu'
let build_opts = {
\ 'exe_before': 'echo > ' . syntastic#util#shescape(dummy) . ' ;',
\ 'fname_before': '.syntastic_dummy.cu -include' }
else
return []
endif
endif
call extend(build_opts, {
\ 'args_before': arch_flag . ' --cuda -O0 -I .',
\ 'args': syntastic#c#ReadConfig(g:syntastic_cuda_config_file),
\ 'args_after': '-Xcompiler -fsyntax-only',
\ 'tail_after': syntastic#c#NullOutput() })
let makeprg = self.makeprgBuild(build_opts)
let errorformat = let errorformat =
\ '%*[^"]"%f"%*\D%l: %m,'. \ '%*[^"]"%f"%*\D%l: %m,'.
@ -40,19 +62,13 @@ function! SyntaxCheckers_cuda_nvcc_GetLocList() dict
\ '%DMaking %*\a in %f,'. \ '%DMaking %*\a in %f,'.
\ '%f|%l| %m' \ '%f|%l| %m'
if index(['h', 'hpp', 'cuh'], expand('%:e', 1), 0, 1) >= 0 let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat })
if syntastic#util#var('cuda_check_header', 0)
let makeprg = if dummy !=# ''
\ 'echo > .syntastic_dummy.cu ; ' . call delete(dummy)
\ self.getExecEscaped() . ' ' . arch_flag .
\ ' --cuda -O0 -I . .syntastic_dummy.cu -Xcompiler -fsyntax-only -include ' .
\ syntastic#util#shexpand('%') . ' ' . syntastic#c#NullOutput()
else
return []
endif
endif endif
return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) return loclist
endfunction endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -0,0 +1,23 @@
"============================================================================
"File: eslint.vim
"Description: Syntax checking plugin for syntastic
"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_html_eslint_checker')
finish
endif
let g:loaded_syntastic_html_eslint_checker = 1
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'html',
\ 'name': 'eslint',
\ 'redirect': 'javascript/eslint'})
" vim: set sw=4 sts=4 et fdm=marker:

View file

@ -42,7 +42,8 @@ endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'racket', \ 'filetype': 'racket',
\ 'name': 'racket'}) \ 'name': 'racket',
\ 'enable': 'enable_racket_racket_checker' })
let &cpo = s:save_cpo let &cpo = s:save_cpo
unlet s:save_cpo unlet s:save_cpo

View file

@ -1,25 +1,57 @@
## 1.7 (unreleased) ## 1.8 (unplanned)
IMPROVEMENTS:
* `:GoDoc` accepts arguments now which are passed directly to `godoc`. So usages like `:GoDoc flag` works again (it was changed in previous versions [gh-894]
BUG FIXES:
* Escape `#` characters when opening URL's, as it's handled as alternative file in vim [gh-895]
* Fix typos in `doc/vim-go.txt` about usages of syntax highglightings [gh-897]
## 1.7.1 (June 7, 2016)
BUG FIXES:
* Fixed typo in `syntax/go.vim` file from `go:go_highlight_fields` to `g:go_highlight_fields`
## 1.7 (June 7, 2016)
FEATURES: FEATURES:
* New **`:GoImpl`** command that generates method stubs for implementing an interface. Checkout the [demo](https://twitter.com/fatih/status/729991365581545472) to see how it works. [gh-846] * New **`:GoImpl`** command that generates method stubs for implementing an interface. Checkout the [demo](https://twitter.com/fatih/status/729991365581545472) to see how it works. [gh-846]
* `godef` support is added back as an optional setting. By default `:GoDef` still uses `guru`, but can be changed to `godef` by adding the option: `let g:go_def_mode = 'godef'` [gh-888]
* New `<C-w><C-]>` and `<C-w>]>` shortcuts to split current window and jumpt to the identifier under cursor. [gh-838] * New `<C-w><C-]>` and `<C-w>]>` shortcuts to split current window and jumpt to the identifier under cursor. [gh-838]
* New syntax setting" `g:go_highlight_fields` that highlights struct field references [gh-854]
IMPROVEMENTS: IMPROVEMENTS:
* Invoking `:GoRename` now reloads all files to reflect new changes automatically [gh-855]
* Calling `:GoTestCompile` does not create any temporary binary file anymore [gh-879]
* Enable passing the `-tags` flag to `:GoDef`. Now you can pass build tags to `:GoDef` via `:GoGuruTags` or `g:go_guru_tags` * Enable passing the `-tags` flag to `:GoDef`. Now you can pass build tags to `:GoDef` via `:GoGuruTags` or `g:go_guru_tags`
* Internal refactoring to use custom `system()` function that wraps both the standard `system()` call and `vimproc`. Now all system calls will take advantage and will use `vimproc` if installed. [gh-801] * Internal refactoring to use custom `system()` function that wraps both the standard `system()` call and `vimproc`. Now all system calls will take advantage and will use `vimproc` if installed. [gh-801]
* Completion enables now `gocode`'s `autobuild` and `propose-builtins` flags automatically. With these settings packages will be automatically build to get the freshest completion candidates and builtin keywords will be showed as well. By defaults these settings are enabled. Settings can be disabled/enabled via `g:go_gocode_autobuild` and `g:go_gocode_propose_builtins`. [gh-815]
* Added new `http.HandlerFunc` snippets with `hf` and `hhf` shortcuts [gh-816] * Added new `http.HandlerFunc` snippets with `hf` and `hhf` shortcuts [gh-816]
* Added new `Example` and `Benchmark` snippets with `example` and `benchmark` shortcuts [gh-836] * Added new `Example` and `Benchmark` snippets with `example` and `benchmark` shortcuts [gh-836]
* Search tool binaries first in `GOBIN` and then in `PATH` as most of vim-go users installs it to `GOBIN` mostly [gh-823] * Search tool binaries first in `GOBIN` and then in `PATH` as most of vim-go users installs it to `GOBIN` mostly [gh-823]
* Improve `guru` based commands by providing automatically detected GOPATHS, such as `gb`, `godep` to be used if possible [gh-861]
* Add `<Plug>(go-imports)` mapping to make it assignable to other keys [gh-878]
* Increase compatibility with tcsh [gh-869]
* Improve `:GoInstallBinaries` for GOPATH's which don't have packages that work well with `go get -u`. We have a new `g:go_get_update` setting to disable it. By default it's enabled. [gh-883]
BUG FIXES: BUG FIXES:
* Fix `(go-freevars)` plug mapping to work as in visual mode instead of noncompatible normal mode [gh-832] * Fix `(go-freevars)` plug mapping to work as in visual mode instead of noncompatible normal mode [gh-832]
* Commands based on guru now shows a more meaningful error message instead of just showing the exit status (-1) * Commands based on guru now shows a more meaningful error message instead of just showing the exit status (-1)
* Fix `:GoCoverage` accidently enabling syntax highlighting for users who don't use syntax (i.e syntax off) [gh-827] * Fix `:GoCoverage` accidently enabling syntax highlighting for users who don't use syntax (i.e syntax off) [gh-827]
* Fix `:GoCoverage` colors to work for xterm as well [gh-863]
* Fix commenting out block of texts for Go templates (filetype gothtmltmpl) [gh-813] * Fix commenting out block of texts for Go templates (filetype gothtmltmpl) [gh-813]
* Fix `:GoImplements` failing because of an empty scope definition. Now we default to current package to make it usable. * Fix `:GoImplements` failing because of an empty scope definition. Now we default to current package to make it usable.
* Fix `:GoPlay` posting to non HTTPS url. [gh-847] * Fix `:GoPlay` posting to non HTTPS url. [gh-847]
* Fix escaping the filenames for lint and motion commands [gh-862]
* Fix escaping the filename to `:GoDef` completely for tcsh [gh-868]
* Fix showing SUCCESS for `go test` related commands if no test files are available [gh-859]

View file

@ -52,7 +52,7 @@ disabled/enabled easily.
## Install ## Install
Master branch is supposed to be a development branch. So stuff here can break and change. Master branch is supposed to be a development branch. So stuff here can break and change.
Please try use always the [latest release](https://github.com/fatih/vim-go/releases/latest) Please try use always the [latest release](https://github.com/fatih/vim-go/releases/latest)
Vim-go follows the standard runtime path structure, so I highly recommend to Vim-go follows the standard runtime path structure, so I highly recommend to
@ -180,6 +180,7 @@ To change it:
```vim ```vim
let g:go_highlight_functions = 1 let g:go_highlight_functions = 1
let g:go_highlight_methods = 1 let g:go_highlight_methods = 1
let g:go_highlight_fields = 1
let g:go_highlight_structs = 1 let g:go_highlight_structs = 1
let g:go_highlight_interfaces = 1 let g:go_highlight_interfaces = 1
let g:go_highlight_operators = 1 let g:go_highlight_operators = 1
@ -218,6 +219,11 @@ let g:go_bin_path = expand("~/.gotools")
let g:go_bin_path = "/home/fatih/.mypath" "or give absolute path let g:go_bin_path = "/home/fatih/.mypath" "or give absolute path
``` ```
Disable updating dependencies when installing/updating binaries:
```vim
let g:go_get_update = 0
```
### Using with Neovim (beta) ### Using with Neovim (beta)
Note: Neovim currently is not a first class citizen for vim-go. You are free Note: Neovim currently is not a first class citizen for vim-go. You are free

View file

@ -191,12 +191,14 @@ function! go#cmd#Test(bang, compile, ...)
" don't run the test, only compile it. Useful to capture and fix errors or " don't run the test, only compile it. Useful to capture and fix errors or
" to create a test binary. " to create a test binary.
if a:compile if a:compile
call add(args, "-c") let compile_file = "vim-go-test-compile"
call extend(args, ["-c", "-o", compile_file])
endif endif
if a:0 if a:0
" expand all wildcards(i.e: '%' to the current file name) " expand all wildcards(i.e: '%' to the current file name)
let goargs = map(copy(a:000), "expand(v:val)") let goargs = map(copy(a:000), "expand(v:val)")
let goargs = go#util#Shelllist(goargs, 1)
call extend(args, goargs, 1) call extend(args, goargs, 1)
else else
@ -217,6 +219,11 @@ function! go#cmd#Test(bang, compile, ...)
else else
let id = go#jobcontrol#Spawn(a:bang, "test", args) let id = go#jobcontrol#Spawn(a:bang, "test", args)
endif endif
if a:compile
call go#jobcontrol#AddHandler(function('s:test_compile_handler'))
let s:test_compile_handlers[id] = compile_file
endif
return id return id
endif endif
@ -229,6 +236,10 @@ function! go#cmd#Test(bang, compile, ...)
let l:listtype = "quickfix" let l:listtype = "quickfix"
if a:compile
call delete(compile_file)
endif
if go#util#ShellError() != 0 if go#util#ShellError() != 0
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd() let dir = getcwd()
@ -332,4 +343,19 @@ function! go#cmd#Generate(bang, ...)
let $GOPATH = old_gopath let $GOPATH = old_gopath
endfunction endfunction
" -----------------------
" | Neovim job handlers |
" -----------------------
let s:test_compile_handlers = {}
function! s:test_compile_handler(job, exit_status, data)
if !has_key(s:test_compile_handlers, a:job.id)
return
endif
let l:compile_file = s:test_compile_handlers[a:job.id]
call delete(l:compile_file)
unlet s:test_compile_handlers[a:job.id]
endfunction
" vim:ts=4:sw=4:et " vim:ts=4:sw=4:et

View file

@ -1,9 +1,4 @@
if !exists("g:go_gocode_bin") function! s:gocodeCurrentBuffer()
let g:go_gocode_bin = "gocode"
endif
fu! s:gocodeCurrentBuffer()
let buf = getline(1, '$') let buf = getline(1, '$')
if &encoding != 'utf-8' if &encoding != 'utf-8'
let buf = map(buf, 'iconv(v:val, &encoding, "utf-8")') let buf = map(buf, 'iconv(v:val, &encoding, "utf-8")')
@ -17,9 +12,9 @@ fu! s:gocodeCurrentBuffer()
call writefile(buf, file) call writefile(buf, file)
return file return file
endf endfunction
fu! s:gocodeCommand(cmd, preargs, args) function! s:gocodeCommand(cmd, preargs, args)
for i in range(0, len(a:args) - 1) for i in range(0, len(a:args) - 1)
let a:args[i] = go#util#Shellescape(a:args[i]) let a:args[i] = go#util#Shellescape(a:args[i])
endfor endfor
@ -27,7 +22,7 @@ fu! s:gocodeCommand(cmd, preargs, args)
let a:preargs[i] = go#util#Shellescape(a:preargs[i]) let a:preargs[i] = go#util#Shellescape(a:preargs[i])
endfor endfor
let bin_path = go#path#CheckBinPath(g:go_gocode_bin) let bin_path = go#path#CheckBinPath("gocode")
if empty(bin_path) if empty(bin_path)
return return
endif endif
@ -49,20 +44,43 @@ fu! s:gocodeCommand(cmd, preargs, args)
endif endif
return result return result
endif endif
endf endfunction
fu! s:gocodeCurrentBufferOpt(filename) function! s:gocodeCurrentBufferOpt(filename)
return '-in=' . a:filename return '-in=' . a:filename
endf endfunction
let s:optionsEnabled = 0
function! s:gocodeEnableOptions()
if s:optionsEnabled
return
endif
let bin_path = go#path#CheckBinPath("gocode")
if empty(bin_path)
return
endif
let s:optionsEnabled = 1
call go#util#System(printf('%s set propose-builtins %s', go#util#Shellescape(bin_path), s:toBool(get(g:, 'go_gocode_propose_builtins', 1))))
call go#util#System(printf('%s set autobuild %s', go#util#Shellescape(bin_path), s:toBool(get(g:, 'go_gocode_autobuild', 1))))
endfunction
function! s:toBool(val)
if a:val | return 'true ' | else | return 'false' | endif
endfunction
function! s:gocodeAutocomplete()
call s:gocodeEnableOptions()
fu! s:gocodeAutocomplete()
let filename = s:gocodeCurrentBuffer() let filename = s:gocodeCurrentBuffer()
let result = s:gocodeCommand('autocomplete', let result = s:gocodeCommand('autocomplete',
\ [s:gocodeCurrentBufferOpt(filename), '-f=vim'], \ [s:gocodeCurrentBufferOpt(filename), '-f=vim'],
\ [expand('%:p'), go#util#OffsetCursor()]) \ [expand('%:p'), go#util#OffsetCursor()])
call delete(filename) call delete(filename)
return result return result
endf endfunction
function! go#complete#GetInfo() function! go#complete#GetInfo()
let offset = go#util#OffsetCursor()+1 let offset = go#util#OffsetCursor()+1
@ -120,7 +138,7 @@ function! s:trim_bracket(val)
return a:val return a:val
endfunction endfunction
fu! go#complete#Complete(findstart, base) function! go#complete#Complete(findstart, base)
"findstart = 1 when we need to get the text length "findstart = 1 when we need to get the text length
if a:findstart == 1 if a:findstart == 1
execute "silent let g:gocomplete_completions = " . s:gocodeAutocomplete() execute "silent let g:gocomplete_completions = " . s:gocodeAutocomplete()

View file

@ -28,6 +28,19 @@ function! go#coverage#Buffer(bang, ...)
return -1 return -1
endif endif
" check if there is any test file, if not we just return
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd . fnameescape(expand("%:p:h"))
if empty(glob("*_test.go"))
call go#util#EchoError("no tests files available")
return
endif
finally
execute cd . fnameescape(dir)
endtry
let s:toggle = 1 let s:toggle = 1
let l:tmpname = tempname() let l:tmpname = tempname()
let args = [a:bang, 0, "-coverprofile", l:tmpname] let args = [a:bang, 0, "-coverprofile", l:tmpname]
@ -221,9 +234,9 @@ function! go#coverage#overlay(file)
endfor endfor
syntax manual syntax manual
highlight normaltext term=bold ctermfg=59 guifg=#75715E highlight normaltext term=bold ctermfg=darkgrey guifg=#75715E
highlight covered term=bold ctermfg=118 guifg=#A6E22E highlight covered term=bold ctermfg=green guifg=#A6E22E
highlight uncover term=bold ctermfg=197 guifg=#F92672 highlight uncover term=bold ctermfg=red guifg=#F92672
" clear the matches if we leave the buffer " clear the matches if we leave the buffer
autocmd BufWinLeave <buffer> call go#coverage#Clear() autocmd BufWinLeave <buffer> call go#coverage#Clear()

View file

@ -2,201 +2,227 @@ let s:go_stack = []
let s:go_stack_level = 0 let s:go_stack_level = 0
function! go#def#Jump(mode) function! go#def#Jump(mode)
let bin_path = go#path#CheckBinPath("guru") let old_gopath = $GOPATH
if empty(bin_path) let $GOPATH = go#path#Detect()
return
endif
let old_gopath = $GOPATH let fname = fnamemodify(expand("%"), ':p:gs?\\?/?')
let $GOPATH = go#path#Detect()
let flags = "" " so guru right now is slow for some people. previously we were using
if exists('g:go_guru_tags') " godef which also has it's own quirks. But this issue come up so many
let tags = get(g:, 'go_guru_tags') " times I've decided to support both. By default we still use guru as it
let flags = printf(" -tags %s", tags) " covers all edge cases, but now anyone can switch to godef if they wish
endif let bin_name = get(g:, 'go_def_mode', 'guru')
if bin_name == 'godef'
let bin_path = go#path#CheckBinPath("godef")
if empty(bin_path)
let $GOPATH = old_gopath
return
endif
let command = printf("%s -f=%s -o=%s -t", bin_path, fname, go#util#OffsetCursor())
let out = go#util#System(command)
let fname = fnamemodify(expand("%"), ':p:gs?\\?/?') " append the type information to the same line so our
let command = printf("%s %s definition %s:#%s", bin_path, flags, shellescape(fname), go#util#OffsetCursor()) " jump_to_declaration() function can parse it. This makes it
" compatible with guru definition as well too
let out = join(split(out, '\n'), ':')
elseif bin_name == 'guru'
let bin_path = go#path#CheckBinPath("guru")
if empty(bin_path)
let $GOPATH = old_gopath
return
endif
let out = go#util#System(command) let flags = ""
if go#util#ShellError() != 0 if exists('g:go_guru_tags')
call go#util#EchoError(out) let tags = get(g:, 'go_guru_tags')
return let flags = printf(" -tags %s", tags)
endif endif
call s:jump_to_declaration(out, a:mode) let fname = shellescape(fname.':#'.go#util#OffsetCursor())
let $GOPATH = old_gopath let command = printf("%s %s definition %s", bin_path, flags, fname)
let out = go#util#System(command)
else
call go#util#EchoError('go_def_mode value: '. bin_name .' is not valid. Valid values are: [godef, guru]')
return
endif
if go#util#ShellError() != 0
call go#util#EchoError(out)
return
endif
call s:jump_to_declaration(out, a:mode)
let $GOPATH = old_gopath
endfunction endfunction
function! s:jump_to_declaration(out, mode) function! s:jump_to_declaration(out, mode)
" strip line ending " strip line ending
let out = split(a:out, go#util#LineEnding())[0] let out = split(a:out, go#util#LineEnding())[0]
if go#util#IsWin() if go#util#IsWin()
let parts = split(out, '\(^[a-zA-Z]\)\@<!:') let parts = split(out, '\(^[a-zA-Z]\)\@<!:')
else else
let parts = split(out, ':') let parts = split(out, ':')
endif endif
let filename = parts[0] let filename = parts[0]
let line = parts[1] let line = parts[1]
let col = parts[2] let col = parts[2]
let ident = parts[3] let ident = parts[3]
" Remove anything newer than the current position, just like basic " Remove anything newer than the current position, just like basic
" vim tag support " vim tag support
if s:go_stack_level == 0 if s:go_stack_level == 0
let s:go_stack = [] let s:go_stack = []
else else
let s:go_stack = s:go_stack[0:s:go_stack_level-1] let s:go_stack = s:go_stack[0:s:go_stack_level-1]
endif endif
" increment the stack counter " increment the stack counter
let s:go_stack_level += 1 let s:go_stack_level += 1
" push it on to the jumpstack " push it on to the jumpstack
let stack_entry = {'line': line("."), 'col': col("."), 'file': expand('%:p'), 'ident': ident} let stack_entry = {'line': line("."), 'col': col("."), 'file': expand('%:p'), 'ident': ident}
call add(s:go_stack, stack_entry) call add(s:go_stack, stack_entry)
" needed for restoring back user setting this is because there are two " needed for restoring back user setting this is because there are two
" modes of switchbuf which we need based on the split mode " modes of switchbuf which we need based on the split mode
let old_switchbuf = &switchbuf let old_switchbuf = &switchbuf
" jump to existing buffer if, 1. we have enabled it, 2. the buffer is loaded " jump to existing buffer if, 1. we have enabled it, 2. the buffer is loaded
" and 3. there is buffer window number we switch to " and 3. there is buffer window number we switch to
if get(g:, 'go_def_reuse_buffer', 0) && bufloaded(filename) != 0 && bufwinnr(filename) != -1 if get(g:, 'go_def_reuse_buffer', 0) && bufloaded(filename) != 0 && bufwinnr(filename) != -1
" jumpt to existing buffer if it exists " jumpt to existing buffer if it exists
execute bufwinnr(filename) . 'wincmd w' execute bufwinnr(filename) . 'wincmd w'
elseif a:mode == "tab" elseif a:mode == "tab"
let &switchbuf = "usetab" let &switchbuf = "usetab"
if bufloaded(filename) == 0 if bufloaded(filename) == 0
tab split tab split
endif endif
elseif a:mode == "split" elseif a:mode == "split"
split split
elseif a:mode == "vsplit" elseif a:mode == "vsplit"
vsplit vsplit
endif endif
" open the file and jump to line and column " open the file and jump to line and column
exec 'edit '.filename exec 'edit '.filename
call cursor(line, col) call cursor(line, col)
" also align the line to middle of the view " also align the line to middle of the view
normal! zz normal! zz
let &switchbuf = old_switchbuf let &switchbuf = old_switchbuf
endfunction endfunction
function! go#def#SelectStackEntry() function! go#def#SelectStackEntry()
let target_window = go#ui#GetReturnWindow() let target_window = go#ui#GetReturnWindow()
if empty(target_window) if empty(target_window)
let target_window = winnr() let target_window = winnr()
endif endif
let highlighted_stack_entry = matchstr(getline("."), '^..\zs\(\d\+\)') let highlighted_stack_entry = matchstr(getline("."), '^..\zs\(\d\+\)')
if !empty(highlighted_stack_entry) if !empty(highlighted_stack_entry)
execute target_window . "wincmd w" execute target_window . "wincmd w"
call go#def#Stack(str2nr(highlighted_stack_entry)) call go#def#Stack(str2nr(highlighted_stack_entry))
endif endif
call go#ui#CloseWindow() call go#ui#CloseWindow()
endfunction endfunction
function! go#def#StackUI() function! go#def#StackUI()
if len(s:go_stack) == 0 if len(s:go_stack) == 0
call go#util#EchoError("godef stack empty") call go#util#EchoError("godef stack empty")
return return
endif endif
let stackOut = ['" <Up>,<Down>:navigate <Enter>:jump <Esc>,q:exit'] let stackOut = ['" <Up>,<Down>:navigate <Enter>:jump <Esc>,q:exit']
let i = 0 let i = 0
while i < len(s:go_stack) while i < len(s:go_stack)
let entry = s:go_stack[i] let entry = s:go_stack[i]
let prefix = "" let prefix = ""
if i == s:go_stack_level if i == s:go_stack_level
let prefix = ">" let prefix = ">"
else else
let prefix = " " let prefix = " "
endif endif
call add(stackOut, printf("%s %d %s|%d col %d|%s", call add(stackOut, printf("%s %d %s|%d col %d|%s",
\ prefix, i+1, entry["file"], entry["line"], entry["col"], entry["ident"])) \ prefix, i+1, entry["file"], entry["line"], entry["col"], entry["ident"]))
let i += 1 let i += 1
endwhile endwhile
if s:go_stack_level == i if s:go_stack_level == i
call add(stackOut, "> ") call add(stackOut, "> ")
endif endif
call go#ui#OpenWindow("GoDef Stack", stackOut, "godefstack") call go#ui#OpenWindow("GoDef Stack", stackOut, "godefstack")
noremap <buffer> <silent> <CR> :<C-U>call go#def#SelectStackEntry()<CR> noremap <buffer> <silent> <CR> :<C-U>call go#def#SelectStackEntry()<CR>
noremap <buffer> <silent> <Esc> :<C-U>call go#ui#CloseWindow()<CR> noremap <buffer> <silent> <Esc> :<C-U>call go#ui#CloseWindow()<CR>
noremap <buffer> <silent> q :<C-U>call go#ui#CloseWindow()<CR> noremap <buffer> <silent> q :<C-U>call go#ui#CloseWindow()<CR>
endfunction endfunction
function! go#def#StackClear(...) function! go#def#StackClear(...)
let s:go_stack = [] let s:go_stack = []
let s:go_stack_level = 0 let s:go_stack_level = 0
endfunction endfunction
function! go#def#StackPop(...) function! go#def#StackPop(...)
if len(s:go_stack) == 0 if len(s:go_stack) == 0
call go#util#EchoError("godef stack empty") call go#util#EchoError("godef stack empty")
return return
endif endif
if s:go_stack_level == 0 if s:go_stack_level == 0
call go#util#EchoError("at bottom of the godef stack") call go#util#EchoError("at bottom of the godef stack")
return return
endif endif
if !len(a:000) if !len(a:000)
let numPop = 1 let numPop = 1
else else
let numPop = a:1 let numPop = a:1
endif endif
let newLevel = str2nr(s:go_stack_level) - str2nr(numPop) let newLevel = str2nr(s:go_stack_level) - str2nr(numPop)
call go#def#Stack(newLevel + 1) call go#def#Stack(newLevel + 1)
endfunction endfunction
function! go#def#Stack(...) function! go#def#Stack(...)
if len(s:go_stack) == 0 if len(s:go_stack) == 0
call go#util#EchoError("godef stack empty") call go#util#EchoError("godef stack empty")
return return
endif endif
if !len(a:000) if !len(a:000)
" Display interactive stack " Display interactive stack
call go#def#StackUI() call go#def#StackUI()
return return
else else
let jumpTarget = a:1 let jumpTarget = a:1
endif endif
if jumpTarget !~ '^\d\+$' if jumpTarget !~ '^\d\+$'
if jumpTarget !~ '^\s*$' if jumpTarget !~ '^\s*$'
call go#util#EchoError("location must be a number") call go#util#EchoError("location must be a number")
endif endif
return return
endif endif
let jumpTarget = str2nr(jumpTarget) - 1 let jumpTarget = str2nr(jumpTarget) - 1
if jumpTarget >= 0 && jumpTarget < len(s:go_stack) if jumpTarget >= 0 && jumpTarget < len(s:go_stack)
let s:go_stack_level = jumpTarget let s:go_stack_level = jumpTarget
let target = s:go_stack[s:go_stack_level] let target = s:go_stack[s:go_stack_level]
" jump " jump
exec 'edit '.target["file"] exec 'edit '.target["file"]
call cursor(target["line"], target["col"]) call cursor(target["line"], target["col"])
normal! zz normal! zz
else else
call go#util#EchoError("invalid location. Try :GoDefStack to see the list of valid entries") call go#util#EchoError("invalid location. Try :GoDefStack to see the list of valid entries")
endif endif
endfunction endfunction

View file

@ -77,17 +77,28 @@ function! go#doc#OpenBrowser(...)
endfunction endfunction
function! go#doc#Open(newmode, mode, ...) function! go#doc#Open(newmode, mode, ...)
" check if we have 'gogetdoc' and use it automatically if len(a:000)
let bin_path = go#path#CheckBinPath('gogetdoc') " check if we have 'godoc' and use it automatically
if empty(bin_path) let bin_path = go#path#CheckBinPath('godoc')
return if empty(bin_path)
return
endif
let command = printf("%s %s", bin_path, join(a:000, ' '))
else
" check if we have 'gogetdoc' and use it automatically
let bin_path = go#path#CheckBinPath('gogetdoc')
if empty(bin_path)
return
endif
let offset = go#util#OffsetCursor()
let fname = expand("%:p:gs!\\!/!")
let pos = shellescape(fname.':#'.offset)
let command = printf("%s -pos %s", bin_path, pos)
endif endif
let offset = go#util#OffsetCursor()
let fname = expand("%:p")
let command = printf("%s -pos %s:#%s", bin_path, fname, offset)
let out = go#util#System(command) let out = go#util#System(command)
if go#util#ShellError() != 0 if go#util#ShellError() != 0
call go#util#EchoError(out) call go#util#EchoError(out)
@ -134,6 +145,7 @@ function! s:GodocView(newposition, position, content)
call append(0, split(a:content, "\n")) call append(0, split(a:content, "\n"))
sil $delete _ sil $delete _
setlocal nomodifiable setlocal nomodifiable
sil normal! gg
" close easily with <esc> or enter " close easily with <esc> or enter
noremap <buffer> <silent> <CR> :<C-U>close<CR> noremap <buffer> <silent> <CR> :<C-U>close<CR>

View file

@ -87,7 +87,7 @@ function! go#fmt#Format(withGoimport)
" get the command first so we can test it " get the command first so we can test it
let fmt_command = g:go_fmt_command let fmt_command = g:go_fmt_command
if a:withGoimport == 1 if a:withGoimport == 1
let fmt_command = g:go_goimports_bin let fmt_command = g:go_goimports_bin
endif endif
@ -109,18 +109,15 @@ function! go#fmt#Format(withGoimport)
" populate the final command with user based fmt options " populate the final command with user based fmt options
let command = fmt_command . ' -w ' let command = fmt_command . ' -w '
if a:withGoimport != 1 if a:withGoimport != 1
let command = command . g:go_fmt_options let command = command . g:go_fmt_options
endif endif
if fmt_command == "goimports" if fmt_command == "goimports"
if !exists('b:goimports_vendor_compatible') if !exists('b:goimports_vendor_compatible')
let out = go#util#System("goimports --help") let out = go#util#System(bin_path . " --help")
if out !~ "-srcdir" if out !~ "-srcdir"
echohl WarningMsg call go#util#EchoWarning("vim-go: goimports does not support srcdir. update with: :GoUpdateBinaries")
echomsg "vim-go: goimports does not support srcdir."
echomsg " update with: :GoUpdateBinaries"
echohl None
else else
let b:goimports_vendor_compatible = 1 let b:goimports_vendor_compatible = 1
endif endif

View file

@ -74,7 +74,8 @@ func! s:RunGuru(mode, format, selected, needs_scope) range abort
endif endif
" this is our final command " this is our final command
let command .= printf(' %s %s:%s', a:mode, shellescape(filename), pos) let filename .= ':'.pos
let command .= printf(' %s %s', a:mode, shellescape(filename))
let old_gopath = $GOPATH let old_gopath = $GOPATH
let $GOPATH = go#path#Detect() let $GOPATH = go#path#Detect()

View file

@ -24,7 +24,7 @@ endif
function! go#lint#Gometa(autosave, ...) abort function! go#lint#Gometa(autosave, ...) abort
if a:0 == 0 if a:0 == 0
let goargs = expand('%:p:h') let goargs = shellescape(expand('%:p:h'))
else else
let goargs = go#util#Shelljoin(a:000) let goargs = go#util#Shelljoin(a:000)
endif endif

View file

@ -46,7 +46,7 @@ function! go#package#Paths()
let dirs += [s:goroot] let dirs += [s:goroot]
endif endif
let workspaces = split($GOPATH, go#util#PathListSep()) let workspaces = split(go#path#Detect(), go#util#PathListSep())
if workspaces != [] if workspaces != []
let dirs += workspaces let dirs += workspaces
endif endif

View file

@ -151,6 +151,9 @@ function! go#path#CheckBinPath(binpath)
" if it's in PATH just return it " if it's in PATH just return it
if executable(binpath) if executable(binpath)
if v:version == 704 && has('patch235')
let binpath = exepath(binpath)
endif
let $PATH = old_path let $PATH = old_path
return binpath return binpath
endif endif

View file

@ -36,6 +36,15 @@ function! go#rename#Rename(bang, ...)
let out = go#tool#ExecuteInDir(cmd) let out = go#tool#ExecuteInDir(cmd)
" reload all files to reflect the new changes. We explicitly call
" checktime to trigger a reload of all files. See
" http://www.mail-archive.com/vim@vim.org/msg05900.html for more info
" about the autoread bug
let current_autoread = &autoread
set autoread
silent! checktime
let &autoread = current_autoread
" strip out newline on the end that gorename puts. If we don't remove, it " strip out newline on the end that gorename puts. If we don't remove, it
" will trigger the 'Hit ENTER to continue' prompt " will trigger the 'Hit ENTER to continue' prompt
let clean = split(out, '\n') let clean = split(out, '\n')

View file

@ -16,7 +16,7 @@ endif
function! go#textobj#Function(mode) function! go#textobj#Function(mode)
let offset = go#util#OffsetCursor() let offset = go#util#OffsetCursor()
let fname = expand("%:p") let fname = shellescape(expand("%:p"))
if &modified if &modified
" Write current unsaved buffer to a temp file and use the modified content " Write current unsaved buffer to a temp file and use the modified content
let l:tmpname = tempname() let l:tmpname = tempname()
@ -103,7 +103,7 @@ function! go#textobj#FunctionJump(mode, direction)
let offset = go#util#OffsetCursor() let offset = go#util#OffsetCursor()
let fname = expand("%:p") let fname = shellescape(expand("%:p"))
if &modified if &modified
" Write current unsaved buffer to a temp file and use the modified content " Write current unsaved buffer to a temp file and use the modified content
let l:tmpname = tempname() let l:tmpname = tempname()

View file

@ -1,19 +1,21 @@
function! go#tool#Files() function! go#tool#Files()
if go#util#IsWin() if go#util#IsWin()
let command = 'go list -f "{{range $f := .GoFiles}}{{$.Dir}}\{{$f}}{{printf \"\n\"}}{{end}}{{range $f := .CgoFiles}}{{$.Dir}}\{{$f}}{{printf \"\n\"}}{{end}}"' let format = '{{range $f := .GoFiles}}{{$.Dir}}\{{$f}}{{printf \"\n\"}}{{end}}{{range $f := .CgoFiles}}{{$.Dir}}\{{$f}}{{printf \"\n\"}}{{end}}'
else else
let command = "go list -f '{{range $f := .GoFiles}}{{$.Dir}}/{{$f}}{{printf \"\\n\"}}{{end}}{{range $f := .CgoFiles}}{{$.Dir}}/{{$f}}{{printf \"\\n\"}}{{end}}'" let format = "{{range $f := .GoFiles}}{{$.Dir}}/{{$f}}{{printf \"\\n\"}}{{end}}{{range $f := .CgoFiles}}{{$.Dir}}/{{$f}}{{printf \"\\n\"}}{{end}}"
endif endif
let command = 'go list -f '.shellescape(format)
let out = go#tool#ExecuteInDir(command) let out = go#tool#ExecuteInDir(command)
return split(out, '\n') return split(out, '\n')
endfunction endfunction
function! go#tool#Deps() function! go#tool#Deps()
if go#util#IsWin() if go#util#IsWin()
let command = 'go list -f "{{range $f := .Deps}}{{$f}}{{printf \"\n\"}}{{end}}"' let format = '{{range $f := .Deps}}{{$f}}{{printf \"\n\"}}{{end}}'
else else
let command = "go list -f $'{{range $f := .Deps}}{{$f}}\n{{end}}'" let format = "{{range $f := .Deps}}{{$f}}\n{{end}}"
endif endif
let command = 'go list -f '.shellescape(format)
let out = go#tool#ExecuteInDir(command) let out = go#tool#ExecuteInDir(command)
return split(out, '\n') return split(out, '\n')
endfunction endfunction
@ -21,10 +23,11 @@ endfunction
function! go#tool#Imports() function! go#tool#Imports()
let imports = {} let imports = {}
if go#util#IsWin() if go#util#IsWin()
let command = 'go list -f "{{range $f := .Imports}}{{$f}}{{printf \"\n\"}}{{end}}"' let format = '{{range $f := .Imports}}{{$f}}{{printf \"\n\"}}{{end}}'
else else
let command = "go list -f $'{{range $f := .Imports}}{{$f}}\n{{end}}'" let format = "{{range $f := .Imports}}{{$f}}{{printf \"\\n\"}}{{end}}"
endif endif
let command = 'go list -f '.shellescape(format)
let out = go#tool#ExecuteInDir(command) let out = go#tool#ExecuteInDir(command)
if go#util#ShellError() != 0 if go#util#ShellError() != 0
echo out echo out
@ -32,7 +35,7 @@ function! go#tool#Imports()
endif endif
for package_path in split(out, '\n') for package_path in split(out, '\n')
let cmd = "go list -f {{.Name}} " . package_path let cmd = "go list -f '{{.Name}}' " . shellescape(package_path)
let package_name = substitute(go#tool#ExecuteInDir(cmd), '\n$', '', '') let package_name = substitute(go#tool#ExecuteInDir(cmd), '\n$', '', '')
let imports[package_name] = package_path let imports[package_name] = package_path
endfor endfor
@ -168,10 +171,10 @@ function! go#tool#OpenBrowser(url)
return return
endif endif
if cmd =~ '^!' if cmd =~ '^!'
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g') let cmd = substitute(cmd, '%URL%', '\=escape(shellescape(a:url),"#")', 'g')
silent! exec cmd silent! exec cmd
elseif cmd =~ '^:[A-Z]' elseif cmd =~ '^:[A-Z]'
let cmd = substitute(cmd, '%URL%', '\=a:url', 'g') let cmd = substitute(cmd, '%URL%', '\=escape(a:url,"#")', 'g')
exec cmd exec cmd
else else
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g') let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g')

View file

@ -87,7 +87,7 @@ function! go#ui#OpenDefinition(filter)
" don't touch our first line or any blank line " don't touch our first line or any blank line
if curline =~ a:filter || curline =~ "^$" if curline =~ a:filter || curline =~ "^$"
" supress information about calling this function " suppress information about calling this function
echo "" echo ""
return return
endif endif

View file

@ -439,7 +439,8 @@ CTRL-t
:GoInstallBinaries :GoInstallBinaries
Download and Install all necessary Go tool binaries such as `godef`, Download and Install all necessary Go tool binaries such as `godef`,
`goimports`, `gocode`, etc.. under `g:go_bin_path` `goimports`, `gocode`, etc.. under `g:go_bin_path`. Set |g:go_get_update|
to disable updating dependencies.
*:GoUpdateBinaries* *:GoUpdateBinaries*
:GoUpdateBinaries :GoUpdateBinaries
@ -630,6 +631,7 @@ CTRL-t
:GoImpl f *Foo io.Writer :GoImpl f *Foo io.Writer
:GoImpl T io.ReadWriteCloser :GoImpl T io.ReadWriteCloser
< <
=============================================================================== ===============================================================================
MAPPINGS *go-mappings* MAPPINGS *go-mappings*
@ -672,17 +674,14 @@ Calls `go build` for the current package
Calls `go generate` for the current package Calls `go generate` for the current package
*(go-info)* *(go-info)*
Shows type information for the word under the cursor Shows type information for the word under the cursor
*(go-install)* *(go-install)*
Calls `go install` for the current package Calls `go install` for the current package
*(go-test)* *(go-test)*
Calls `go test` for the current package Calls `go test` for the current package
@ -710,6 +709,10 @@ Calls `go test -coverprofile-temp.out` for the current package and shows the
coverage annotation. If run agains it acts as a toggle and clears the coverage annotation. If run agains it acts as a toggle and clears the
annotation. annotation.
*(go-imports)*
Calls `goimports` for the current package
*(go-vet)* *(go-vet)*
Calls `go vet` for the current package Calls `go vet` for the current package
@ -834,6 +837,11 @@ Alternates between the implementation and test code in a new horizontal split
Alternates between the implementation and test code in a new vertical split Alternates between the implementation and test code in a new vertical split
*(go-import)*
Calls `:GoImport` for the current package
=============================================================================== ===============================================================================
TEXT OBJECTS *go-text-objects* TEXT OBJECTS *go-text-objects*
@ -973,6 +981,14 @@ K , keywordprg shortcut. Usually this shortcut is set to use the program `man`.
In Go, using `godoc` is more idiomatic. Default is enabled. > In Go, using `godoc` is more idiomatic. Default is enabled. >
let g:go_doc_keywordprg_enabled = 1 let g:go_doc_keywordprg_enabled = 1
<
*'g:go_def_mode'*
Use this option to define the command to be used for |:GoDef|. By default
`guru` is being used as it covers all edge cases. But one might also use
`godef` as it's more faster. Current valid options are: `[guru, godef]` >
let g:go_def_mode = 'guru'
< <
*'g:go_def_mapping_enabled'* *'g:go_def_mapping_enabled'*
@ -1028,6 +1044,14 @@ is used. Use "neosnippet" for neosnippet.vim: >
let g:go_snippet_engine = "ultisnips" let g:go_snippet_engine = "ultisnips"
< <
*'g:go_get_update'*
Use this option to disable updating dependencies with |GoInstallBinaries|. By
default this is enabled.
>
let g:go_get_update = 1
<
*'g:go_guru_scope'* *'g:go_guru_scope'*
Use this option to define the scope of the analysis to be passed for guru Use this option to define the scope of the analysis to be passed for guru
@ -1098,7 +1122,13 @@ Highlights method names. By default it's disabled. >
Highlights struct names. By default it's disabled. > Highlights struct names. By default it's disabled. >
let g:go_highlight_structs = 0 let g:go_highlight_structs = 0
<
*'g:go_highlight_fields'*
Highlights field names. By default it's disabled. >
let g:go_highlight_fields = 0
< <
*'g:go_highlight_interfaces'* *'g:go_highlight_interfaces'*
@ -1243,10 +1273,24 @@ By default it is set to edit.
*g:go_gorename_prefill* *g:go_gorename_prefill*
Specifies whether |:GoRename| prefills the new identifier name with the Specifies whether |:GoRename| prefills the new identifier name with the
word under the cursor. By default is is enabled. word under the cursor. By default it is enabled.
> >
let g:go_gorename_prefill = 1 let g:go_gorename_prefill = 1
< <
*g:go_gocode_autobuild*
Specifies whether `gocode` should automatically build out-of-date packages
when their source fiels are modified, in order to obtahin the freshes
autocomplete results for them. By default it is enabled.
>
let g:go_gocode_autobuild = 1
<
*g:go_gocode_propose_builtins*
Specifies whether `gocode` should add built-in types, functions and constants
to an autocompletion proposals. By default it is enabled.
>
let g:go_gocode_propose_builtins = 1
=============================================================================== ===============================================================================

View file

@ -33,6 +33,7 @@ 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-deps) :<C-u>call go#tool#Deps()<CR>
nnoremap <silent> <Plug>(go-info) :<C-u>call go#complete#Info(0)<CR> nnoremap <silent> <Plug>(go-info) :<C-u>call go#complete#Info(0)<CR>
nnoremap <silent> <Plug>(go-import) :<C-u>call go#import#SwitchImport(1, '', expand('<cword>'), '')<CR> nnoremap <silent> <Plug>(go-import) :<C-u>call go#import#SwitchImport(1, '', expand('<cword>'), '')<CR>
nnoremap <silent> <Plug>(go-imports) :<C-u>call go#fmt#Format(1)<CR>
nnoremap <silent> <Plug>(go-implements) :<C-u>call go#guru#Implements(-1)<CR> nnoremap <silent> <Plug>(go-implements) :<C-u>call go#guru#Implements(-1)<CR>
nnoremap <silent> <Plug>(go-callees) :<C-u>call go#guru#Callees(-1)<CR> nnoremap <silent> <Plug>(go-callees) :<C-u>call go#guru#Callees(-1)<CR>

View file

@ -307,19 +307,17 @@ abbr if err != nil { t.Fatalf(...) }
} }
# test example # test example
snippet example snippet example
func Example${1:Method}() { func Example${1:Method}() {
${0} ${0}
// Output: // Output:
} }
endsnippet
# test benchmark # test benchmark
snippet benchmark snippet benchmark
func Benchmark${1:Method}(b *testing.B) { func Benchmark${1:Method}(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
${0} ${0}
}
} }
}
endsnippet
# variable declaration # variable declaration
snippet var snippet var
abbr var x Type [= ...] abbr var x Type [= ...]

View file

@ -8,11 +8,12 @@ let g:go_loaded_install = 1
" needed by the user with GoInstallBinaries " needed by the user with GoInstallBinaries
let s:packages = [ let s:packages = [
\ "github.com/nsf/gocode", \ "github.com/nsf/gocode",
\ "github.com/alecthomas/gometalinter", \ "github.com/alecthomas/gometalinter",
\ "golang.org/x/tools/cmd/goimports", \ "golang.org/x/tools/cmd/goimports",
\ "golang.org/x/tools/cmd/guru", \ "golang.org/x/tools/cmd/guru",
\ "golang.org/x/tools/cmd/gorename", \ "golang.org/x/tools/cmd/gorename",
\ "github.com/golang/lint/golint", \ "github.com/golang/lint/golint",
\ "github.com/rogpeppe/godef",
\ "github.com/kisielk/errcheck", \ "github.com/kisielk/errcheck",
\ "github.com/jstemmer/gotags", \ "github.com/jstemmer/gotags",
\ "github.com/klauspost/asmfmt/cmd/asmfmt", \ "github.com/klauspost/asmfmt/cmd/asmfmt",
@ -65,13 +66,16 @@ function! s:GoInstallBinaries(updateBinaries)
set noshellslash set noshellslash
endif endif
let cmd = "go get -u -v " let cmd = "go get -v "
if get(g:, "go_get_update", 1) != 0
let cmd .= "-u "
endif
let s:go_version = matchstr(go#util#System("go version"), '\d.\d.\d') let s:go_version = matchstr(go#util#System("go version"), '\d.\d.\d')
" https://github.com/golang/go/issues/10791 " https://github.com/golang/go/issues/10791
if s:go_version > "1.4.0" && s:go_version < "1.5.0" if s:go_version > "1.4.0" && s:go_version < "1.5.0"
let cmd .= "-f " let cmd .= "-f "
endif endif
for pkg in s:packages for pkg in s:packages

View file

@ -67,6 +67,10 @@ if !exists("g:go_highlight_methods")
let g:go_highlight_methods = 0 let g:go_highlight_methods = 0
endif endif
if !exists("g:go_highlight_fields")
let g:go_highlight_fields = 0
endif
if !exists("g:go_highlight_structs") if !exists("g:go_highlight_structs")
let g:go_highlight_structs = 0 let g:go_highlight_structs = 0
endif endif
@ -308,6 +312,12 @@ if g:go_highlight_methods != 0
endif endif
hi def link goMethod Type hi def link goMethod Type
" Fields;
if g:go_highlight_fields != 0
syn match goField /\(\.\)\@<=\a\+\([\ \n\r\:\)]\)\@=/
endif
hi def link goField Type
" Structs; " Structs;
if g:go_highlight_structs != 0 if g:go_highlight_structs != 0
syn match goStruct /\(.\)\@<=\w\+\({\)\@=/ syn match goStruct /\(.\)\@<=\w\+\({\)\@=/

View file

@ -199,10 +199,21 @@ highlight link multiple_cursors_visual Visual
## FAQ ## FAQ
**Q** <kbd>CTRL</kbd>+<kbd>n</kbd> doesn't seem to work in gVIM? #### **Q** <kbd>CTRL</kbd>+<kbd>n</kbd> doesn't seem to work in gVIM?
**A** Try setting `set selection=inclusive` in your `~/.gvimrc` **A** Try setting `set selection=inclusive` in your `~/.gvimrc`
#### **Q** How can I select `n` keywords with several keystrokes? I have tried `200<C-n>` which does not work.
**A** You can use :MultipleCursorsFind keyword. I have this binding in my vimrc:
```VimL
nnoremap <silent> <M-j> :MultipleCursorsFind <C-R>/<CR>
vnoremap <silent> <M-j> :MultipleCursorsFind <C-R>/<CR>
```
This allows one to a) search for the keyword using `*` b) turn search results into cursors with `Alt-j`.
## Known Issues ## Known Issues
- Select mode is not implemented - Select mode is not implemented

View file

@ -14,6 +14,7 @@ additional contributions from:
* [asymmetric](https://github.com/asymmetric) * [asymmetric](https://github.com/asymmetric)
* [bpugh](https://github.com/bpugh) * [bpugh](https://github.com/bpugh)
* [bruno-](https://github.com/bruno-) * [bruno-](https://github.com/bruno-)
* [CharlesGueunet](https://github.com/CharlesGueunet)
* [darkwise](https://github.com/darkwise) * [darkwise](https://github.com/darkwise)
* [dreviejo](https://github.com/dreviejo) * [dreviejo](https://github.com/dreviejo)
* [fish-face](https://github.com/fish-face) * [fish-face](https://github.com/fish-face)
@ -40,6 +41,7 @@ additional contributions from:
* [redpill](https://github.com/redpill) * [redpill](https://github.com/redpill)
* [rglassett](http://github.com/rglassett) * [rglassett](http://github.com/rglassett)
* [robhudson](https://github.com/robhudson) * [robhudson](https://github.com/robhudson)
* [shinymayhem](https://github.com/shinymayhem)
* [Shraymonks](https://github.com/shraymonks) * [Shraymonks](https://github.com/shraymonks)
* [sickill](https://github.com/sickill) * [sickill](https://github.com/sickill)
* [statik](https://github.com/statik) * [statik](https://github.com/statik)

View file

@ -87,7 +87,7 @@ languages. For this we provide two options: scope aliases and the
`:SnipMateLoadScope` command. Scope aliases simply say "whenever this scope is `:SnipMateLoadScope` command. Scope aliases simply say "whenever this scope is
loaded, also load this other scope: loaded, also load this other scope:
let g:snipMate = {} let g:snipMate = get(g:, 'snipMate', {}) " Allow for vimrc re-sourcing
let g:snipMate.scope_aliases = {} let g:snipMate.scope_aliases = {}
let g:snipMate.scope_aliases['ruby'] = 'ruby,rails' let g:snipMate.scope_aliases['ruby'] = 'ruby,rails'
@ -98,6 +98,16 @@ does `:SnipMateLoadScope rails` when editing a Rails project for example.
## Release Notes ## ## Release Notes ##
### 0.89 - 2016-05-29 ###
* Various regex updates to legacy parser
* Addition of double bang syntax to completely remove a snippet from lookup
* Group various SnipMate autocommands
* Support setting 'shiftwidth' to 0
* Parser now operates linewise, adding some flexibility
* Mirror substitutions are more literal
* Mirror length is calculated correctly when substitutions occur
### 0.88 - 2015-04-04 ### ### 0.88 - 2015-04-04 ###
* Implement simple caching * Implement simple caching

View file

@ -28,7 +28,8 @@ function! snipMate#expandSnip(snip, version, col) abort
let [snippet, b:snip_state.stops] = snipmate#parse#snippet(a:snip) let [snippet, b:snip_state.stops] = snipmate#parse#snippet(a:snip)
" Build stop/mirror info " Build stop/mirror info
let b:snip_state.stop_count = s:build_stops(snippet, b:snip_state.stops, lnum, col, indent) let b:snip_state.stop_count = s:build_stops(snippet, b:snip_state.stops, lnum, col, indent)
let snipLines = snipMate#sniplist_str(snippet, b:snip_state.stops) let snipLines = map(copy(snippet),
\ 'snipMate#sniplist_str(v:val, b:snip_state.stops)')
else else
let snippet = snipmate#legacy#process_snippet(a:snip) let snippet = snipmate#legacy#process_snippet(a:snip)
let [b:snip_state.stops, b:snip_state.stop_count] = snipmate#legacy#build_stops(snippet, lnum, col - indent, indent) let [b:snip_state.stops, b:snip_state.stop_count] = snipmate#legacy#build_stops(snippet, lnum, col - indent, indent)
@ -77,11 +78,11 @@ function! snipMate#expandSnip(snip, version, col) abort
endfunction endfunction
function! snipMate#placeholder_str(num, stops) abort function! snipMate#placeholder_str(num, stops) abort
return snipMate#sniplist_str(a:stops[a:num].placeholder, a:stops)[0] return snipMate#sniplist_str(a:stops[a:num].placeholder, a:stops)
endfunction endfunction
function! snipMate#sniplist_str(snippet, stops) abort function! snipMate#sniplist_str(snippet, stops) abort
let lines = [''] let str = ''
let pos = 0 let pos = 0
let add_to = 1 let add_to = 1
let seen_stops = [] let seen_stops = []
@ -90,110 +91,82 @@ function! snipMate#sniplist_str(snippet, stops) abort
let item = a:snippet[pos] let item = a:snippet[pos]
if type(item) == type('') if type(item) == type('')
if add_to let str .= item
let lines[-1] .= item
else
call add(lines, item)
endif
let add_to = 0
elseif type(item) == type([]) elseif type(item) == type([])
let lines[-1] .= snipMate#placeholder_str(item[0], a:stops) let str .= snipMate#placeholder_str(item[0], a:stops)
let add_to = 1
endif endif
let pos += 1 let pos += 1
unlet item " avoid E706 unlet item " avoid E706
endwhile endwhile
return lines return str
endfunction endfunction
function! s:build_stops(snippet, stops, lnum, col, indent) abort function! s:build_stops(snippet, stops, lnum, col, indent) abort
let stops = a:stops let stops = a:stops
let line = a:lnum let lnum = a:lnum
let col = a:col let col = a:col
for [id, dict] in items(stops) for line in a:snippet
for i in dict.instances let col = s:build_loc_info(line, stops, lnum, col, [])
if len(i) > 1 && type(i[1]) != type({}) if line isnot line[-1]
if !has_key(dict, 'placeholder') let lnum += 1
let dict.placeholder = i[1:] let col = a:indent
else
unlet i[1:]
endif
endif
endfor
if !has_key(dict, 'placeholder')
let dict.placeholder = []
let j = 0
while len(dict.instances[j]) > 1
let j += 1
endwhile
call add(dict.instances[j], '')
endif endif
unlet dict.instances
endfor endfor
let [line, col] = s:build_loc_info(a:snippet, stops, line, col, a:indent)
" add zero tabstop if it doesn't exist and then link it to the highest stop " add zero tabstop if it doesn't exist and then link it to the highest stop
" number " number
let stops[0] = get(stops, 0, let stops[0] = get(stops, 0,
\ { 'placeholder' : [], 'line' : line, 'col' : col }) \ { 'placeholder' : [], 'line' : lnum, 'col' : col })
let stop_count = max(keys(stops)) + 2 let stop_count = max(keys(stops)) + 2
let stops[stop_count - 1] = stops[0] let stops[stop_count - 1] = stops[0]
return stop_count return stop_count
endfunction endfunction
function! s:build_loc_info(snippet, stops, line, col, indent) abort function! s:build_loc_info(snippet, stops, lnum, col, seen_items) abort
let stops = a:stops let stops = a:stops
let line = a:line let lnum = a:lnum
let col = a:col let col = a:col
let pos = 0 let pos = 0
let in_text = 0 let in_text = 0
let seen_items = a:seen_items
while pos < len(a:snippet) for item in a:snippet
let item = a:snippet[pos]
if type(item) == type('') if type(item) == type('')
if in_text
let line += 1
let col = a:indent
endif
let col += len(item) let col += len(item)
let in_text = 1
elseif type(item) == type([]) elseif type(item) == type([])
let id = item[0] let id = item[0]
if len(item) > 1 && type(item[1]) != type({}) let stub = item[-1]
let stops[id].line = line let stub.line = lnum
let stops[id].col = col let stub.col = col
let [line, col] = s:build_loc_info(item[1:], stops, line, col, a:indent) call s:add_update_objects(stub, seen_items)
if len(item) > 2 && type(item[1]) != type({})
let col = s:build_loc_info(item[1:-2], stops, lnum, col, seen_items)
else else
call s:add_mirror(stops, id, line, col, item)
let col += len(snipMate#placeholder_str(id, stops)) let col += len(snipMate#placeholder_str(id, stops))
endif endif
let in_text = 0 let in_text = 0
endif endif
let pos += 1
unlet item " avoid E706 unlet item " avoid E706
endwhile endfor
return [line, col] return col
endfunction endfunction
function! s:add_mirror(stops, id, line, col, item) abort function! s:add_update_objects(object, targets) abort
let stops = a:stops let targets = a:targets
let item = a:item
let stops[a:id].mirrors = get(stops[a:id], 'mirrors', []) for item in targets
let mirror = get(a:item, 1, {}) let item.update_objects = get(item, 'update_objects', [])
let mirror.line = a:line call add(item.update_objects, a:object)
let mirror.col = a:col endfor
call add(stops[a:id].mirrors, mirror)
if len(item) == 1 call add(targets, a:object)
call add(item, mirror)
endif
endfunction endfunction
" reads a .snippets file " reads a .snippets file

View file

@ -113,7 +113,7 @@ function! s:state_update_changes() dict abort
return self.remove() return self.remove()
endif endif
call self.update(self.cur_stop, change_len) call self.update(self.cur_stop, change_len, change_len)
if !empty(self.mirrors) if !empty(self.mirrors)
call self.update_mirrors(change_len) call self.update_mirrors(change_len)
endif endif
@ -141,14 +141,37 @@ function! s:state_update_mirrors(change) dict abort
endif endif
endfor endfor
call self.update(mirror, changeLen) if has_key(mirror, 'oldSize')
" recover the old size deduce the endline
let oldSize = mirror.oldSize
else
" first time, we use the intitial size
let oldSize = strlen(newWord)
endif
" Split the line into three parts: the mirror, what's before it, and " Split the line into three parts: the mirror, what's before it, and
" what's after it. Then combine them using the new mirror string. " what's after it. Then combine them using the new mirror string.
" Subtract one to go from column index to byte index " Subtract one to go from column index to byte index
let theline = getline(mirror.line) let theline = getline(mirror.line)
let update = strpart(theline, 0, mirror.col - 1)
let update .= substitute(newWord, get(mirror, 'pat', ''), get(mirror, 'sub', ''), get(mirror, 'flags', '')) " part before the current mirror
let update .= strpart(theline, mirror.col + self.end_col - self.start_col - a:change - 1) let beginline = strpart(theline, 0, mirror.col - 1)
" current mirror transformation, and save size
let wordMirror= substitute(newWord, get(mirror, 'pat', ''), get(mirror, 'sub', ''), get(mirror, 'flags', ''))
let mirror.oldSize = strlen(wordMirror)
" end of the line, use the oldSize because with the transformation,
" the size of the mirror can be different from those of the snippet
let endline = strpart(theline, mirror.col + oldSize -1)
" Update other object on the line
call self.update(mirror, changeLen, mirror.oldSize - oldSize)
" reconstruct the line
let update = beginline.wordMirror.endline
call setline(mirror.line, update) call setline(mirror.line, update)
endfor endfor
@ -179,17 +202,17 @@ function! s:state_find_update_objects(item) dict abort
return item.update_objects return item.update_objects
endfunction endfunction
function! s:state_update(item, change_len) dict abort function! s:state_update(item, change_len, mirror_change) dict abort
let item = a:item let item = a:item
if exists('item.update_objects') if !exists('item.update_objects')
let to_update = item.update_objects let item.update_objects = self.find_update_objects(a:item)
else
let to_update = self.find_update_objects(a:item)
let item.update_objects = to_update
endif endif
let to_update = item.update_objects
for obj in to_update for obj in to_update
let obj.col += a:change_len " object does not necessarly have the same decalage
" than mirrors if mirrors use regexp
let obj.col += a:mirror_change
if obj is self.cur_stop if obj is self.cur_stop
let self.start_col += a:change_len let self.start_col += a:change_len
let self.end_col += a:change_len let self.end_col += a:change_len

View file

@ -12,8 +12,7 @@ function! snipmate#legacy#process_snippet(snip) abort
else else
let visual = '' let visual = ''
endif endif
let snippet = substitute(snippet, '\n\(\t\+\).\{-\}\zs{VISUAL}', let snippet = s:substitute_visual(snippet, visual)
\ substitute(escape(visual, '%\'), "\n", "\n\\\\1", 'g'), 'g')
" Evaluate eval (`...`) expressions. " Evaluate eval (`...`) expressions.
" Backquotes prefixed with a backslash "\" are ignored. " Backquotes prefixed with a backslash "\" are ignored.
@ -118,6 +117,16 @@ function! snipmate#legacy#build_stops(snip, lnum, col, indent) abort
return [stops, i + 1] return [stops, i + 1]
endfunction endfunction
function! s:substitute_visual(snippet, visual) abort
let lines = []
for line in split(a:snippet, "\n")
let indent = matchstr(line, '^\t\+')
call add(lines, substitute(line, '{VISUAL}',
\ substitute(escape(a:visual, '%\'), "\n", "\n" . indent, 'g'), 'g'))
endfor
return join(lines, "\n")
endfunction
" Counts occurences of haystack in needle " Counts occurences of haystack in needle
function! s:count(haystack, needle) abort function! s:count(haystack, needle) abort
let counter = 0 let counter = 0

View file

@ -5,6 +5,7 @@ function! s:sfile() abort
endfunction endfunction
let s:parser_proto = {} let s:parser_proto = {}
let s:special_chars = "$`\n"
function! s:new_parser(text) abort function! s:new_parser(text) abort
let ret = copy(s:parser_proto) let ret = copy(s:parser_proto)
@ -14,6 +15,7 @@ function! s:new_parser(text) abort
let ret.indent = 0 let ret.indent = 0
let ret.value = [] let ret.value = []
let ret.vars = {} let ret.vars = {}
let ret.stored_lines = []
call ret.advance() call ret.advance()
return ret return ret
endfunction endfunction
@ -82,35 +84,56 @@ function! s:parser_varend() dict abort
endfunction endfunction
function! s:parser_placeholder() dict abort function! s:parser_placeholder() dict abort
return self.parse('}') let ret = self.text('}')
return empty(ret) ? [''] : ret
endfunction endfunction
function! s:parser_subst() dict abort function! s:parser_subst() dict abort
let ret = {} let ret = {}
let ret.pat = join(self.text('/', 1)) let ret.pat = self.pat()
if self.same('/') if self.same('/')
let ret.sub = join(self.text('/}')) let ret.sub = self.pat(1)
endif endif
if self.same('/') if self.same('/')
let ret.flags = join(self.text('}', 1)) let ret.flags = self.pat(1)
endif endif
return ret return ret
endfunction endfunction
function! s:parser_pat(...) dict abort
let val = ''
while self.pos < self.len
if self.same('\')
if self.next == '/'
let val .= '/'
call self.advance()
elseif a:0 && self.next == '}'
let val .= '}'
call self.advance()
else
let val .= '\'
endif
elseif self.next == '/' || a:0 && self.next == '}'
break
else
let val .= self.next
call self.advance()
endif
endwhile
return val
endfunction
function! s:parser_expr() dict abort function! s:parser_expr() dict abort
let str = join(self.text('`', 1)) let str = self.string('`')
call self.same('`') call self.same('`')
return snipmate#util#eval(str) return snipmate#util#eval(str)
endfunction endfunction
function! s:parser_text(...) dict abort function! s:parser_string(till, ...) dict abort
let res = []
let val = '' let val = ''
if a:0 == 2 && a:2 let till = '\V\[' . escape(a:till, '\') . ']'
let till = '\V' . escape(a:1, '\')
else
let till = '[`$' . (a:0 ? a:1 : '') . ']'
endif
while self.pos < self.len while self.pos < self.len
if self.same('\') if self.same('\')
@ -120,11 +143,6 @@ function! s:parser_text(...) dict abort
call self.advance() call self.advance()
elseif self.next =~# till elseif self.next =~# till
break break
elseif self.next == "\n"
call add(res, val)
let val = ''
let self.indent = 0
call self.advance()
elseif self.next == "\t" elseif self.next == "\t"
let self.indent += 1 let self.indent += 1
let val .= s:indent(1) let val .= s:indent(1)
@ -135,55 +153,77 @@ function! s:parser_text(...) dict abort
endif endif
endwhile endwhile
call add(res, val) return val
return res
endfunction endfunction
function! s:parser_parse(...) dict abort function! s:join_consecutive_strings(list) abort
let ret = a:0 ? [] : self.value let list = a:list
let pos = 0
while pos + 1 < len(list)
if type(list[pos]) == type('') && type(list[pos+1]) == type('')
let list[pos] .= list[pos+1]
call remove(list, pos + 1)
else
let pos += 1
endif
endwhile
endfunction
function! s:parser_text(till) dict abort
let ret = []
while self.pos < self.len while self.pos < self.len
let lines = []
if self.same('$') if self.same('$')
let var = self.var() let var = self.var()
if !empty(var) if !empty(var)
if var[0] is# 'VISUAL' if var[0] is# 'VISUAL'
let add_to = s:visual_placeholder(var, self.indent) let lines = s:visual_placeholder(var, self.indent)
if !empty(ret) && type(ret[-1]) == type('')
let ret[-1] .= add_to[0]
else
call add(ret, add_to[0])
endif
call extend(ret, add_to[1:-1])
elseif var[0] >= 0 elseif var[0] >= 0
call add(ret, var) call add(ret, var)
call self.add_var(var) call self.add_var(var)
endif endif
endif endif
elseif self.same('`') elseif self.same('`')
let add_to = self.expr() let lines = split(self.expr(), "\n", 1)
if !empty(ret) && type(ret[-1]) == type('')
let ret[-1] .= add_to
else
call add(ret, add_to)
endif
else else
let text = a:0 ? self.text(a:1) : self.text() let lines = [self.string(a:till . s:special_chars)]
if exists('add_to')
let ret[-1] .= text[0]
call remove(text, 0)
unlet add_to
endif
call extend(ret, text)
endif endif
if a:0 && self.next == a:1
if !empty(lines)
call add(ret, lines[0])
call extend(self.stored_lines, lines[1:])
endif
" Empty lines are ignored if this is tested at the start of an iteration
if self.next ==# a:till
break break
endif endif
endwhile endwhile
call s:join_consecutive_strings(ret)
return ret return ret
endfunction endfunction
call extend(s:parser_proto, snipmate#util#add_methods(s:sfile(), 'parser', function! s:parser_line() dict abort
\ [ 'advance', 'same', 'id', 'add_var', 'var', 'varend', let ret = []
\ 'placeholder', 'subst', 'expr', 'text', 'parse' ]), 'error') if !empty(self.stored_lines)
call add(ret, remove(self.stored_lines, 0))
else
call extend(ret, self.text("\n"))
call self.same("\n")
endif
let self.indent = 0
return ret
endfunction
function! s:parser_parse() dict abort
while self.pos < self.len || !empty(self.stored_lines)
let line = self.line()
call add(self.value, line)
endwhile
endfunction
function! s:indent(count) abort function! s:indent(count) abort
if &expandtab if &expandtab
@ -211,9 +251,59 @@ function! s:visual_placeholder(var, indent) abort
return content return content
endfunction endfunction
function! snipmate#parse#snippet(text) abort function! s:parser_create_stubs() dict abort
for [id, dict] in items(self.vars)
for i in dict.instances
if len(i) > 1 && type(i[1]) != type({})
if !has_key(dict, 'placeholder')
let dict.placeholder = i[1:]
call add(i, dict)
else
unlet i[1:]
call s:create_mirror_stub(i, dict)
endif
else
call s:create_mirror_stub(i, dict)
endif
endfor
if !has_key(dict, 'placeholder')
let dict.placeholder = []
let j = 0
while len(dict.instances[j]) > 2
let j += 1
endwhile
let oldstub = remove(dict.instances[j], 1, -1)[-1]
call add(dict.instances[j], '')
call add(dict.instances[j], dict)
call filter(dict.mirrors, 'v:val isnot oldstub')
endif
unlet dict.instances
endfor
endfunction
function! s:create_mirror_stub(mirror, dict)
let mirror = a:mirror
let dict = a:dict
let stub = get(mirror, 1, {})
call add(mirror, stub)
let dict.mirrors = get(dict, 'mirrors', [])
call add(dict.mirrors, stub)
endfunction
function! snipmate#parse#snippet(text, ...) abort
let parser = s:new_parser(a:text) let parser = s:new_parser(a:text)
call parser.parse() call parser.parse()
if !(a:0 && a:1)
call parser.create_stubs()
endif
unlet! b:snipmate_visual unlet! b:snipmate_visual
return [parser.value, parser.vars] return [parser.value, parser.vars]
endfunction endfunction
call extend(s:parser_proto, snipmate#util#add_methods(s:sfile(), 'parser',
\ [ 'advance', 'same', 'id', 'add_var', 'var', 'varend',
\ 'line', 'string', 'create_stubs', 'pat',
\ 'placeholder', 'subst', 'expr', 'text', 'parse',
\ ]), 'error')

View file

@ -1,7 +1,6 @@
*SnipMate.txt* Plugin for using TextMate-style snippets in Vim. *SnipMate.txt* Plugin for using TextMate-style snippets in Vim.
SnipMate *snippet* *snippets* *SnipMate* SnipMate *snippet* *snippets* *SnipMate*
Last Change: December 27, 2009
1. Description |SnipMate-description| 1. Description |SnipMate-description|
2. Usage |SnipMate-usage| 2. Usage |SnipMate-usage|
@ -504,6 +503,15 @@ Perhaps some of these features will be added in a later release.
============================================================================== ==============================================================================
CHANGELOG *SnipMate-changelog* CHANGELOG *SnipMate-changelog*
0.89 - 2016-05-29
-----------------
* Various regex updates to legacy parser Addition of double bang syntax to
* completely remove a snippet from lookup Group various SnipMate autocommands
* Support setting 'shiftwidth' to 0 Parser now operates linewise, adding some
* flexibility Mirror substitutions are more literal Mirror length is
* calculated correctly when substitutions occur
0.88 - 2015-04-04 0.88 - 2015-04-04
----------------- -----------------

View file

@ -2,27 +2,27 @@ describe 'snippet parser'
before before
function! Parse(snippet, ...) function! Parse(snippet, ...)
let [snip, stops] = snipmate#parse#snippet(a:snippet) let [snip, stops] = snipmate#parse#snippet(a:snippet, (a:0 ? a:1 : 1))
return a:0 ? [snip, stops] : snip return (a:0 > 1 && a:2) ? [snip, stops] : snip
endfunction endfunction
let b:snipmate_visual = 'testvisual' let b:snipmate_visual = 'testvisual'
end end
it 'parses numeric $id and ${id} vars as [id] lists' it 'parses numeric $id and ${id} vars as [id] lists'
let expect = [[1234567890]] let expect = [[[1234567890]]]
Expect Parse('$1234567890') == expect Expect Parse('$1234567890') == expect
Expect Parse('${1234567890}') == expect Expect Parse('${1234567890}') == expect
end end
it 'disregards $ or ${ followed by a non-id' it 'disregards $ or ${ followed by a non-id'
Expect Parse('$x1') == ['x1'] Expect Parse('$x1') == [['x1']]
Expect Parse('${x}1') == ['x}1'] Expect Parse('${x}1') == [['x}1']]
Expect Parse('$VISUA1') == ['VISUA1'] Expect Parse('$VISUA1') == [['VISUA1']]
Expect Parse('${VISUA}1') == ['VISUA}1'] Expect Parse('${VISUA}1') == [['VISUA}1']]
end end
it 'gathers references to each instance of each stop id' it 'gathers references to each instance of each stop id'
let [snip, b:stops] = Parse('x$1x${2:x$1x}x$1x${1/a/b}x$VISUALx', 1) let [snip, b:stops] = Parse('x$1x${2:x$1x}x$1x${1/a/b}x$VISUALx', 1, 1)
function! InstanceFound(list) function! InstanceFound(list)
return !empty(filter(copy(b:stops[a:list[0]].instances), return !empty(filter(copy(b:stops[a:list[0]].instances),
\ 'v:val is a:list')) \ 'v:val is a:list'))
@ -36,87 +36,107 @@ describe 'snippet parser'
unlet item " E732 unlet item " E732
endfor endfor
endfunction endfunction
call CheckList(snip) call CheckList(snip[0])
end end
it 'parses mirror substitutions ${n/pat/sub} as [n, {...}]' it 'parses mirror substitutions ${n/pat/sub} as [n, {...}]'
let expect = [[1, { 'pat' : 'abc', 'sub' : 'def' }]] let expect = [[[1, { 'pat' : 'abc', 'sub' : 'def' }]]]
Expect Parse('${1/abc/def}') == expect Expect Parse('${1/abc/def}') == expect
let expect[0][1].flags = '' let expect[0][0][1].flags = ''
Expect Parse('${1/abc/def/}') == expect Expect Parse('${1/abc/def/}') == expect
let expect[0][1].flags = 'g' let expect[0][0][1].flags = 'g'
Expect Parse('${1/abc/def/g}') == expect Expect Parse('${1/abc/def/g}') == expect
end end
it 'reads patterns literally except for "\/"'
Expect Parse('${1/\a\/b/\c\/d\}}') == [[[1, { 'pat' : '\a/b', 'sub' : '\c/d}' }]]]
end
it 'parses vars with placeholders as [id, placeholder] lists' it 'parses vars with placeholders as [id, placeholder] lists'
Expect Parse('${1:abc}') == [[1, 'abc']] Expect Parse('${1:abc}') == [[[1, 'abc']]]
end end
it 'evaluates backtick expressions' it 'evaluates backtick expressions'
Expect Parse('`fnamemodify("x.y", ":r")`') == ['x'] Expect Parse('`fnamemodify("x.y", ":r")`') == [['x']]
end end
it 'parses placeholders for vars and other specials' it 'parses placeholders for vars and other specials'
let text = 'a `fnamemodify("x.y", ":r")` ${2:(${3/a/b})}' let text = 'a `fnamemodify("x.y", ":r")` ${2:(${3/a/b})}'
let expect = ['a x ', [2, '(', [3, { 'pat' : 'a', 'sub' : 'b' }], ')']] let expect = ['a x ', [2, '(', [3, { 'pat' : 'a', 'sub' : 'b' }], ')']]
Expect Parse(text) == expect Expect Parse(text) == [expect]
Expect Parse(printf('${1:%s}', text)) == [[1] + expect] Expect Parse(printf('${1:%s}', text)) == [[[1] + expect]]
end end
it 'converts tabs according to &et, &sts, &sw, &ts' it 'converts tabs according to &et, &sts, &sw, &ts'
" &noet -> leave tabs alone " &noet -> leave tabs alone
setl noet setl noet
Expect Parse("abc\tdef\n\t\tghi") == ["abc\tdef", "\t\tghi"] Expect Parse("abc\tdef\n\t\tghi") == [["abc\tdef"], ["\t\tghi"]]
" &et -> &sts or &sw " &et -> &sts or &sw
setl et sts=2 sw=3 setl et sts=2 sw=3
Expect Parse("abc\tdef\n\t\tghi") == ["abc def", " ghi"] Expect Parse("abc\tdef\n\t\tghi") == [["abc def"], [" ghi"]]
setl et sts=0 sw=3 setl et sts=0 sw=3
Expect Parse("abc\tdef\n\t\tghi") == ["abc def", " ghi"] Expect Parse("abc\tdef\n\t\tghi") == [["abc def"], [" ghi"]]
setl et sts=-1 sw=3 setl et sts=-1 sw=3
Expect Parse("abc\tdef\n\t\tghi") == ["abc def", " ghi"] Expect Parse("abc\tdef\n\t\tghi") == [["abc def"], [" ghi"]]
" See #227 " See #227
if exists('*shiftwidth') if exists('*shiftwidth')
setl et sts=0 sw=0 ts=3 setl et sts=0 sw=0 ts=3
Expect Parse("abc\tdef\n\t\tghi") == ["abc def", " ghi"] Expect Parse("abc\tdef\n\t\tghi") == [["abc def"], [" ghi"]]
endif endif
end end
it 'parses backslashes as escaping the next character or joining lines' it 'parses backslashes as escaping the next character or joining lines'
Expect Parse('x\x') == ['xx'] Expect Parse('x\x') == [['xx']]
Expect Parse('x\\x') == ['x\x'] Expect Parse('x\\x') == [['x\x']]
Expect Parse("x\\\nx") == ['xx'] Expect Parse("x\\\nx") == [['xx']]
Expect Parse('x\$1') == ['x$1'] Expect Parse('x\$1') == [['x$1']]
Expect Parse('${1:\}}') == [[1, '}']] Expect Parse('${1:\}}') == [[[1, '}']]]
Expect Parse('${1/\//\}}') == [[1, { 'pat' : '/', 'sub' : '}' }]] Expect Parse('`fnamemodify("\`.x", ":r")`') == [['`']]
Expect Parse('`fnamemodify("\`.x", ":r")`') == ['`'] Expect Parse('\`x\`') == [['`x`']]
Expect Parse('\`x\`') == ['`x`']
end end
it 'splits text at newlines' it 'splits text at newlines'
Expect Parse("x\nx") == ['x', 'x'] Expect Parse("x\nx") == [['x'], ['x']]
end end
it 'joins evaluated expressions to surrounding text on the same line' it 'joins evaluated expressions to surrounding text on the same line'
let g:foo = 'bar' let g:foo = 'bar'
Expect Parse("x`g:foo`x") == ['xbarx'] Expect Parse("x`g:foo`x") == [['xbarx']]
Expect Parse("x`g:foo`\nx") == ['xbar', 'x'] Expect Parse("x`g:foo`\nx") == [['xbar'], ['x']]
Expect Parse("x\n`g:foo`x") == ['x', 'barx'] Expect Parse("x\n`g:foo`x") == [['x'], ['barx']]
end
it 'adds empty strings before/after vars if at the start/end of a line'
Expect Parse("x$1\nx") == ['x', [1], '', 'x']
Expect Parse("x\n$1x") == ['x', '', [1], 'x']
end end
it 'expands $VISUAL placeholders with any indents' it 'expands $VISUAL placeholders with any indents'
Expect Parse("x$VISUALx") == ['xtestvisualx'] Expect Parse("x$VISUALx") == [['xtestvisualx']]
let b:snipmate_visual = " foo\nbar\n baz" let b:snipmate_visual = " foo\nbar\n baz"
setl noet setl noet
Expect Parse("\tx\n\t$VISUAL\nx") == ["\tx", "\t foo", "\tbar", "\t baz", "x"] Expect Parse("\tx\n\t$VISUAL\nx") == [["\tx"], ["\t foo"], ["\tbar"],
\ ["\t baz"], ["x"]]
end
it 'determines which var with an id is the stop'
let [snip, stops] = Parse("$1$1$1", 0, 1)
Expect snip == [[[1, "", stops[1]], [1, {}], [1, {}]]]
let [snip, stops] = Parse("$1${1}$1", 0, 1)
Expect snip == [[[1, "", stops[1]], [1, {}], [1, {}]]]
let [snip, stops] = Parse("$1${1:}$1", 0, 1)
Expect snip == [[[1, {}], [1, "", stops[1]], [1, {}]]]
end
it 'picks the first of many possible stops'
let [snip, stops] = Parse("$1${1:foo}${1:bar}", 0, 1)
Expect snip == [[[1, {}], [1, "foo", stops[1]], [1, {}]]]
end
it 'represents empty lines as an empty string'
Expect Parse("foo\n\nbar") == [['foo'], [''], ['bar']]
end end
end end

View file

@ -1,8 +1,9 @@
# Snippets for phpspec # Snippets for phpspec, to use add the following to your .vimrc
# `autocmd BufRead,BufNewFile,BufEnter *Spec.php UltiSnipsAddFiletypes php-phpspec`
priority -50 priority -50
snippet spec "phpspec class" b snippet spec "class XYZSpec extends ObjectBehaviour"
<?php <?php
namespace `!p namespace `!p
@ -22,17 +23,200 @@ class `!p
snip.rv = re.match(r'.*(?=\.)', fn).group() snip.rv = re.match(r'.*(?=\.)', fn).group()
` extends ObjectBehavior ` extends ObjectBehavior
{ {
public function it${1:_does_something}() function it${1}()
{ {
$0 $0
} }
} }
endsnippet endsnippet
snippet it "phpspec function it..." b snippet it "function it_does_something() { ... }"
public function it${1:_does_something}() function it${1}()
{ {
$0 ${0:${VISUAL}}
} }
endsnippet endsnippet
snippet let "function let() { ... }"
function let()
{
${0:${VISUAL}}
}
endsnippet
snippet letgo "function letgo() { ... }"
function letgo()
{
${0:${VISUAL}}
}
endsnippet
# Object construction
snippet cw "$this->beConstructedWith($arg)"
$this->beConstructedWith(${1});
endsnippet
snippet ct "$this->beConstructedThrough($methodName, [$arg])"
$this->beConstructedThrough(${1:'methodName'}, [${2:'$arg'}]);
endsnippet
# Identity and comparison matchers
snippet sreturn "$this->XYZ()->shouldReturn('value')"
$this->${1:method}()->shouldReturn(${2:'value'});
endsnippet
snippet snreturn "$this->XYZ()->shouldNotReturn('value')"
$this->${1:method}()->shouldNotReturn(${2:'value'});
endsnippet
snippet sbe "$this->XYZ()->shouldBe('value')"
$this->${1:method}()->shouldBe(${2:'value'});
endsnippet
snippet snbe "$this->XYZ()->shouldNotBe('value')"
$this->${1:method}()->shouldNotBe(${2:'value'});
endsnippet
snippet sequal "$this->XYZ()->shouldEqual('value')"
$this->${1:method}()->shouldEqual(${2:'value'});
endsnippet
snippet snequal "$this->XYZ()->shouldNotEqual('value')"
$this->${1:method}()->shouldNotEqual(${2:'value'});
endsnippet
snippet sbequalto "$this->XYZ()->shouldBeEqualTo('value')"
$this->${1:method}()->shouldBeEqualTo(${2:'value'});
endsnippet
snippet snbequalto "$this->XYZ()->shouldNotBeEqualTo('value')"
$this->${1:method}()->shouldNotBeEqualTo(${2:'value'});
endsnippet
snippet sblike "$this->XYZ()->shouldBeLike('value')"
$this->${1:method}()->shouldBeLike(${2:'value'});
endsnippet
snippet snblike "$this->XYZ()->shouldNotBeLike('value')"
$this->${1:method}()->shouldNotBeLike(${2:'value'});
endsnippet
# Throw matcher
snippet sthrowm "$this->shouldThrow('\Exception')->duringXYZ($arg)"
$this->shouldThrow(${1:'\Exception'})->during${2:Method}(${3:'$arg'});
endsnippet
snippet sthrowi "$this->shouldThrow('\Exception')->duringInstantiation()"
$this->shouldThrow(${1:'\Exception'})->duringInstantiation();
endsnippet
# Type matchers
snippet stype "$this->shouldHaveType('Type')"
$this->shouldHaveType(${1});
endsnippet
snippet sntype "$this->shouldNotHaveType('Type')"
$this->shouldNotHaveType(${1});
endsnippet
snippet srinstance "$this->shouldReturnAnInstanceOf('Type')"
$this->shouldReturnAnInstanceOf(${1});
endsnippet
snippet snrinstance "$this->shouldNotReturnAnInstanceOf('Type')"
$this->shouldNotReturnAnInstanceOf(${1});
endsnippet
snippet sbinstance "$this->shouldBeAnInstanceOf('Type')"
$this->shouldBeAnInstanceOf(${1});
endsnippet
snippet snbinstance "$this->shouldNotBeAnInstanceOf('Type')"
$this->shouldNotBeAnInstanceOf(${1});
endsnippet
snippet simplement "$this->shouldImplement('Type')"
$this->shouldImplement(${1});
endsnippet
snippet snimplement "$this->shouldNotImplement('Type')"
$this->shouldNotImplement(${1});
endsnippet
# Object state matchers
snippet sbstate "$this->shouldBeXYZ()"
$this->shouldBe${1}();
endsnippet
snippet snbstate "$this->shouldNotBeXYZ()"
$this->shouldNotBe${1}();
endsnippet
# Count matchers
snippet scount "$this->XYZ()->shouldHaveCount(7)"
$this->${1:method}()->shouldHaveCount(${2:7});
endsnippet
snippet sncount "$this->XYZ()->shouldNotHaveCount(7)"
$this->${1:method}()->shouldNotHaveCount(${2:7});
endsnippet
# Scalar type matchers
snippet sbscalar "$this->XYZ()->shouldBeString|Array|Bool()"
$this->${1:method}()->shouldBe(${2:'String|Array|Bool'});
endsnippet
snippet snbscalar "$this->XYZ()->shouldNotBeString|Array|Bool()"
$this->${1:method}()->shouldNotBe(${2:'String|Array|Bool'});
endsnippet
# Contain matcher
snippet scontain "$this->XYZ()->shouldContain('value')"
$this->${1:method}()->shouldContain(${2:'value'});
endsnippet
snippet sncontain "$this->XYZ()->shouldNotContain('value')"
$this->${1:method}()->shouldNotContain(${2:'value'});
endsnippet
# Array matchers
snippet skey "$this->XYZ()->shouldHaveKey('key')"
$this->${1:method}()->shouldHaveKey(${2:'key'});
endsnippet
snippet snkey "$this->XYZ()->shouldNotHaveKey('key')"
$this->${1:method}()->shouldNotHaveKey(${2:'key'});
endsnippet
snippet skeyvalue "$this->XYZ()->shouldHaveKeyWithValue('key', 'value')"
$this->${1:method}()->shouldHaveKeyWithValue(${2:'key'}, ${3:'value'});
endsnippet
snippet snkeyvalue "$this->XYZ()->shouldNotHaveKeyWithValue('key', 'value')"
$this->${1:method}()->shouldNotHaveKeyWithValue(${2:'key'}, ${3:'value'});
endsnippet
# String matchers
snippet sstart "$this->XYZ()->shouldStartWith('string')"
$this->${1:method}()->shouldStartWith(${2:'string'});
endsnippet
snippet snstart "$this->XYZ()->shouldNotStartWith('string')"
$this->${1:method}()->shouldNotStartWith(${2:'string'});
endsnippet
snippet send "$this->XYZ()->shouldEndWith('string')"
$this->${1:method}()->shouldEndWith(${2:'string'});
endsnippet
snippet snend "$this->XYZ()->shouldNotEndWith('string')"
$this->${1:method}()->shouldNotEndWith(${2:'string'});
endsnippet
snippet smatch "$this->XYZ()->shouldMatch('/wizard/i')"
$this->${1:method}()->shouldMatch(${2:'/wizard/i'});
endsnippet
snippet snmatch "$this->XYZ()->shouldNotMatch('/wizard/i')"
$this->${1:method}()->shouldNotMatch(${2:'/wizard/i'});
endsnippet

View file

@ -1,40 +0,0 @@
# suggestion? report bugs?
# please go to https://github.com/chrisyue/vim-snippets/issues
priority -50
snippet test "phpunit test class" b
<?php
namespace `!p
relpath = os.path.relpath(path)
m = re.search(r'[A-Z].+(?=/)', relpath)
if m:
snip.rv = m.group().replace('/', '\\')
`;
/**
* @author `!v g:snips_author`
*/
class `!p
snip.rv = re.match(r'.*(?=\.)', fn).group()
` extends \PHPUnit_Framework_TestCase
{
public function test${1}()
{
${2}
}
}
endsnippet
snippet exp "phpunit expects" i
expects($this->${1:once}())
->method('${2}')
->with($this->equalTo(${3})${4})
->will($this->returnValue(${5}));
endsnippet
snippet testcmt "phpunit comment with group" b
/**
* @group ${1}
*/
endsnippet

View file

@ -3,119 +3,11 @@ priority -50
## Snippets from SnipMate, taken from ## Snippets from SnipMate, taken from
## https://github.com/scrooloose/snipmate-snippets.git ## https://github.com/scrooloose/snipmate-snippets.git
snippet array "array"
$${1:arrayName} = array('${2}' => ${3});${4}
endsnippet
snippet def "def"
define('${1:VARIABLE_NAME}', ${2:'definition'});${3}
endsnippet
snippet wh "while"
while (${1}) {
${0:${VISUAL}}
}
endsnippet
snippet do "do"
do {
${2:// code... }
} while (${1:/* condition */});
endsnippet
snippet doc_f "doc_f"
/**
* $2
* @return ${4:void}
* @author ${5:`!v g:snips_author`}
**/
${1:public }function ${2:someFunc}(${3})
{${6}
}
endsnippet
snippet doc_i "doc_i"
/**
* $1
* @package ${2:default}
* @author ${3:`!v g:snips_author`}
**/
interface ${1:someClass}
{${4}
} // END interface $1"
endsnippet
snippet el "else"
else {
${0:${VISUAL}}
}
endsnippet
snippet for "for"
for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {
${4:// code...}
}
endsnippet
snippet foreachk "foreachk"
foreach ($${1:variable} as $${2:key} => $${3:value}) {
${4:// code...}
}
endsnippet
snippet get "get"
$_GET['${1}']${2}
endsnippet
snippet if "if"
if (${1}) {
${0:${VISUAL}}
}
endsnippet
snippet eif "elseif"
elseif (${1}) {
${0:${VISUAL}}
}
endsnippet
snippet inc "inc"
include '${1:file}';${2}
endsnippet
snippet log "log"
error_log(var_export(${1}, true));${2}
endsnippet
snippet post "post"
$_POST['${1}']${2}
endsnippet
snippet req "req1"
require_once '${1:file}';${2}
endsnippet
snippet req1 "req1"
require_once '${1:file}';${2}
endsnippet
snippet session "session"
$_SESSION['${1}']${2}
endsnippet
snippet t "t"
$${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};${5}
endsnippet
snippet var "var"
var_export(${1});${2}
endsnippet
snippet getter "PHP Class Getter" b snippet getter "PHP Class Getter" b
/** /**
* Getter for $1 * Getter for $1
* *
* ${2:return string} * @return ${2:string}
*/ */
public function get${1/\w+\s*/\u$0/}() public function get${1/\w+\s*/\u$0/}()
{ {
@ -127,7 +19,7 @@ snippet setter "PHP Class Setter" b
/** /**
* Setter for $1 * Setter for $1
* *
* @param ${2:string} $$1 * @param ${2:string} $$1
* @return ${3:`!p snip.rv=snip.basename`} * @return ${3:`!p snip.rv=snip.basename`}
*/ */
public function set${1/\w+\s*/\u$0/}(${4:${2/(void|string|int|integer|double|float|object|boolear|null|mixed|number|resource)|(.*)/(?1::$2 )/}}$$1) public function set${1/\w+\s*/\u$0/}(${4:${2/(void|string|int|integer|double|float|object|boolear|null|mixed|number|resource)|(.*)/(?1::$2 )/}}$$1)
@ -143,7 +35,7 @@ snippet gs "PHP Class Getter Setter" b
/** /**
* Getter for $1 * Getter for $1
* *
* return ${2:string} * @return ${2:string}
*/ */
public function get${1/\w+\s*/\u$0/}() public function get${1/\w+\s*/\u$0/}()
{ {
@ -251,27 +143,11 @@ function ${1:name}(${2:$param})
$0 $0
endsnippet endsnippet
snippet fore "Foreach loop"
foreach ($${1:variable} as $${3:value}) {
${VISUAL}${4}
}
$0
endsnippet
snippet new "New class instance" b snippet new "New class instance" b
$${1:variableName} = new ${2:${1/\w+\s*/\u$0/}}($3); $${1:variableName} = new ${2:${1/\w+\s*/\u$0/}}($3);
$0 $0
endsnippet endsnippet
snippet ife "if else"
if (${1:/* condition */}) {
${2:// code...}
} else {
${3:// code...}
}
$0
endsnippet
snippet ns "namespace declaration" b snippet ns "namespace declaration" b
namespace ${1:`!p namespace ${1:`!p
relpath = os.path.relpath(path) relpath = os.path.relpath(path)
@ -316,7 +192,7 @@ if m:
*/ */
interface $1 interface $1
{ {
public function ${3:someFunction}();$4 public function ${3:someFunction}();$4
} }
endsnippet endsnippet
@ -349,18 +225,29 @@ public function __construct(${1:$dependencies})
$0 $0
endsnippet endsnippet
snippet ve "Dumb debug helper in HTML" # PHPUnit snippets
echo '<pre>' . var_export($1, 1) . '</pre>';$0 snippet testcase "class XYZTest extends \PHPUnit_Framework_TestCase { ... }"
endsnippet <?php
snippet pc "Dumb debug helper in cli" namespace `!p
var_export($1);$0 relpath = os.path.relpath(path)
endsnippet m = re.search(r'[A-Z].+(?=/)', relpath)
if m:
snip.rv = m.group().replace('/', '\\')
`;
snippet inheritdoc "@inheritdoc docblock"
/** /**
* {@inheritdoc} * @author `!v g:snips_author`
*/ */
class `!p
snip.rv = re.match(r'.*(?=\.)', fn).group()
` extends \PHPUnit_Framework_TestCase
{
public function test${1}()
{
${0:${VISUAL}}
}
}
endsnippet endsnippet
# :vim:ft=snippets: # :vim:ft=snippets:

View file

@ -1,53 +0,0 @@
priority -50
snippet bl "twig block" b
{% block ${1} %}
${2}
{% endblock $1 %}
endsnippet
snippet js "twig javascripts" b
{% javascripts '${1}' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
endsnippet
snippet css "twig stylesheets" b
{% stylesheets '${1}' %}
<link rel="stylesheet" href="{{ asset_url }}">
{% endstylesheets %}
endsnippet
snippet if "twig if" b
{% if ${1} %}
${0:${VISUAL}}
{% endif %}
endsnippet
snippet ife "twig if ... else" b
{% if ${1} %}
${2}
{% else %}
${0}
{% endif %}
endsnippet
snippet el "twig else"
{% else %}
${0:${VISUAL}}
endsnippet
snippet eif "twig elseif"
{% elseif ${1} %}
${0:${VISUAL}}
endsnippet
snippet for "twig for" b
{% for ${1} in ${2} %}
${3}
{% endfor %}
endsnippet
snippet ext "twig extends" b
{% extends ${1} %}
endsnippet

View file

@ -7,6 +7,8 @@ snippet date
`strftime("%Y-%m-%d")` `strftime("%Y-%m-%d")`
snippet ddate snippet ddate
`strftime("%B %d, %Y")` `strftime("%B %d, %Y")`
snippet diso
`strftime("%Y-%m-%dT%H:%M:%S")`
snippet time snippet time
`strftime("%H:%M")` `strftime("%H:%M")`
snippet datetime snippet datetime

View file

@ -146,9 +146,9 @@ snippet itera
## Lambdas ## Lambdas
# lamda (one line) # lamda (one line)
snippet ld snippet ld
[${1}](${2}){${3}} [${1}](${2}){${3}};
# lambda (multi-line) # lambda (multi-line)
snippet lld snippet lld
[${1}](${2}){ [${1}](${2}){
${3} ${3}
} };

View file

@ -114,7 +114,7 @@ snippet testa
end end
snippet exunit snippet exunit
defmodule ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} do defmodule ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} do
use ExUnit.Case use ExUnit.Case, async: true
${0} ${0}
end end
@ -131,3 +131,6 @@ snippet qu
quote do quote do
${1} ${1}
end end
snippet beh
@behaviour ${1:Mix.Task}
${0}

View file

@ -0,0 +1,50 @@
snippet mod
module `substitute(substitute(expand('%:r'), '[/\\]','.','g'),'^\%(\l*\.\)\?','','')` exposing (${1})
${0}
snippet imp
import ${0:List}
snippet impe
import ${1:List} exposing (${0:map})
snippet fn
${1:fn} : ${2:a} -> ${3:a}
$1 ${4} =
${0}
snippet fn1
${1:fn} : ${2:a} -> ${3:a}
$1 ${4} =
${0}
snippet fn2
${1:fn} : ${2:a} -> ${3:a} -> ${4:a}
$1 ${5} =
${0}
snippet fn3
${1:fn} : ${2:a} -> ${3:a} -> ${4:a} -> ${5:a}
$1 ${6} =
${0}
snippet fn0
${1:fn} : ${2:a}
$1 =
${0}
snippet case
case ${1} of
${2} ->
${0}
snippet -
${1} ->
${0}
snippet let
let
${1} = ${2}
in
${0}
snippet if
if ${1} then
${2}
else
${0}
snippet ty
type ${1:Msg}
= ${0}
snippet tya
type alias ${1:Model} =
${0}

View file

@ -482,6 +482,37 @@ snippet gen_event
%%%=================================================================== %%%===================================================================
%%% Internal functions %%% Internal functions
%%%=================================================================== %%%===================================================================
# EUnit snippets
snippet eunit
-module(${1:`vim_snippets#Filename('', 'my')`}).
-include_lib("eunit/include/eunit.hrl").
${0}
snippet ieunit
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
${0}
-endif.
snippet as
?assert(${0})
snippet asn
?assertNot(${0})
snippet aseq
?assertEqual(${1}, ${0})
snippet asneq
?assertNotEqual(${1}, ${0})
snippet asmat
?assertMatch(${1:Pattern}, ${0:Expression})
snippet asnmat
?assertNotMatch(${1:Pattern}, ${0:Expression})
snippet aserr
?assertError(${1:Pattern}, ${0:Expression})
snippet asex
?assertExit(${1:Pattern}, ${0:Expression})
snippet asexc
?assertException(${1:Class}, ${2:Pattern}, ${0:Expression})
# common_test test_SUITE # common_test test_SUITE
snippet testsuite snippet testsuite
-module(${0:`vim_snippets#Filename('', 'my')`}). -module(${0:`vim_snippets#Filename('', 'my')`}).

View file

@ -0,0 +1,14 @@
snippet des "Describe" b
describe('${1:}', () => {
${0}
});
snippet it "it" b
it('${1:}', () => {
${0}
});
snippet exp "expect" b
expect(${1:})${0};
snippet expe "expect" b
expect(${1:}).to.equal(${0});
snippet expd "expect" b
expect(${1:}).to.deep.equal(${0});

View file

@ -43,3 +43,8 @@ snippet el
# .DEFAULT_GOAL := target # .DEFAULT_GOAL := target
snippet default snippet default
.DEFAULT_GOAL := ${1} .DEFAULT_GOAL := ${1}
# help target for self-documented Makefile
snippet help
help: ## Prints help for targets with comments
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $\$1, $\$2}'
${0}

View file

@ -0,0 +1,18 @@
# if {{#value}} ... {{/value}}
snippet if
{{#${1:value}}}
${0}
{{/$1}}
# if not {{^value}} ... {{/value}}
snippet ifn
{{^${1:value}}}
${0}
{{/$1}}
# if else {{#value}} ... {{/value}} {{^value}} ... {{/value}}
snippet ife
{{#${1:value}}}
${2}
{{/$1}}
{{^$1}}
${3}
{{/$1}}

View file

@ -24,10 +24,7 @@ snippet ?i
snippet ns snippet ns
namespace ${1:Foo\Bar\Baz}; namespace ${1:Foo\Bar\Baz};
${0} ${0}
snippet use snippet c
use ${1:Foo\Bar\Baz};
${0}
snippet c
class ${1:`vim_snippets#Filename()`} class ${1:`vim_snippets#Filename()`}
{ {
${0} ${0}
@ -81,13 +78,14 @@ snippet $s
#getter #getter
snippet $g snippet $g
${1:$foo}->get${0:Bar}(); ${1:$foo}->get${0:Bar}();
# Tertiary conditional # Tertiary conditional
snippet =?: snippet =?:
$${1:foo} = ${2:true} ? ${3:a} : ${0}; $${1:foo} = ${2:true} ? ${3:a} : ${0};
snippet ?: snippet ?:
${1:true} ? ${2:a} : ${0} ${1:true} ? ${2:a} : ${0}
snippet t "$retVal = (condition) ? a : b"
$${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};
# Predefined variables
snippet C snippet C
$_COOKIE['${1:variable}'] $_COOKIE['${1:variable}']
snippet E snippet E
@ -104,7 +102,12 @@ snippet S
$_SERVER['${1:variable}'] $_SERVER['${1:variable}']
snippet SS snippet SS
$_SESSION['${1:variable}'] $_SESSION['${1:variable}']
snippet get "get"
$_GET['${1}']
snippet post "post"
$_POST['${1}']
snippet session "session"
$_SESSION['${1}']
# the following are old ones # the following are old ones
snippet inc snippet inc
include '${1:file}'; include '${1:file}';
@ -205,7 +208,19 @@ snippet doc_h
* @copyright ${4:$2}, `strftime('%d %B, %Y')` * @copyright ${4:$2}, `strftime('%d %B, %Y')`
* @package ${0:default} * @package ${0:default}
*/ */
snippet doc_i "interface someClass {}"
/**
* $1
* @package ${2:default}
* @author ${3:`!v g:snips_author`}
**/
interface ${1:someClass}
{${4}
}
snippet inheritdoc "@inheritdoc docblock"
/**
* {@inheritdoc}
*/
# Interface # Interface
snippet interface snippet interface
/** /**
@ -254,55 +269,54 @@ snippet nc
${0} ${0}
} }
# define(...) # define(...)
snippet def snippet def "define('VARIABLE_NAME', 'definition')"
define('${1}'${2}); define('${1:VARIABLE_NAME}', ${2:'definition'});
# defined(...) # defined(...)
snippet def? snippet def?
${1}defined('${2}') ${1}defined('${2}')
snippet wh snippet wh "while (condition) { ... }"
while (${1:/* condition */}) { while (${1:/* condition */}) {
${0} ${0}
} }
# do ... while snippet do "do { ... } while (condition)"
snippet do
do { do {
${0} ${0}
} while (${1:/* condition */}); } while (${1});
snippet if snippet if "if (condition) { ... }"
if (${1:/* condition */}) { if (${1}) {
${0} ${0}
} }
snippet ifn snippet ifn "if (!condition) { ... }"
if (!${1:/* condition */}) { if (!${1}) {
${2} ${2}
} }
snippet ifil snippet ifil "<?php if (condition): ?> ... <?php endif; ?>"
<?php if (${1:/* condition */}): ?> <?php if (${1}): ?>
${0} ${0}
<?php endif; ?> <?php endif; ?>
snippet ife snippet ife "if (cond) { ... } else { ... }"
if (${1:/* condition */}) { if (${1}) {
${2} ${2}
} else { } else {
${3} ${3}
} }
${0} ${0}
snippet ifeil snippet ifeil "<?php if (condition): ?> ... <?php else: ?> ... <?php endif; ?>"
<?php if (${1:/* condition */}): ?> <?php if (${1}): ?>
${2:<!-- html... -->} ${2}
<?php else: ?> <?php else: ?>
${3:<!-- html... -->} ${3}
<?php endif; ?> <?php endif; ?>
${0} ${0}
snippet el snippet el "else { ... }"
else { else {
${0} ${0}
} }
snippet eif snippet eif "elseif(condition) { ... }"
elseif (${1}) { elseif (${1}) {
${0} ${0}
} }
snippet switch snippet switch "switch($var) { case 'xyz': ... default: .... }"
switch ($${1:variable}) { switch ($${1:variable}) {
case '${2:value}': case '${2:value}':
${3} ${3}
@ -312,34 +326,33 @@ snippet switch
${4} ${4}
break; break;
} }
snippet case snippet case "case 'value': ... break"
case '${1:value}': case '${1:value}':
${2} ${2}
break; break;
snippet for snippet for "for ($i = 0; $i < $count; $i++) { ... }"
for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) { for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {
${0} ${0}
} }
snippet foreach snippet foreach "foreach ($var as $value) { .. }"
foreach ($${1:variable} as $${2:value}) { foreach ($${1:variable} as $${2:value}) {
${0} ${0}
} }
snippet foreachil snippet foreachil "<?php foreach ($var as $value): ?> ... <?php endforeach; ?>"
<?php foreach ($${1:variable} as $${2:value}): ?> <?php foreach ($${1:variable} as $${2:value}): ?>
${0:<!-- html... -->} ${0}
<?php endforeach; ?> <?php endforeach; ?>
snippet foreachk snippet foreachk "foreach ($var as $key => $value) { .. }"
foreach ($${1:variable} as $${2:key} => $${3:value}) { foreach ($${1:variable} as $${2:key} => $${3:value}) {
${0} ${0}
} }
snippet foreachkil snippet foreachkil "<?php foreach ($var as $key => $value): ?> ... <?php endforeach; ?>"
<?php foreach ($${1:variable} as $${2:key} => $${3:value}): ?> <?php foreach ($${1:variable} as $${2:key} => $${3:value}): ?>
${0:<!-- html... -->} ${0:<!-- html... -->}
<?php endforeach; ?> <?php endforeach; ?>
# $... = array (...) snippet array "$... = array(...)"
snippet array b
$${1:arrayName} = array('${2}' => ${3}); $${1:arrayName} = array('${2}' => ${3});
snippet try snippet try "try { ... } catch (Exception $e) { ... }"
try { try {
${0} ${0}
} catch (${1:Exception} $e) { } catch (${1:Exception} $e) {
@ -369,6 +382,14 @@ snippet http_redirect
header ("HTTP/1.1 301 Moved Permanently"); header ("HTTP/1.1 301 Moved Permanently");
header ("Location: ".URL); header ("Location: ".URL);
exit(); exit();
snippet log "error_log(var_export($var, true));"
error_log(var_export(${1}, true));
snippet var "var_export($var)"
var_export(${1});
snippet ve "Dumb debug helper in HTML"
echo '<pre>' . var_export(${1}, 1) . '</pre>';
snippet pc "Dumb debug helper in cli"
var_export($1);$0
# Getters & Setters # Getters & Setters
snippet gs snippet gs
/** /**
@ -425,14 +446,12 @@ snippet aw
array_walk($${1:foo}, function(&$${2:v}, $${3:k}) { array_walk($${1:foo}, function(&$${2:v}, $${3:k}) {
$$2 = ${0}; $$2 = ${0};
}); });
# static var assign once # static var assign once
snippet static_var snippet static_var
static $${1} = null; static $${1} = null;
if (is_null($$1)){ if (is_null($$1)){
$$1 = ${2}; $$1 = ${2};
} }
snippet CSVWriter snippet CSVWriter
<?php <?php
@ -467,7 +486,6 @@ snippet CSVWriter
} }
} }
snippet CSVIterator snippet CSVIterator
// http://snipplr.com/view.php?codeview&id=1986 // modified // http://snipplr.com/view.php?codeview&id=1986 // modified
@ -570,72 +588,75 @@ snippet CSVIterator
} }
} // end class } // end class
# phpunit
snippet is snippet ase "$this->assertEquals()"
isset($1{VISUAL})
# phpunit
snippet ase
$this->assertEquals(${1:expected}, ${2:actual}); $this->assertEquals(${1:expected}, ${2:actual});
snippet asne "$this->assertNotEquals()"
snippet asne
$this->assertNotEquals(${1:expected}, ${2:actual}); $this->assertNotEquals(${1:expected}, ${2:actual});
snippet asf "$this->assertFalse()"
snippet asf $this->assertFalse(${1});
$this->assertFalse(${1:Something}); snippet ast "$this->assertTrue()"
$this->assertTrue(${1});
snippet ast snippet asfex "$this->assertFileExists()"
$this->assertTrue(${1:Something}); $this->assertFileExists(${1:'path/to/file'});
snippet asfnex "$this->assertFileNotExists()"
snippet asfex $this->assertFileNotExists(${1:'path/to/file'});
$this->assertFileExists(${1:path/to/file}); snippet ascon "$this->assertContains()"
$this->assertContains(${1:$needle}, ${2:$haystack});
snippet asfnex snippet ashk "$this->assertArrayHasKey()"
$this->assertFileNotExists(${1:path/to/file}); $this->assertArrayHasKey(${1:$key}, ${2:$array});
snippet asnhk "$this->assertArrayNotHasKey()"
snippet ascon this->assertArrayNotHasKey(${1:$key}, ${2:$array});
$this->assertContains(${1:Search Value}, ${2:Array or Iterator}); snippet ascha "$this->assertClassHasAttribute()"
$this->assertClassHasAttribute(${1:$attributeName}, '${2:$className}');
snippet ashk snippet asi "$this->assertInstanceOf(...)"
$this->assertArrayHasKey(${1:key}, ${2:array});
snippet asnhk
this->assertArrayNotHasKey(${1:value}, ${2:array});
snippet ascha
$this->assertClassHasAttribute('${1:Attribute Name}', '${2:ClassName}');
snippet asi
$this->assertInstanceOf(${1:expected}, ${2:actual}); $this->assertInstanceOf(${1:expected}, ${2:actual});
snippet test "public function testXYZ() { ... }"
snippet tc public function test${1}()
public function test${1:name_of_the_test}()
{ {
${0:code} ${0}
} }
snippet te snippet setup "protected function setUp() { ... }"
protected function setUp()
{
${0}
}
snippet teardown "protected function tearDown() { ... }"
protected function tearDown()
{
${0}
}
snippet exp "phpunit expects"
expects($this->${1:once}())
->method('${2}')
->with($this->equalTo(${3})${4})
->will($this->returnValue(${5}));
snippet testcmt "phpunit comment with group"
/**
* @group ${1}
*/
snippet fail "$this->fail()"
$this->fail(${1});
snippet marki "$this->markTestIncomplete()"
$this->markTestIncomplete(${1});
snippet marks "$this->markTestSkipped()"
$this->markTestSkipped(${1});
# end of phpunit snippets
snippet te "throw new Exception()"
throw new ${1:Exception}("${2:Error Processing Request}"); throw new ${1:Exception}("${2:Error Processing Request}");
snippet fpc "file_put_contents" b snippet fpc "file_put_contents" b
file_put_contents(${1:file}, ${2:content}${3:, FILE_APPEND});$0 file_put_contents(${1:file}, ${2:content}${3:, FILE_APPEND});$0
snippet sr "str_replace" snippet sr "str_replace"
str_replace(${1:search}, ${2:replace}, ${3:subject})$0 str_replace(${1:search}, ${2:replace}, ${3:subject})$0
snippet ia "in_array" snippet ia "in_array"
in_array(${1:needle}, ${2:haystack})$0 in_array(${1:needle}, ${2:haystack})$0
snippet is "isset" snippet is "isset"
isset(${1:var})$0 isset(${1:var})$0
snippet isa "isset array" snippet isa "isset array"
isset($${1:array}[${2:key}])$0 isset($${1:array}[${2:key}])$0
snippet in "is_null" snippet in "is_null"
is_null($${1:var})$0 is_null($${1:var})$0
snippet fe "file_exists" snippet fe "file_exists"
file_exists(${1:file})$0 file_exists(${1:file})$0
snippet id "is_dir" snippet id "is_dir"
is_dir(${1:path})$0 is_dir(${1:path})$0

View file

@ -1,5 +1,7 @@
snippet enc snippet enc
# encoding: utf-8 # encoding: utf-8
snippet frozen
# frozen_string_literal: true
snippet #! snippet #!
#!/usr/bin/env ruby #!/usr/bin/env ruby
# New Block # New Block

View file

@ -1,43 +1,34 @@
# twig block snippet bl "{% block xyz %} .. {% endblock xyz %}"
snippet bl
{% block ${1} %} {% block ${1} %}
${2} ${2}
{% endblock $1 %} {% endblock $1 %}
# twig javascripts snippet js "{% javascripts 'xyz' %} .. {% endjavascripts %}"
snippet js
{% javascripts '${1}' %} {% javascripts '${1}' %}
<script src="{{ asset_url }}"></script> <script src="{{ asset_url }}"></script>
{% endjavascripts %} {% endjavascripts %}
# twig stylesheets snippet css "{% stylesheets 'xyz' %} .. {% endstylesheets %}"
snippet css
{% stylesheets '${1}' %} {% stylesheets '${1}' %}
<link rel="stylesheet" href="{{ asset_url }}"> <link rel="stylesheet" href="{{ asset_url }}">
{% endstylesheets %} {% endstylesheets %}
# twig if snippet if "{% if %} .. {% endif %}"
snippet if
{% if ${1} %} {% if ${1} %}
${2} ${2}
{% endif %} {% endif %}
# twig if ... else snippet ife "{% if %} .. {% else %} .. {% endif %}"
snippet ife
{% if ${1} %} {% if ${1} %}
${2} ${2}
{% else %} {% else %}
${0} ${0}
{% endif %} {% endif %}
# twig else snippet el "{% else %}"
snippet el
{% else %} {% else %}
${0} ${0}
# twig elseif snippet eif "{% elseif %}"
snippet eif
{% elseif ${1} %} {% elseif ${1} %}
${0} ${0}
# twig for snippet for "{% for x in y %} .. {% endfor %}"
snippet for
{% for ${1} in ${2} %} {% for ${1} in ${2} %}
${3} ${3}
{% endfor %} {% endfor %}
# twig extends snippet ext "{% extends xyz %}"
snippet ext
{% extends ${1} %} {% extends ${1} %}

View file

@ -92,7 +92,7 @@ function! s:process(string)
let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i)) let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i))
if m != '' if m != ''
let m = substitute(strpart(m,1),'\r.*','','') let m = substitute(strpart(m,1),'\r.*','','')
let repl_{i} = input(substitute(m,':\s*$','','').': ') let repl_{i} = input(match(m,'\w\+$') >= 0 ? m.': ' : m)
endif endif
endfor endfor
let s = "" let s = ""