1
0
Fork 0
mirror of synced 2024-11-22 16:55:34 -05:00

Updated plugins

This commit is contained in:
amix 2014-04-18 13:58:02 +01:00
parent ac3ef260c8
commit 6a16a9393c
91 changed files with 2554 additions and 708 deletions

View file

@ -1,101 +1,60 @@
# ack.vim # # ack.vim
This plugin is a front for the Perl module This plugin is a front for the Perl module
[App::Ack](http://search.cpan.org/~petdance/ack/ack). Ack can be used as a [App::Ack](http://search.cpan.org/~petdance/ack/ack). Ack can be used as a
replacement for 99% of the uses of _grep_. This plugin will allow you to run replacement for 99% of the uses of _grep_. This plugin will allow you to run
ack from vim, and shows the results in a split window. ack from vim, and shows the results in a split window.
The *Official Version* of this plugin is available at [vim.org](http://www.vim.org/scripts/script.php?script_id=2572). ## Installation
## Installation ##
### Ack ### Ack
You have to install [ack](http://betterthangrep.com/), of course. You will need the ack, of course, to install it follow the
[manual](http://beyondgrep.com/install/)
Install on Debian / Ubuntu with:
sudo apt-get install ack-grep
Install on Fedora with:
su -l -c 'yum install ack'
Install on openSUSE with:
sudo zypper install ack
Install on Gentoo with:
sudo emerge ack
Install with Homebrew:
brew install ack
Install with MacPorts:
sudo port install p5-app-ack
Install with Gentoo Prefix:
emerge ack
Install on FreeBSD with:
cd /usr/ports/textproc/p5-ack/ && make install clean
You can specify a custom ack name and path in your .vimrc like so:
let g:ackprg="<custom-ack-path-goes-here> -H --nocolor --nogroup --column"
Otherwise, you are on your own.
### The Plugin ### The Plugin
If you have [Rake](http://rake.rubyforge.org/) installed, you can just run: `rake install`. To install it is recommended to use one of the popular package managers for Vim,
rather than installing by drag and drop all required files into your `.vim` folder.
Otherwise, the file ack.vim goes in ~/.vim/plugin, and the ack.txt file belongs in ~/.vim/doc. Be sure to run #### Manual (not recommended)
:helptags ~/.vim/doc Just
[download](https://github.com/mileszs/ack.vim/archive/kb-improve-readme.zip) the
plugin and put it in your `~/.vim/`(or `%PROGRAMFILES%/Vim/vimfiles` on windows)
afterwards. #### Vundle
Bundle 'mileszs/ack.vim'
## Usage ## #### NeoBundle
:Ack [options] {pattern} [{directory}] NeoBundle 'mileszs/ack.vim'
Search recursively in {directory} (which defaults to the current directory) for the {pattern}. ## Usage
:Ack [options] {pattern} [{directories}]
Search recursively in {directory} (which defaults to the current directory) for
the {pattern}.
Files containing the search term will be listed in the split window, along with Files containing the search term will be listed in the split window, along with
the line number of the occurrence, once for each occurrence. [Enter] on a line the line number of the occurrence, once for each occurrence. [Enter] on a line
in this window will open the file, and place the cursor on the matching line. in this window will open the file, and place the cursor on the matching line.
Just like where you use :grep, :grepadd, :lgrep, and :lgrepadd, you can use `:Ack`, `:AckAdd`, `:LAck`, and `:LAckAdd` respectively. (See `doc/ack.txt`, or install and `:h Ack` for more information.) Just like where you use :grep, :grepadd, :lgrep, and :lgrepadd, you can use
`:Ack`, `:AckAdd`, `:LAck`, and `:LAckAdd` respectively.
(See `doc/ack.txt`, or install and `:h Ack` for more information.)
**From the [ack docs](http://betterthangrep.com/)** (my favorite feature): For more ack options see
[ack documentation](http://beyondgrep.com/documentation/)
--type=TYPE, --type=noTYPE ### Keyboard Shortcuts
Specify the types of files to include or exclude from a search. TYPE is a filetype, like perl or xml. --type=perl can also be specified as --perl, and --type=noperl can be done as --noperl.
If a file is of both type "foo" and "bar", specifying --foo and --nobar will exclude the file, because an exclusion takes precedence over an inclusion.
Type specifications can be repeated and are ORed together.
See ack --help=types for a list of valid types.
### Gotchas ###
Some characters have special meaning, and need to be escaped your search pattern. For instance, '#'. You have to escape it like this `:Ack '\\\#define foo'` to search for `#define foo`. (From [blueyed in issue #5](https://github.com/mileszs/ack.vim/issues/5).)
### Keyboard Shortcuts ###
In the quickfix window, you can use: In the quickfix window, you can use:
o to open (same as enter) o to open (same as enter)
O to open and close quickfix window
go to preview file (open but maintain focus on ack.vim results) go to preview file (open but maintain focus on ack.vim results)
t to open in new tab t to open in new tab
T to open in new tab silently T to open in new tab silently
@ -106,9 +65,29 @@ In the quickfix window, you can use:
q to close the quickfix window q to close the quickfix window
This Vim plugin is derived (and by derived, I mean copied, essentially) from This Vim plugin is derived (and by derived, I mean copied, essentially) from
Antoine Imbert's blog post [Ack and Vim Antoine Imbert's blog post
Integration](http://blog.ant0ine.com/typepad/2007/03/ack-and-vim-integration.html) (in [Ack and Vim Integration](http://blog.ant0ine.com/typepad/2007/03/ack-and-vim-integration.html)
particular, the function at the bottom of the post). I added a help file that (in particular, the function at the bottom of the post). I added a help file that
provides just enough reference to get you going. I also highly recommend you provides just enough reference to get you going. I also highly recommend you
check out the docs for the Perl script 'ack', for obvious reasons: [ack - check out the docs for the Perl script 'ack', for obvious reasons:
grep-like text finder](http://betterthangrep.com/). [ack - grep-like text finder](http://beyondgrep.com/).
### Gotchas
Some characters have special meaning, and need to be escaped your search
pattern. For instance, '#'. You have to escape it like this :Ack '\\\#define
foo' to search for #define foo. (From blueyed in issue #5.)
## Changelog
### 1.0
* Remove support to ack 1.x
* Start to use a Changelog
* Use `autoload` directory to define functions, instead of `plugin`.
* Add option to auto fold the results(`g:ack_autofold_results`)
* Improve documentation, list all options and shortcuts
* Improve highlight option to work when passes directories or use quotes.
* Add g:ack_mapping
* Add g:ack_default_options
* Add a help toggle `?`(like NERDTree)

View file

@ -1,23 +0,0 @@
# Added by Josh Nichols, a.k.a. technicalpickles
require 'rake'
files = ['doc/ack.txt', 'plugin/ack.vim']
desc 'Install plugin and documentation'
task :install do
vimfiles = if ENV['VIMFILES']
ENV['VIMFILES']
elsif RUBY_PLATFORM =~ /(win|w)32$/
File.expand_path("~/vimfiles")
else
File.expand_path("~/.vim")
end
files.each do |file|
target_file = File.join(vimfiles, file)
FileUtils.mkdir_p File.dirname(target_file)
FileUtils.cp file, target_file
puts " Copied #{file} to #{target_file}"
end
end

View file

@ -0,0 +1,143 @@
function! ack#Ack(cmd, args)
redraw
echo "Searching ..."
" If no pattern is provided, search for the word under the cursor
if empty(a:args)
let l:grepargs = expand("<cword>")
else
let l:grepargs = a:args . join(a:000, ' ')
end
let l:ackprg_run = g:ackprg
" Format, used to manage column jump
if a:cmd =~# '-g$'
let g:ackformat="%f"
let l:ackprg_run = substitute(l:ackprg_run, '-H\|--column', '', 'g')
else
let g:ackformat="%f:%l:%c:%m,%f:%l:%m"
endif
let grepprg_bak = &grepprg
let grepformat_bak = &grepformat
let &grepprg=l:ackprg_run
let &grepformat=g:ackformat
try
" NOTE: we escape special chars, but not everything using shellescape to
" allow for passing arguments etc
silent execute a:cmd . " " . escape(l:grepargs, '|#%')
finally
let &grepprg=grepprg_bak
let &grepformat=grepformat_bak
endtry
if a:cmd =~# '^l'
let s:handler = g:ack_lhandler
let s:apply_mappings = g:ack_apply_lmappings
let s:close_cmd = ':lclose<CR>'
else
let s:handler = g:ack_qhandler
let s:apply_mappings = g:ack_apply_qmappings
let s:close_cmd = ':cclose<CR>'
endif
call ack#show_results()
call <SID>highlight(l:grepargs)
redraw!
endfunction
function! ack#show_results()
execute s:handler
call <SID>apply_maps()
endfunction
function! s:apply_maps()
let g:ack_mappings.q = s:close_cmd
execute "nnoremap <buffer> <silent> ? :call ack#quick_help()<CR>"
if s:apply_mappings && &ft == "qf"
if g:ack_autoclose
for key_map in items(g:ack_mappings)
execute printf("nnoremap <buffer> <silent> %s %s", get(key_map, 0), get(key_map, 1) . s:close_cmd)
endfor
execute "nnoremap <buffer> <silent> <CR> <CR>" . s:close_cmd
else
for key_map in items(g:ack_mappings)
execute printf("nnoremap <buffer> <silent> %s %s", get(key_map, 0), get(key_map, 1))
endfor
endif
if exists("g:ackpreview") " if auto preview in on, remap j and k keys
execute "nnoremap <buffer> <silent> j j<CR><C-W><C-W>"
execute "nnoremap <buffer> <silent> k k<CR><C-W><C-W>"
endif
endif
endfunction
function! ack#quick_help()
execute "edit " . globpath(&rtp, "doc/ack_quick_help.txt")
silent normal gg
setlocal buftype=nofile
setlocal bufhidden=hide
setlocal noswapfile
setlocal nobuflisted
setlocal nomodifiable
setlocal filetype=help
setlocal nonumber
setlocal norelativenumber
setlocal nowrap
setlocal foldlevel=20
setlocal foldmethod=diff
nnoremap <buffer> <silent> ? :q!<CR>:call ack#show_results()<CR>
endfunction
function! s:highlight(args)
if !g:ackhighlight
return
endif
let @/ = matchstr(a:args, "\\v\\w+\>|['\"]\\zs[^\"]+\\ze['\"]")
setlocal hlsearch
call feedkeys(":let v:hlsearch=1 \| echo \<CR>", "n")
endfunction
function! ack#AckFromSearch(cmd, args)
let search = getreg('/')
" translate vim regular expression to perl regular expression.
let search = substitute(search, '\(\\<\|\\>\)', '\\b', 'g')
call ack#Ack(a:cmd, '"' . search . '" ' . a:args)
endfunction
function! s:GetDocLocations()
let dp = ''
for p in split(&rtp, ',')
let p = p . '/doc/'
if isdirectory(p)
let dp = p . '*.txt ' . dp
endif
endfor
return dp
endfunction
function! ack#AckHelp(cmd, args)
let args = a:args . ' ' . s:GetDocLocations()
call ack#Ack(a:cmd, args)
endfunction
function! ack#AckWindow(cmd, args)
let files = tabpagebuflist()
" remove duplicated filenames (files appearing in more than one window)
let files = filter(copy(sort(files)), 'index(files,v:val,v:key+1)==-1')
call map(files, "bufname(v:val)")
" remove unnamed buffers as quickfix (empty strings before shellescape)
call filter(files, 'v:val != ""')
" expand to full path (avoid problems with cd/lcd in au QuickFixCmdPre)
let files = map(files, "shellescape(fnamemodify(v:val, ':p'))")
let args = a:args . ' ' . join(files)
call ack#Ack(a:cmd, args)
endfunction

View file

@ -16,7 +16,7 @@ shows the results in a split window.
Search recursively in {directory} (which defaults to the current Search recursively in {directory} (which defaults to the current
directory) for the {pattern}. Behaves just like the |:grep| command, but directory) for the {pattern}. Behaves just like the |:grep| command, but
will open the |Quickfix| window for you. If [!] is not given the first will open the |Quickfix| window for you. If [!] is not given the first
error is jumped to. occurence is jumped to.
:AckAdd [options] {pattern} [{directory}] *:AckAdd* :AckAdd [options] {pattern} [{directory}] *:AckAdd*
@ -53,6 +53,16 @@ shows the results in a split window.
Just like |:AckHelp| but instead of the |quickfix| list, matches are placed Just like |:AckHelp| but instead of the |quickfix| list, matches are placed
in the current |location-list|. in the current |location-list|.
:AckWindow[!] [options] {pattern} *:AckWindow*
Search all buffers visible in the screen (current tab page only) files for
the {pattern}.
:LAckWindow [options] {pattern} *:LAckWindow*
Just like |:AckWindow| but instead of the |quickfix| list, matches are
placed in the current |location-list|.
Files containing the search term will be listed in the split window, along Files containing the search term will be listed in the split window, along
with the line number of the occurrence, once for each occurrence. <Enter> on with the line number of the occurrence, once for each occurrence. <Enter> on
a line in this window will open the file, and place the cursor on the matching a line in this window will open the file, and place the cursor on the matching
@ -60,6 +70,139 @@ line.
See http://betterthangrep.com/ for more information. See http://betterthangrep.com/ for more information.
==============================================================================
CONFIGURATION *ack-configuration*
*g:ackprg*
g:ackprg
Default for ubuntu: "ack-grep"
Default for other systems: "ack"
Use this option to specify the ack command and its options
Example:
>
let g:ackprg = "other-bin-ack"
<
g:ack_default_options*
g:ack_default_options
Default: " -s -H --nocolor --nogroup --column"
Use this option to specify the options used by ack
Example:
>
let g:ackprg =
\ " -s -H --nocolor --nogroup --column --smart-case --follow"
<
*g:ack_apply_qmappings*
g:ack_apply_qmappings
Default: 1
This option enable mappings on quickview window.
*g:ack_apply_lmappings*
g:ack_apply_lmappings
Default: 1
This option enable mappings on Location list window.
*g:ack_mappings*
g:ack_mappings
Default: {
\ "t": "<C-W><CR><C-W>T",
\ "T": "<C-W><CR><C-W>TgT<C-W>j",
\ "o": "<CR>",
\ "O": "<CR><C-W><C-W>:ccl<CR>",
\ "go": "<CR><C-W>j",
\ "h": "<C-W><CR><C-W>K",
\ "H": "<C-W><CR><C-W>K<C-W>b",
\ "v": "<C-W><CR><C-W>H<C-W>b<C-W>J<C-W>t",
\ "gv": "<C-W><CR><C-W>H<C-W>b<C-W>J" }
This option list all maps create on quickfix/Location list window.
Example, if you want to open the result in the middle of the screen:
>
let g:ack_mappings = { "o": "<CR>zz" }
<
*g:ack_qhandler*
g:ack_qhandler
Default: "botright copen"
Command to open the quickview window.
If you want to open a quickview window with 30 lines you can do:
>
let g:ack_qhandler = "botright copen 30"
<
*g:ack_lhandler*
g:ack_lhandler
Default: "botright lopen"
Command to open the Location list window.
If you want to open a Location list window with 30 lines you can do:
>
let g:ack_lhandler = "botright lopen 30"
<
*g:ackhighlight*
g:ackhighlight
Default: 0
Use this option to highlight the searched term.
Example:
>
let g:ackhighlight = 1
<
*g:ack_autoclose*
g:ack_autoclose
Default: 0
Use this option to specify whether to close the quickfix window after
using any of the shortcuts.
Example:
>
let g:ack_autoclose = 1
<
*g:ack_autofold_results*
g:ack_autofold_results
Default: 0
Use this option to fold the results in quickfix by file name. Only the current
fold will be open by default and while you press 'j' and 'k' to move between the
results if you hit other fold the last one will be closed and the current will
be open.
Example:
>
let g:ack_autofold_results = 1
<
*g:ackpreview*
g:ackpreview
Default: 0
Use this option to automagically open the file with 'j' or 'k'.
Example:
>
let g:ackpreview = 1
<
============================================================================== ==============================================================================
MAPPINGS *ack-mappings* MAPPINGS *ack-mappings*
@ -67,6 +210,8 @@ The following keyboard shortcuts are available in the quickfix window:
o open file (same as enter). o open file (same as enter).
O open file and close quickfix window.
go preview file (open but maintain focus on ack.vim results). go preview file (open but maintain focus on ack.vim results).
t open in a new tab. t open in a new tab.

View file

@ -0,0 +1,14 @@
==== ack.vim quick help ===============
*?:* Show this help
*t:* Open in a new tab
*T:* Open in a new tab silently
*o:* Open
*O:* Open and close result window
*go:* Preview
*h:* Horizontal open
*H:* Horizontal open silently
*v:* Vertical open
*gv:* Vertical open silently
========================================

View file

@ -0,0 +1,9 @@
if g:ack_autofold_results
setlocal foldlevel=0
setlocal foldmethod=expr
setlocal foldexpr=matchstr(getline(v:lnum),'^[^\|]\\+')==#matchstr(getline(v:lnum+1),'^[^\|]\\+')?1:'<1'
setlocal foldenable
setlocal foldclose=all
setlocal foldopen=all
nnoremap <buffer> j jzz
endif

View file

@ -1,16 +1,17 @@
" NOTE: You must, of course, install the ack script if !exists("g:ack_default_options")
" in your path. let g:ack_default_options = " -s -H --nocolor --nogroup --column"
" On Debian / Ubuntu: endif
" sudo apt-get install ack-grep
" With MacPorts:
" sudo port install p5-app-ack
" With Homebrew:
" brew install ack
" Location of the ack utility " Location of the ack utility
if !exists("g:ackprg") if !exists("g:ackprg")
let s:ackcommand = executable('ack-grep') ? 'ack-grep' : 'ack' if executable('ack')
let g:ackprg=s:ackcommand." -H --nocolor --nogroup --column" let g:ackprg = "ack"
elseif executable('ack-grep')
let g:ackprg = "ack-grep"
else
finish
endif
let g:ackprg .= g:ack_default_options
endif endif
if !exists("g:ack_apply_qmappings") if !exists("g:ack_apply_qmappings")
@ -21,102 +22,50 @@ if !exists("g:ack_apply_lmappings")
let g:ack_apply_lmappings = !exists("g:ack_lhandler") let g:ack_apply_lmappings = !exists("g:ack_lhandler")
endif endif
let s:ack_mappings = {
\ "t": "<C-W><CR><C-W>T",
\ "T": "<C-W><CR><C-W>TgT<C-W>j",
\ "o": "<CR>",
\ "O": "<CR><C-W><C-W>:ccl<CR>",
\ "go": "<CR><C-W>j",
\ "h": "<C-W><CR><C-W>K",
\ "H": "<C-W><CR><C-W>K<C-W>b",
\ "v": "<C-W><CR><C-W>H<C-W>b<C-W>J<C-W>t",
\ "gv": "<C-W><CR><C-W>H<C-W>b<C-W>J" }
if exists("g:ack_mappings")
let g:ack_mappings = extend(s:ack_mappings, g:ack_mappings)
else
let g:ack_mappings = s:ack_mappings
endif
if !exists("g:ack_qhandler") if !exists("g:ack_qhandler")
let g:ack_qhandler="botright copen" let g:ack_qhandler = "botright copen"
endif endif
if !exists("g:ack_lhandler") if !exists("g:ack_lhandler")
let g:ack_lhandler="botright lopen" let g:ack_lhandler = "botright lopen"
endif endif
function! s:Ack(cmd, args) if !exists("g:ackhighlight")
redraw let g:ackhighlight = 0
echo "Searching ..." endif
" If no pattern is provided, search for the word under the cursor if !exists("g:ack_autoclose")
if empty(a:args) let g:ack_autoclose = 0
let l:grepargs = expand("<cword>") endif
else
let l:grepargs = a:args . join(a:000, ' ')
end
" Format, used to manage column jump if !exists("g:ack_autofold_results")
if a:cmd =~# '-g$' let g:ack_autofold_results = 0
let g:ackformat="%f" endif
else
let g:ackformat="%f:%l:%c:%m,%f:%l:%m"
end
let grepprg_bak=&grepprg command! -bang -nargs=* -complete=file Ack call ack#Ack('grep<bang>', <q-args>)
let grepformat_bak=&grepformat command! -bang -nargs=* -complete=file AckAdd call ack#Ack('grepadd<bang>', <q-args>)
try command! -bang -nargs=* -complete=file AckFromSearch call ack#AckFromSearch('grep<bang>', <q-args>)
let &grepprg=g:ackprg command! -bang -nargs=* -complete=file LAck call ack#Ack('lgrep<bang>', <q-args>)
let &grepformat=g:ackformat command! -bang -nargs=* -complete=file LAckAdd call ack#Ack('lgrepadd<bang>', <q-args>)
silent execute a:cmd . " " . escape(l:grepargs, '|') command! -bang -nargs=* -complete=file AckFile call ack#Ack('grep<bang> -g', <q-args>)
finally command! -bang -nargs=* -complete=help AckHelp call ack#AckHelp('grep<bang>', <q-args>)
let &grepprg=grepprg_bak command! -bang -nargs=* -complete=help LAckHelp call ack#AckHelp('lgrep<bang>', <q-args>)
let &grepformat=grepformat_bak command! -bang -nargs=* -complete=help AckWindow call ack#AckWindow('grep<bang>', <q-args>)
endtry command! -bang -nargs=* -complete=help LAckWindow call ack#AckWindow('lgrep<bang>', <q-args>)
if a:cmd =~# '^l'
exe g:ack_lhandler
let l:apply_mappings = g:ack_apply_lmappings
let l:close_cmd = ':lclose<CR>'
else
exe g:ack_qhandler
let l:apply_mappings = g:ack_apply_qmappings
let l:close_cmd = ':cclose<CR>'
endif
if l:apply_mappings
exec "nnoremap <silent> <buffer> q " . l:close_cmd
exec "nnoremap <silent> <buffer> t <C-W><CR><C-W>T"
exec "nnoremap <silent> <buffer> T <C-W><CR><C-W>TgT<C-W><C-W>"
exec "nnoremap <silent> <buffer> o <CR>"
exec "nnoremap <silent> <buffer> go <CR><C-W><C-W>"
exec "nnoremap <silent> <buffer> h <C-W><CR><C-W>K"
exec "nnoremap <silent> <buffer> H <C-W><CR><C-W>K<C-W>b"
exec "nnoremap <silent> <buffer> v <C-W><CR><C-W>H<C-W>b<C-W>J<C-W>t"
exec "nnoremap <silent> <buffer> gv <C-W><CR><C-W>H<C-W>b<C-W>J"
endif
" If highlighting is on, highlight the search keyword.
if exists("g:ackhighlight")
let @/ = substitute(l:grepargs,'["'']','','g')
set hlsearch
end
redraw!
endfunction
function! s:AckFromSearch(cmd, args)
let search = getreg('/')
" translate vim regular expression to perl regular expression.
let search = substitute(search,'\(\\<\|\\>\)','\\b','g')
call s:Ack(a:cmd, '"' . search .'" '. a:args)
endfunction
function! s:GetDocLocations()
let dp = ''
for p in split(&rtp,',')
let p = p.'/doc/'
if isdirectory(p)
let dp = p.'*.txt '.dp
endif
endfor
return dp
endfunction
function! s:AckHelp(cmd,args)
let args = a:args.' '.s:GetDocLocations()
call s:Ack(a:cmd,args)
endfunction
command! -bang -nargs=* -complete=file Ack call s:Ack('grep<bang>',<q-args>)
command! -bang -nargs=* -complete=file AckAdd call s:Ack('grepadd<bang>', <q-args>)
command! -bang -nargs=* -complete=file AckFromSearch call s:AckFromSearch('grep<bang>', <q-args>)
command! -bang -nargs=* -complete=file LAck call s:Ack('lgrep<bang>', <q-args>)
command! -bang -nargs=* -complete=file LAckAdd call s:Ack('lgrepadd<bang>', <q-args>)
command! -bang -nargs=* -complete=file AckFile call s:Ack('grep<bang> -g', <q-args>)
command! -bang -nargs=* -complete=help AckHelp call s:AckHelp('grep<bang>',<q-args>)
command! -bang -nargs=* -complete=help LAckHelp call s:AckHelp('lgrep<bang>',<q-args>)

View file

@ -46,7 +46,7 @@ function! s:init_pad(command)
execute a:command execute a:command
setlocal buftype=nofile bufhidden=wipe nomodifiable nobuflisted noswapfile setlocal buftype=nofile bufhidden=wipe nomodifiable nobuflisted noswapfile
\ nonu nocursorline winfixwidth winfixheight statusline=\ \ nonu nocursorline nocursorcolumn winfixwidth winfixheight statusline=\
if exists('&rnu') if exists('&rnu')
setlocal nornu setlocal nornu
endif endif
@ -115,6 +115,8 @@ function! s:tranquilize()
endfunction endfunction
function! s:goyo_on(width) function! s:goyo_on(width)
let s:orig_tab = tabpagenr()
" New tab " New tab
tab split tab split
@ -249,6 +251,7 @@ function! s:goyo_off()
bd bd
endif endif
tabclose tabclose
execute 'normal! '.s:orig_tab.'gt'
let wmh = remove(goyo_revert, 'winminheight') let wmh = remove(goyo_revert, 'winminheight')
let wh = remove(goyo_revert, 'winheight') let wh = remove(goyo_revert, 'winheight')

View file

@ -29,7 +29,7 @@ Following the coding conventions/styles used in the syntastic core:
* Use 4 space indents. * Use 4 space indents.
* Don't use abbreviated keywords - e.g. use `endfunction`, not `endfun` (there's always room for more fun!). * Don't use abbreviated keywords - e.g. use `endfunction`, not `endfun` (there's always room for more fun!).
* Don't use `l:` prefixes for variables unless actually required (i.e. almost never). * Don't use `l:` prefixes for variables unless actually required (i.e. almost never).
* Code for maintainability. We would rather a function be a couple of lines longer and have (for example) some [explaining variables](http://www.refactoring.com/catalog/introduceExplainingVariable.html) to aid readability. * Code for maintainability. We would rather a function be a couple of lines longer and have (for example) some [explaining variables](http://www.refactoring.com/catalog/extractVariable.html) to aid readability.
# Syntax checker style notes # Syntax checker style notes

View file

@ -40,10 +40,11 @@ CoffeeScript, Coco, Coq, CSS, Cucumber, CUDA, D, Dart, DocBook, Dust, Elixir,
Erlang, eRuby, Fortran, Gentoo metadata, GLSL, Go, Haml, Haskell, Haxe, Erlang, eRuby, Fortran, Gentoo metadata, GLSL, Go, Haml, Haskell, Haxe,
Handlebars, HSS, HTML, Java, JavaScript, JSON, JSX, LESS, Lex, Limbo, LISP, Handlebars, HSS, HTML, Java, JavaScript, JSON, JSX, LESS, Lex, Limbo, LISP,
LLVM intermediate language, Lua, MATLAB, NASM, Objective-C, Objective-C++, LLVM intermediate language, Lua, MATLAB, NASM, Objective-C, Objective-C++,
OCaml, Perl, Perl POD, PHP, gettext Portable Object, Puppet, Python, Racket, OCaml, Perl, Perl POD, PHP, gettext Portable Object, OS X and iOS property
reStructuredText, Ruby, Rust, SASS/SCSS, Scala, Slim, Tcl, TeX, Texinfo, Twig, lists, Puppet, Python, Racket, R, reStructuredText, Ruby, Rust, SASS/SCSS,
TypeScript, Vala, Verilog, VHDL, VimL, xHtml, XML, XSLT, YACC, YAML, z80, Zope Scala, Slim, Tcl, TeX, Texinfo, Twig, TypeScript, Vala, Verilog, VHDL, VimL,
page templates, and zsh. xHtml, XML, XSLT, YACC, YAML, z80, Zope page templates, and zsh. See the
[wiki][3] for details about the corresponding supported checkers.
Below is a screenshot showing the methods that Syntastic uses to display syntax Below is a screenshot showing the methods that Syntastic uses to display syntax
errors. Note that, in practise, you will only have a subset of these methods errors. Note that, in practise, you will only have a subset of these methods
@ -111,6 +112,8 @@ If you get an error when you do this, then you probably didn't install
## 3\. FAQ ## 3\. FAQ
<a name="faqinfo"></a>
__Q. I installed syntastic but it isn't reporting any errors...__ __Q. I installed syntastic but it isn't reporting any errors...__
A. The most likely reason is that none of the syntax checkers that it requires A. The most likely reason is that none of the syntax checkers that it requires
@ -125,6 +128,8 @@ error output for a syntax checker may have changed. In this case, make sure you
have the latest version of the syntax checker installed. If it still fails then have the latest version of the syntax checker installed. If it still fails then
create an issue - or better yet, create a pull request. create an issue - or better yet, create a pull request.
<a name="faqperl"></a>
__Q. The `perl` checker has stopped working...__ __Q. The `perl` checker has stopped working...__
A. The `perl` checker runs `perl -c` against your file, which in turn A. The `perl` checker runs `perl -c` against your file, which in turn
@ -138,6 +143,8 @@ still producing useful results, the checker is now disabled by default. To
let g:syntastic_enable_perl_checker = 1 let g:syntastic_enable_perl_checker = 1
``` ```
<a name="faqloclist"></a>
__Q. I run a checker and the location list is not updated...__ __Q. I run a checker and the location list is not updated...__
A. By default the location list is changed only when you run the `:Errors` A. By default the location list is changed only when you run the `:Errors`
@ -148,6 +155,8 @@ your vimrc:
let g:syntastic_always_populate_loc_list = 1 let g:syntastic_always_populate_loc_list = 1
``` ```
<a name="faqargs"></a>
__Q. How can I pass additional arguments to a checker?__ __Q. How can I pass additional arguments to a checker?__
A. Almost all syntax checkers use the `makeprgBuild()` function. Those checkers A. Almost all syntax checkers use the `makeprgBuild()` function. Those checkers
@ -162,6 +171,8 @@ let g:syntastic_ruby_mri_args = "--my --args --here"
See `:help syntastic-checker-options` for more information. See `:help syntastic-checker-options` for more information.
<a name="faqcheckers"></a>
__Q. Syntastic supports several checkers for my filetype - how do I tell it __Q. Syntastic supports several checkers for my filetype - how do I tell it
which one(s) to use?__ which one(s) to use?__
@ -190,6 +201,32 @@ let g:syntastic_php_checkers = ['php', 'phpcs', 'phpmd']
This is telling syntastic to run the `php` checker first, and if no errors are This is telling syntastic to run the `php` checker first, and if no errors are
found, run `phpcs`, and then `phpmd`. found, run `phpcs`, and then `phpmd`.
You can also run checkers explicitly by calling `:SyntasticCheck <checker>`.
e.g. to run `phpcs` and `phpmd`:
```vim
:SyntasticCheck phpcs phpmd
```
This works for any checkers available for the current filetype, even if they
aren't listed in `g:syntastic_<filetype>_checkers`. You can't run checkers for
"foreign" filetypes though (e.g. you can't run, say, a Python checker if the
current filetype is `php`).
<a name="faqaggregate"></a>
__Q. How can I display together the errors found by all checkers enabled for
the current file?__
A. Set `g:syntastic_aggregate_errors` to 1 in your vimrc:
```vim
let g:syntastic_aggregate_errors = 1
```
See `:help syntastic-aggregating-errors` for more details.
<a name="faqlnext"></a>
__Q. How can I jump between the different errors without using the location __Q. How can I jump between the different errors without using the location
list at the bottom of the window?__ list at the bottom of the window?__
@ -200,6 +237,8 @@ If you use these commands a lot then you may want to add shortcut mappings to
your vimrc, or install something like [unimpaired][2], which provides such your vimrc, or install something like [unimpaired][2], which provides such
mappings (among other things). mappings (among other things).
<a name="faqstyle"></a>
__Q. A syntax checker is giving me unwanted/strange style tips?__ __Q. A syntax checker is giving me unwanted/strange style tips?__
A. Some filetypes (e.g. php) have style checkers as well as syntax A. Some filetypes (e.g. php) have style checkers as well as syntax
@ -214,6 +253,8 @@ let g:syntastic_quiet_messages = { "type": "style" }
``` ```
See `:help syntastic_quiet_messages` for details. See `:help syntastic_quiet_messages` for details.
<a name="faqbdelete"></a>
__Q. The error window is closed automatically when I :quit the current buffer __Q. The error window is closed automatically when I :quit the current buffer
but not when I :bdelete it?__ but not when I :bdelete it?__
@ -248,5 +289,5 @@ a look at [jedi-vim][7], [python-mode][8], or [YouCompleteMe][9].
[6]: http://stackoverflow.com/questions/tagged/syntastic [6]: http://stackoverflow.com/questions/tagged/syntastic
[7]: https://github.com/davidhalter/jedi-vim [7]: https://github.com/davidhalter/jedi-vim
[8]: https://github.com/klen/python-mode [8]: https://github.com/klen/python-mode
[9]: https://github.com/Valloric/YouCompleteMe [9]: http://valloric.github.io/YouCompleteMe/
[10]: http://perldoc.perl.org/perlrun.html#*-c* [10]: http://perldoc.perl.org/perlrun.html#*-c*

View file

@ -8,25 +8,6 @@ set cpo&vim
" Public functions {{{1 " Public functions {{{1
function! s:compareErrorItems(a, b) " {{{2
if a:a['bufnr'] != a:b['bufnr']
" group by files
return a:a['bufnr'] - a:b['bufnr']
elseif a:a['lnum'] != a:b['lnum']
return a:a['lnum'] - a:b['lnum']
elseif a:a['type'] !=? a:b['type']
" errors take precedence over warnings
return a:a['type'] ==? 'e' ? -1 : 1
else
return get(a:a, 'col', 0) - get(a:b, 'col', 0)
endif
endfunction " }}}2
" natural sort
function! syntastic#postprocess#sort(errors) " {{{2
return sort(copy(a:errors), 's:compareErrorItems')
endfunction " }}}2
" merge consecutive blanks " merge consecutive blanks
function! syntastic#postprocess#compressWhitespace(errors) " {{{2 function! syntastic#postprocess#compressWhitespace(errors) " {{{2
for e in a:errors for e in a:errors

View file

@ -56,6 +56,45 @@ function! syntastic#preprocess#perl(errors) " {{{2
return syntastic#util#unique(out) return syntastic#util#unique(out)
endfunction " }}}2 endfunction " }}}2
function! syntastic#preprocess#rparse(errors) " {{{2
let errlist = copy(a:errors)
" remove uninteresting lines and handle continuations
let i = 0
while i < len(errlist)
if i > 0 && errlist[i][:1] == ' ' && errlist[i] !~ '\m\s\+\^$'
let errlist[i-1] .= errlist[i][1:]
call remove(errlist, i)
elseif errlist[i] !~ '\m^\(Lint:\|Lint checking:\|Error in\) '
call remove(errlist, i)
else
let i += 1
endif
endwhile
let out = []
let fname = ''
for e in errlist
if match(e, '\m^Lint: ') == 0
let parts = matchlist(e, '\m^Lint: \(.*\): found on lines \([0-9, ]\+\)\(+\(\d\+\) more\)\=')
if len(parts) >= 3
for line in split(parts[2], '\m,\s*')
call add(out, 'E:' . fname . ':' . line . ': ' . parts[1])
endfor
endif
if len(parts) >= 5 && parts[4] != ''
call add(out, 'E:' . fname . ':0: ' . parts[1] . ' - ' . parts[4] . ' messages not shown')
endif
elseif match(e, '\m^Lint checking: ') == 0
let fname = matchstr(e, '\m^Lint checking: \zs.*')
elseif match(e, '\m^Error in ') == 0
call add(out, substitute(e, '\m^Error in .\+ : .\+\ze:\d\+:\d\+: ', 'E:' . fname, ''))
endif
endfor
return out
endfunction " }}}2
function! syntastic#preprocess#validator(errors) " {{{2 function! syntastic#preprocess#validator(errors) " {{{2
let out = [] let out = []
for e in a:errors for e in a:errors

View file

@ -101,7 +101,7 @@ function! syntastic#util#wideMsg(msg) " {{{2
"convert tabs to spaces so that the tabs count towards the window "convert tabs to spaces so that the tabs count towards the window
"width as the proper amount of characters "width as the proper amount of characters
let chunks = split(msg, "\t", 1) let chunks = split(msg, "\t", 1)
let msg = join(map(chunks[:-2], 'v:val . repeat(" ", &ts - s:width(v:val) % &ts)'), '') . chunks[-1] let msg = join(map(chunks[:-2], 'v:val . repeat(" ", &tabstop - s:width(v:val) % &tabstop)'), '') . chunks[-1]
let msg = strpart(msg, 0, &columns - 1) let msg = strpart(msg, 0, &columns - 1)
set noruler noshowcmd set noruler noshowcmd
@ -218,6 +218,13 @@ function! syntastic#util#dictFilter(errors, filter) " {{{2
endtry endtry
endfunction " }}}2 endfunction " }}}2
function! syntastic#util#sortLoclist(errors) " {{{2
for e in a:errors
call s:setScreenColumn(e)
endfor
call sort(a:errors, 's:compareErrorItems')
endfunction " }}}2
" }}}1 " }}}1
" Private functions {{{1 " Private functions {{{1
@ -254,6 +261,49 @@ function! s:translateElement(key, term) " {{{2
return ret return ret
endfunction " }}}2 endfunction " }}}2
function! s:screenWidth(str, tabstop) " {{{2
let chunks = split(a:str, "\t", 1)
let width = s:width(chunks[-1])
for c in chunks[:-2]
let cwidth = s:width(c)
let width += cwidth + a:tabstop - cwidth % a:tabstop
endfor
return width
endfunction " }}}2
function! s:setScreenColumn(item) " {{{2
if !has_key(a:item, 'scol')
let col = get(a:item, 'col', 0)
if col != 0 && a:item['vcol'] == 0
let buf = str2nr(a:item['bufnr'])
try
let line = getbufline(buf, a:item['lnum'])[0]
catch /\m^Vim\%((\a\+)\)\=:E684/
let line = ''
endtry
let a:item['scol'] = s:screenWidth(strpart(line, 0, col), getbufvar(buf, '&tabstop'))
else
let a:item['scol'] = col
endif
endif
endfunction " }}}2
function! s:compareErrorItems(a, b) " {{{2
if a:a['bufnr'] != a:b['bufnr']
" group by file
return a:a['bufnr'] - a:b['bufnr']
elseif a:a['lnum'] != a:b['lnum']
" sort by line
return a:a['lnum'] - a:b['lnum']
elseif a:a['type'] !=? a:b['type']
" errors take precedence over warnings
return a:a['type'] ==? 'E' ? -1 : 1
else
" sort by screen column
return a:a['scol'] - a:b['scol']
endif
endfunction " }}}2
" }}}1 " }}}1
let &cpo = s:save_cpo let &cpo = s:save_cpo

View file

@ -39,6 +39,8 @@ CONTENTS *syntastic-contents*
6.2.Interaction with python-mode...........|syntastic-pymode| 6.2.Interaction with python-mode...........|syntastic-pymode|
6.3.Interaction with the fish shell........|syntastic-fish| 6.3.Interaction with the fish shell........|syntastic-fish|
6.4.Using syntastic with the fizsh shell...|syntastic-fizsh| 6.4.Using syntastic with the fizsh shell...|syntastic-fizsh|
6.5.Interaction with Eclim.................|syntastic-eclim|
6.6.Interaction with vim-virtualenv........|syntastic-vim-virtualenv|
7.About........................................|syntastic-about| 7.About........................................|syntastic-about|
8.License......................................|syntastic-license| 8.License......................................|syntastic-license|
@ -186,7 +188,12 @@ If |'syntastic_aggregate_errors'| is set, syntastic runs all checkers that
apply (still cf. |syntastic-filetype-checkers|), then aggregates errors found apply (still cf. |syntastic-filetype-checkers|), then aggregates errors found
by all checkers in a single list, and notifies you. In this mode each error by all checkers in a single list, and notifies you. In this mode each error
message is labeled with the name of the checker that generated it, but you can message is labeled with the name of the checker that generated it, but you can
disable these labels by unsetting '|syntastic_id_checkers|'. disable generation of these labels by turning off '|syntastic_id_checkers|'.
If |'syntastic_sort_aggregated_errors'| is set (which is the default), messages
in the aggregated list are grouped by file, then sorted by line number, then
type, then column number. Otherwise messages produced by the same checker are
grouped together.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
2.6 Filtering errors *syntastic-filtering-errors* 2.6 Filtering errors *syntastic-filtering-errors*
@ -278,6 +285,14 @@ a file with a composite filetype), it might not be immediately obvious which
checker has produced a given error message. This variable instructs syntastic checker has produced a given error message. This variable instructs syntastic
to label error messages with the names of the checkers that created them. > to label error messages with the names of the checkers that created them. >
let g:syntastic_id_checkers = 0 let g:syntastic_id_checkers = 0
<
*'syntastic_sort_aggregated_errors'*
Default: 1
By default, when |syntastic_aggregate_errors| is enabled, errors are grouped
by file, then sorted by line number, then grouped by type (namely, errors take
precedence over warnings), then they are sorted by column number. If you want
to leave messages grouped by checker output, set this variable to 0. >
let g:syntastic_sort_aggregated_errors = 0
< <
*'syntastic_echo_current_error'* *'syntastic_echo_current_error'*
Default: 1 Default: 1
@ -557,10 +572,10 @@ Use |:SyntasticInfo| to see which checkers are available for a given filetype.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
5.2 Choosing the executable *syntastic-config-exec* 5.2 Choosing the executable *syntastic-config-exec*
*'syntastic_<filetype>_<subchecker>_exec'* *'syntastic_<filetype>_<checker>_exec'*
The executable used by a checker is normally defined automatically, when the The executable used by a checker is normally defined automatically, when the
checkers is registered. You can however override it by setting the variable checkers is registered. You can however override it by setting the variable
'g:syntastic_<filetype>_<subchecker>_exec': > 'g:syntastic_<filetype>_<checker>_exec': >
let g:syntastic_ruby_mri_exec = '~/bin/ruby2' let g:syntastic_ruby_mri_exec = '~/bin/ruby2'
< <
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
@ -569,7 +584,7 @@ checkers is registered. You can however override it by setting the variable
Most checkers use the 'makeprgBuild()' function and provide many options by Most checkers use the 'makeprgBuild()' function and provide many options by
default - in fact you can customise every part of the command that gets called. default - in fact you can customise every part of the command that gets called.
*'syntastic_<filetype>_<subchecker>_<option>'* *'syntastic_<filetype>_<checker>_<option>'*
Checkers that use 'makeprgBuild()' construct a 'makeprg' like this: > Checkers that use 'makeprgBuild()' construct a 'makeprg' like this: >
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'exe': self.getExec(), \ 'exe': self.getExec(),
@ -580,7 +595,7 @@ Checkers that use 'makeprgBuild()' construct a 'makeprg' like this: >
The result is a 'makeprg' of the form: > The result is a 'makeprg' of the form: >
<exe> <args> <filename> <post_args> <tail> <exe> <args> <filename> <post_args> <tail>
< <
*'syntastic_<filetype>_<subchecker>_exe'* *'syntastic_<filetype>_<checker>_exe'*
All arguments above are optional, and can be overridden by setting global All arguments above are optional, and can be overridden by setting global
variables 'g:syntastic_<filetype>_<checker-name>_<option-name>' - even variables 'g:syntastic_<filetype>_<checker-name>_<option-name>' - even
parameters not specified in the call to makeprgBuild(). These variables also parameters not specified in the call to makeprgBuild(). These variables also
@ -598,7 +613,7 @@ To override the args and the tail: >
let g:syntastic_ruby_mri_tail = "> /tmp/my-output-file-biatch" let g:syntastic_ruby_mri_tail = "> /tmp/my-output-file-biatch"
< <
The general form of the override options is: > The general form of the override options is: >
syntastic_<filetype>_<subchecker>_<option-name> syntastic_<filetype>_<checker>_<option-name>
< <
For checkers that do not use the 'makeprgBuild()' function you will have to For checkers that do not use the 'makeprgBuild()' function you will have to
look at the source code of the checker in question. If there are specific look at the source code of the checker in question. If there are specific
@ -663,6 +678,23 @@ interactive features of 'fizsh'. Using a more traditional shell such as 'zsh',
'bash', 'ksh', or the original Bourne 'sh' might be a better choice: > 'bash', 'ksh', or the original Bourne 'sh' might be a better choice: >
set shell=zsh set shell=zsh
< <
------------------------------------------------------------------------------
6.5. Interaction with Eclim *syntastic-eclim*
As far as syntastic is concerned there shouldn't be any compatibility problems
with the 'Eclim' Vim plugin (see http://eclim.org/). However, at the time of
this writing there are several reports that 'Eclim' triggers a bug in Vim that
makes syntastic forget some of its configuration parameters. No solutions or
workarounds are known for now.
------------------------------------------------------------------------------
6.6. Interaction with vim-virtualenv *syntastic-vim-virtualenv*
At the time of this writing, syntastic can't run checkers installed
in Python virtual environments activated by 'vim-virtualenv' (see
https://github.com/jmcantrell/vim-virtualenv). This is a limitation of
'vim-virtualenv'.
============================================================================== ==============================================================================
7. About *syntastic-about* 7. About *syntastic-about*

View file

@ -18,7 +18,7 @@ if has('reltime')
let g:syntastic_start = reltime() let g:syntastic_start = reltime()
endif endif
let g:syntastic_version = '3.4.0' let g:syntastic_version = '3.4.0-34'
" Sanity checks {{{1 " Sanity checks {{{1
@ -64,6 +64,7 @@ let g:syntastic_defaults = {
\ 'loc_list_height': 10, \ 'loc_list_height': 10,
\ 'quiet_messages': {}, \ 'quiet_messages': {},
\ 'reuse_loc_lists': (v:version >= 704), \ 'reuse_loc_lists': (v:version >= 704),
\ 'sort_aggregated_errors': 1,
\ 'stl_format': '[Syntax: line:%F (%t)]', \ 'stl_format': '[Syntax: line:%F (%t)]',
\ 'style_error_symbol': 'S>', \ 'style_error_symbol': 'S>',
\ 'style_warning_symbol': 'S>', \ 'style_warning_symbol': 'S>',
@ -297,6 +298,7 @@ function! s:CacheErrors(checker_names) " {{{2
let filetypes = s:resolveFiletypes() let filetypes = s:resolveFiletypes()
let aggregate_errors = syntastic#util#var('aggregate_errors') let aggregate_errors = syntastic#util#var('aggregate_errors')
let decorate_errors = (aggregate_errors || len(filetypes) > 1) && syntastic#util#var('id_checkers') let decorate_errors = (aggregate_errors || len(filetypes) > 1) && syntastic#util#var('id_checkers')
let sort_aggregated_errors = aggregate_errors && syntastic#util#var('sort_aggregated_errors')
let clist = [] let clist = []
for type in filetypes for type in filetypes
@ -352,6 +354,10 @@ function! s:CacheErrors(checker_names) " {{{2
" }}}3 " }}}3
call syntastic#log#debug(g:SyntasticDebugLoclist, 'aggregated:', newLoclist) call syntastic#log#debug(g:SyntasticDebugLoclist, 'aggregated:', newLoclist)
if sort_aggregated_errors
call newLoclist.sort()
call syntastic#log#debug(g:SyntasticDebugLoclist, 'sorted:', newLoclist)
endif
endif endif
let b:syntastic_loclist = newLoclist let b:syntastic_loclist = newLoclist

View file

@ -13,6 +13,7 @@ function! g:SyntasticChecker.New(args) " {{{2
let newObj._filetype = a:args['filetype'] let newObj._filetype = a:args['filetype']
let newObj._name = a:args['name'] let newObj._name = a:args['name']
let newObj._exec = get(a:args, 'exec', newObj._name) let newObj._exec = get(a:args, 'exec', newObj._name)
let newObj._sort = 0
if has_key(a:args, 'redirect') if has_key(a:args, 'redirect')
let [filetype, name] = split(a:args['redirect'], '/') let [filetype, name] = split(a:args['redirect'], '/')
@ -68,6 +69,7 @@ function! g:SyntasticChecker.getLocListRaw() " {{{2
call self._populateHighlightRegexes(list) call self._populateHighlightRegexes(list)
call syntastic#log#debug(g:SyntasticDebugLoclist, name . ' raw:', list) call syntastic#log#debug(g:SyntasticDebugLoclist, name . ' raw:', list)
call self._quietMessages(list) call self._quietMessages(list)
call self._sortMessages(list)
return list return list
endfunction " }}}2 endfunction " }}}2
@ -75,6 +77,14 @@ function! g:SyntasticChecker.getLocList() " {{{2
return g:SyntasticLoclist.New(self.getLocListRaw()) return g:SyntasticLoclist.New(self.getLocListRaw())
endfunction " }}}2 endfunction " }}}2
function! g:SyntasticChecker.getWantSort() " {{{2
return self._sort
endfunction " }}}2
function! g:SyntasticChecker.setWantSort(val) " {{{2
let self._sort = a:val
endfunction " }}}2
function! g:SyntasticChecker.makeprgBuild(opts) " {{{2 function! g:SyntasticChecker.makeprgBuild(opts) " {{{2
let basename = self._filetype . '_' . self._name . '_' let basename = self._filetype . '_' . self._name . '_'
@ -121,6 +131,14 @@ function! g:SyntasticChecker._quietMessages(errors) " {{{2
endif endif
endfunction " }}}2 endfunction " }}}2
function! g:SyntasticChecker._sortMessages(errors) " {{{2
" don't sort now if we're going to sort the aggregated list later
if self._sort && !(syntastic#util#var('aggregate_errors') && syntastic#util#var('sort_aggregated_errors'))
call syntastic#util#sortLoclist(a:errors)
call syntastic#log#debug(g:SyntasticDebugLoclist, 'sorted:', a:errors)
endif
endfunction " }}}2
function! g:SyntasticChecker._populateHighlightRegexes(errors) " {{{2 function! g:SyntasticChecker._populateHighlightRegexes(errors) " {{{2
if has_key(self, '_highlightRegexFunc') if has_key(self, '_highlightRegexFunc')
for e in a:errors for e in a:errors

View file

@ -37,6 +37,10 @@ function! g:SyntasticLoclist.extend(other) " {{{2
return g:SyntasticLoclist.New(list) return g:SyntasticLoclist.New(list)
endfunction " }}}2 endfunction " }}}2
function! g:SyntasticLoclist.sort() " {{{2
call syntastic#util#sortLoclist(self._rawLoclist)
endfunction " }}}2
function! g:SyntasticLoclist.isEmpty() " {{{2 function! g:SyntasticLoclist.isEmpty() " {{{2
return empty(self._rawLoclist) return empty(self._rawLoclist)
endfunction " }}}2 endfunction " }}}2

View file

@ -60,6 +60,7 @@ let s:defaultCheckers = {
\ 'pod': ['podchecker'], \ 'pod': ['podchecker'],
\ 'puppet': ['puppet', 'puppetlint'], \ 'puppet': ['puppet', 'puppetlint'],
\ 'python': ['python', 'flake8', 'pylint'], \ 'python': ['python', 'flake8', 'pylint'],
\ 'r': [],
\ 'racket': ['racket'], \ 'racket': ['racket'],
\ 'rst': ['rst2pseudoxml'], \ 'rst': ['rst2pseudoxml'],
\ 'ruby': ['mri'], \ 'ruby': ['mri'],

View file

@ -47,7 +47,7 @@ endfunction
function! SyntaxCheckers_actionscript_mxmlc_GetLocList() dict function! SyntaxCheckers_actionscript_mxmlc_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args_before': (g:syntastic_actionscript_mxmlc_conf != '' ? \ 'args_before': (g:syntastic_actionscript_mxmlc_conf != '' ?
\ ' -load-config+=' . g:syntastic_actionscript_mxmlc_conf : ''), \ ' -load-config+=' . syntastic#util#shexpand(g:syntastic_actionscript_mxmlc_conf) : ''),
\ 'args_after': '-output=' . syntastic#util#DevNull() }) \ 'args_after': '-output=' . syntastic#util#DevNull() })
let errorformat = let errorformat =

View file

@ -30,7 +30,6 @@ set cpo&vim
function! SyntaxCheckers_c_oclint_GetLocList() dict function! SyntaxCheckers_c_oclint_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args_after': '-text',
\ 'post_args_before': '-- -c ' . syntastic#c#ReadConfig(g:syntastic_oclint_config_file) }) \ 'post_args_before': '-- -c ' . syntastic#c#ReadConfig(g:syntastic_oclint_config_file) })
let errorformat = let errorformat =
@ -42,12 +41,16 @@ function! SyntaxCheckers_c_oclint_GetLocList() dict
\ '%W%f:%l:%c: warning: %m,' . \ '%W%f:%l:%c: warning: %m,' .
\ '%-G%.%#' \ '%-G%.%#'
return SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'subtype': 'Style', \ 'subtype': 'Style',
\ 'postprocess': ['compressWhitespace', 'sort'], \ 'postprocess': ['compressWhitespace'],
\ 'returns': [0, 3, 5] }) \ 'returns': [0, 3, 5] })
call self.setWantSort(1)
return loclist
endfunction endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -35,8 +35,11 @@ function! SyntaxCheckers_c_splint_GetLocList() dict
let errorformat = let errorformat =
\ '%-G%f:%l:%v: %[%#]%[%#]%[%#] Internal Bug %.%#,' . \ '%-G%f:%l:%v: %[%#]%[%#]%[%#] Internal Bug %.%#,' .
\ '%-G%f(%l\,%v): %[%#]%[%#]%[%#] Internal Bug %.%#,' .
\ '%W%f:%l:%v: %m,' . \ '%W%f:%l:%v: %m,' .
\ '%W%f(%l\,%v): %m,' .
\ '%W%f:%l: %m,' . \ '%W%f:%l: %m,' .
\ '%W%f(%l): %m,' .
\ '%-C %\+In file included from %.%#,' . \ '%-C %\+In file included from %.%#,' .
\ '%-C %\+from %.%#,' . \ '%-C %\+from %.%#,' .
\ '%+C %.%#' \ '%+C %.%#'

View file

@ -43,13 +43,14 @@ function! SyntaxCheckers_css_prettycss_GetLocList() dict
let loclist = SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr("")}, \ 'defaults': {'bufnr': bufnr("")} })
\ 'postprocess': ['sort'] })
for e in loclist for e in loclist
let e["text"] .= ')' let e["text"] .= ')'
endfor endfor
call self.setWantSort(1)
return loclist return loclist
endfunction endfunction

View file

@ -19,22 +19,28 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_haskell_hdevtools_GetLocList() dict function! SyntaxCheckers_haskell_hdevtools_GetLocList() dict
let makeprg = self.makeprgBuild({ if exists('g:hdevtools_options')
\ 'exe': self.getExecEscaped() . ' check', let g:syntastic_haskell_hdevtools_args = g:hdevtools_options
\ 'args': get(g:, 'hdevtools_options', '') }) endif
let errorformat= '\%-Z\ %#,'. let makeprg = self.makeprgBuild({
\ '%W%f:%l:%c:\ Warning:\ %m,'. \ 'exe_after': 'check',
\ '%W%f:%l:%c:\ Warning:,'. \ 'fname': syntastic#util#shexpand('%:p') })
\ '%E%f:%l:%c:\ %m,'.
\ '%E%>%f:%l:%c:,'. let errorformat =
\ '%+C\ \ %#%m,'. \ '%-Z %#,'.
\ '%W%>%f:%l:%c:,'. \ '%W%f:%l:%v: Warning: %m,'.
\ '%+C\ \ %#%tarning:\ %m,' \ '%W%f:%l:%v: Warning:,'.
\ '%E%f:%l:%v: %m,'.
\ '%E%>%f:%l:%v:,'.
\ '%+C %#%m,'.
\ '%W%>%f:%l:%v:,'.
\ '%+C %#%tarning: %m,'
return SyntasticMake({ return SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'defaults': {'vcol': 1},
\ 'postprocess': ['compressWhitespace'] }) \ 'postprocess': ['compressWhitespace'] })
endfunction endfunction

View file

@ -14,16 +14,18 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_haskell_hlint_GetLocList() dict function! SyntaxCheckers_haskell_hlint_GetLocList() dict
let makeprg = self.makeprgBuild({}) let makeprg = self.makeprgBuild({
\ 'fname': syntastic#util#shexpand('%:p')})
let errorformat = let errorformat =
\ '%E%f:%l:%c: Error: %m,' . \ '%E%f:%l:%v: Error: %m,' .
\ '%W%f:%l:%c: Warning: %m,' . \ '%W%f:%l:%v: Warning: %m,' .
\ '%C%m' \ '%C%m'
return SyntasticMake({ return SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'defaults': {'vcol': 1},
\ 'postprocess': ['compressWhitespace'] }) \ 'postprocess': ['compressWhitespace'] })
endfunction endfunction

View file

@ -0,0 +1,43 @@
"============================================================================
"File: scan.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer: LCD 47 <lcd047 at gmail dot com>
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists('g:loaded_syntastic_haskell_scan_checker')
finish
endif
let g:loaded_syntastic_haskell_scan_checker = 1
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_haskell_scan_GetLocList() dict
let makeprg = self.makeprgBuild({})
let errorformat = '%f:%l:%v: %m'
let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style' })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'haskell',
\ 'name': 'scan'})
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -34,7 +34,8 @@ endfunction
function! SyntaxCheckers_html_jshint_GetLocList() dict function! SyntaxCheckers_html_jshint_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'exe': expand(g:syntastic_jshint_exec), \ 'exe': expand(g:syntastic_jshint_exec),
\ 'args': (g:syntastic_html_jshint_conf != '' ? '--config ' . g:syntastic_html_jshint_conf : ''), \ 'args': (g:syntastic_html_jshint_conf != '' ?
\ '--config ' . syntastic#util#shexpand(g:syntastic_html_jshint_conf) : ''),
\ 'args_after': '--verbose --extract always' }) \ 'args_after': '--verbose --extract always' })
let errorformat = '%A%f: line %l\, col %v\, %m \(%t%*\d\)' let errorformat = '%A%f: line %l\, col %v\, %m \(%t%*\d\)'

View file

@ -10,7 +10,15 @@
" "
"============================================================================ "============================================================================
" "
" Checker option: " Note: if you need to check HTML5 sources, you might consider installing a
" fork of HTML Tidy, named "HTML Tidy for HTML5":
"
" http://w3c.github.io/tidy-html5/
"
" HTML Tidy for HTML5 can be used without changes by this checker, just install
" it and point g:syntastic_html_tidy_exec to the executable.
"
" Checker options:
" "
" - g:syntastic_html_tidy_ignore_errors (list; default: []) " - g:syntastic_html_tidy_ignore_errors (list; default: [])
" list of errors to ignore " list of errors to ignore
@ -48,19 +56,19 @@ set cpo&vim
" TODO: join this with xhtml.vim for DRY's sake? " TODO: join this with xhtml.vim for DRY's sake?
function! s:TidyEncOptByFenc() function! s:TidyEncOptByFenc()
let tidy_opts = { let tidy_opts = {
\'utf-8': '-utf8', \ 'utf-8': '-utf8',
\'ascii': '-ascii', \ 'ascii': '-ascii',
\'latin1': '-latin1', \ 'latin1': '-latin1',
\'iso-2022-jp': '-iso-2022', \ 'iso-2022-jp': '-iso-2022',
\'cp1252': '-win1252', \ 'cp1252': '-win1252',
\'macroman': '-mac', \ 'macroman': '-mac',
\'utf-16le': '-utf16le', \ 'utf-16le': '-utf16le',
\'utf-16': '-utf16', \ 'utf-16': '-utf16',
\'big5': '-big5', \ 'big5': '-big5',
\'cp932': '-shiftjis', \ 'cp932': '-shiftjis',
\'sjis': '-shiftjis', \ 'sjis': '-shiftjis',
\'cp850': '-ibm858', \ 'cp850': '-ibm858',
\} \ }
return get(tidy_opts, &fileencoding, '-utf8') return get(tidy_opts, &fileencoding, '-utf8')
endfunction endfunction

View file

@ -37,7 +37,8 @@ function! SyntaxCheckers_java_checkstyle_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args_after': '-cp ' . g:syntastic_java_checkstyle_classpath . \ 'args_after': '-cp ' . g:syntastic_java_checkstyle_classpath .
\ ' com.puppycrawl.tools.checkstyle.Main -c ' . g:syntastic_java_checkstyle_conf_file . \ ' com.puppycrawl.tools.checkstyle.Main -c ' .
\ syntastic#util#shexpand(g:syntastic_java_checkstyle_conf_file) .
\ ' -f xml', \ ' -f xml',
\ 'fname': fname }) \ 'fname': fname })

View file

@ -43,7 +43,7 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! s:CygwinPath(path) function! s:CygwinPath(path)
return substitute(system("cygpath -m " . a:path), '\n', '', 'g') return substitute(system("cygpath -m " . syntastic#util#shescape(a:path)), '\n', '', 'g')
endfunction endfunction
if !exists("g:syntastic_java_javac_temp_dir") if !exists("g:syntastic_java_javac_temp_dir")
@ -123,8 +123,8 @@ function! s:SplitClasspath(classpath)
endfunction endfunction
function! s:LoadConfigFile() function! s:LoadConfigFile()
if filereadable(g:syntastic_java_javac_config_file) if filereadable(expand(g:syntastic_java_javac_config_file))
exe 'source '.g:syntastic_java_javac_config_file exe 'source ' . fnameescape(expand(g:syntastic_java_javac_config_file))
endif endif
endfunction endfunction
@ -137,9 +137,9 @@ function! s:SaveClasspath()
endfor endfor
" save classpath to config file " save classpath to config file
if g:syntastic_java_javac_config_file_enabled if g:syntastic_java_javac_config_file_enabled
if filereadable(g:syntastic_java_javac_config_file) if filereadable(expand(g:syntastic_java_javac_config_file))
" load lines from config file " load lines from config file
let lines = readfile(g:syntastic_java_javac_config_file) let lines = readfile(expand(g:syntastic_java_javac_config_file))
" strip g:syntastic_java_javac_classpath options from config file lines " strip g:syntastic_java_javac_classpath options from config file lines
let i = 0 let i = 0
while i < len(lines) while i < len(lines)
@ -155,7 +155,7 @@ function! s:SaveClasspath()
" add new g:syntastic_java_javac_classpath option to config " add new g:syntastic_java_javac_classpath option to config
call add(lines, 'let g:syntastic_java_javac_classpath = "'.path.'"') call add(lines, 'let g:syntastic_java_javac_classpath = "'.path.'"')
" save config file lines " save config file lines
call writefile(lines, g:syntastic_java_javac_config_file) call writefile(lines, expand(g:syntastic_java_javac_config_file))
endif endif
" set new classpath " set new classpath
let g:syntastic_java_javac_classpath = path let g:syntastic_java_javac_classpath = path
@ -192,7 +192,7 @@ function! s:SaveConfig()
let lines = getline(1, line('$')) let lines = getline(1, line('$'))
if g:syntastic_java_javac_config_file_enabled if g:syntastic_java_javac_config_file_enabled
" save config file lines " save config file lines
call writefile(lines, g:syntastic_java_javac_config_file) call writefile(lines, expand(g:syntastic_java_javac_config_file))
endif endif
let &modified = 0 let &modified = 0
endfunction endfunction
@ -202,8 +202,8 @@ function! s:EditConfig()
let winnr = bufwinnr('^' . command . '$') let winnr = bufwinnr('^' . command . '$')
if winnr < 0 if winnr < 0
let lines = [] let lines = []
if filereadable(g:syntastic_java_javac_config_file) if filereadable(expand(g:syntastic_java_javac_config_file))
let lines = readfile(g:syntastic_java_javac_config_file) let lines = readfile(expand(g:syntastic_java_javac_config_file))
endif endif
execute (len(lines) + 5) . 'sp ' . fnameescape(command) execute (len(lines) + 5) . 'sp ' . fnameescape(command)
@ -329,7 +329,7 @@ function! s:MavenOutputDirectory()
endif endif
if has('win32unix') if has('win32unix')
let output_dir=s:CygwinPath(output_dir) let output_dir = s:CygwinPath(output_dir)
endif endif
return output_dir return output_dir
endif endif

View file

@ -21,22 +21,31 @@ endif
let s:save_cpo = &cpo let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_javascript_eslint_IsAvailable() dict
return
\ executable('eslint') &&
\ syntastic#util#versionIsAtLeast(syntastic#util#getVersion('eslint --version'), [0, 1])
endfunction
function! SyntaxCheckers_javascript_eslint_GetLocList() dict function! SyntaxCheckers_javascript_eslint_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args': (g:syntastic_javascript_eslint_conf != '' ? '--config ' . g:syntastic_javascript_eslint_conf : '') }) \ 'args_before': '-f compact',
\ 'args': (g:syntastic_javascript_eslint_conf != '' ?
\ '--config ' . syntastic#util#shexpand(g:syntastic_javascript_eslint_conf) : '') })
let errorformat = let errorformat =
\ '%E%f: line %l\, col %c\, Error - %m' \ '%E%f: line %l\, col %c\, Error - %m'
let loclist = SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat })
\ 'postprocess': ['sort'] })
for e in loclist for e in loclist
let e['col'] += 1 let e['col'] += 1
endfor endfor
call self.setWantSort(1)
return loclist return loclist
endfunction endfunction

View file

@ -19,14 +19,19 @@ set cpo&vim
function! SyntaxCheckers_javascript_jscs_GetLocList() dict function! SyntaxCheckers_javascript_jscs_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args_after': '--no-colors --reporter checkstyle' }) let makeprg = self.makeprgBuild({ 'args_after': '--no-colors --reporter checkstyle' })
let errorformat = '%f:%t:%l:%c:%m' let errorformat = '%f:%t:%l:%c:%m'
return SyntasticMake({
let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'subtype': 'Style', \ 'subtype': 'Style',
\ 'preprocess': 'checkstyle', \ 'preprocess': 'checkstyle',
\ 'postprocess': ['sort'],
\ 'returns': [0, 2] }) \ 'returns': [0, 2] })
call self.setWantSort(1)
return loclist
endfunction endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -25,19 +25,22 @@ function! SyntaxCheckers_javascript_jshint_IsAvailable() dict
if !exists('g:syntastic_jshint_exec') if !exists('g:syntastic_jshint_exec')
let g:syntastic_jshint_exec = self.getExec() let g:syntastic_jshint_exec = self.getExec()
endif endif
return executable(expand(g:syntastic_jshint_exec)) if !executable(expand(g:syntastic_jshint_exec))
return 0
endif
let s:jshint_version = syntastic#util#getVersion(syntastic#util#shexpand(g:syntastic_jshint_exec) . ' --version')
return syntastic#util#versionIsAtLeast(s:jshint_version, [1])
endfunction endfunction
function! SyntaxCheckers_javascript_jshint_GetLocList() dict function! SyntaxCheckers_javascript_jshint_GetLocList() dict
let exe = syntastic#util#shexpand(g:syntastic_jshint_exec)
if !exists('s:jshint_new') if !exists('s:jshint_new')
let s:jshint_new = let s:jshint_new = syntastic#util#versionIsAtLeast(s:jshint_version, [1, 1])
\ syntastic#util#versionIsAtLeast(syntastic#util#getVersion(exe . ' --version'), [1, 1])
endif endif
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'exe': exe, \ 'exe': syntastic#util#shexpand(g:syntastic_jshint_exec),
\ 'args': (g:syntastic_javascript_jshint_conf != '' ? '--config ' . g:syntastic_javascript_jshint_conf : ''), \ 'args': (g:syntastic_javascript_jshint_conf != '' ?
\ '--config ' . syntastic#util#shexpand(g:syntastic_javascript_jshint_conf) : ''),
\ 'args_after': (s:jshint_new ? '--verbose ' : '') }) \ 'args_after': (s:jshint_new ? '--verbose ' : '') })
let errorformat = s:jshint_new ? let errorformat = s:jshint_new ?

View file

@ -23,7 +23,8 @@ set cpo&vim
function! SyntaxCheckers_javascript_jsl_GetLocList() dict function! SyntaxCheckers_javascript_jsl_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args': (g:syntastic_javascript_jsl_conf != '' ? '-conf ' . g:syntastic_javascript_jsl_conf : ''), \ 'args': (g:syntastic_javascript_jsl_conf != '' ?
\ '-conf ' . syntastic#util#shexpand(g:syntastic_javascript_jsl_conf) : ''),
\ 'args_after': '-nologo -nofilelisting -nosummary -nocontext -process' }) \ 'args_after': '-nologo -nofilelisting -nosummary -nocontext -process' })
let errorformat = let errorformat =

View file

@ -18,10 +18,6 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_javascript_jsxhint_IsAvailable() dict function! SyntaxCheckers_javascript_jsxhint_IsAvailable() dict
if !executable('jshint') || !syntastic#util#versionIsAtLeast(syntastic#util#getVersion('jshint --version'), [1, 1])
return 0
endif
let jsxhint_version = system(self.getExecEscaped() . ' --version') let jsxhint_version = system(self.getExecEscaped() . ' --version')
return return
\ v:shell_error == 0 && \ v:shell_error == 0 &&

View file

@ -32,8 +32,7 @@ function! SyntaxCheckers_python_pylama_GetLocList() dict
let loclist = SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat })
\ 'postprocess': ['sort'] })
" adjust for weirdness in each checker " adjust for weirdness in each checker
for e in loclist for e in loclist
@ -53,6 +52,8 @@ function! SyntaxCheckers_python_pylama_GetLocList() dict
endif endif
endfor endfor
call self.setWantSort(1)
return loclist return loclist
endfunction endfunction

View file

@ -32,10 +32,9 @@ function! SyntaxCheckers_python_pylint_GetLocList() dict
\ '%-Z%p^%.%#,' . \ '%-Z%p^%.%#,' .
\ '%-G%.%#' \ '%-G%.%#'
let loclist=SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'postprocess': ['sort'],
\ 'returns': range(32) }) \ 'returns': range(32) })
for e in loclist for e in loclist
@ -55,6 +54,8 @@ function! SyntaxCheckers_python_pylint_GetLocList() dict
let e['vcol'] = 0 let e['vcol'] = 0
endfor endfor
call self.setWantSort(1)
return loclist return loclist
endfunction endfunction
@ -63,9 +64,10 @@ function! s:PylintNew(exe)
try try
" On Windows the version is shown as "pylint-script.py 1.0.0". " On Windows the version is shown as "pylint-script.py 1.0.0".
" On Gentoo Linux it's "pylint-python2.7 0.28.0". " On Gentoo Linux it's "pylint-python2.7 0.28.0".
" On NixOS, that would be ".pylint-wrapped 0.26.0", that would be. " On NixOS, that would be ".pylint-wrapped 0.26.0".
" On Arch Linux it's "pylint2 1.1.0".
" Have you guys considered switching to creative writing yet? ;) " Have you guys considered switching to creative writing yet? ;)
let pylint_version = filter(split(system(exe . ' --version'), '\m, \=\|\n'), 'v:val =~# ''\m^\.\=pylint\>''')[0] let pylint_version = filter(split(system(exe . ' --version'), '\m, \=\|\n'), 'v:val =~# ''\m^\.\=pylint[-0-9]*\>''')[0]
let pylint_version = substitute(pylint_version, '\v^\S+\s+', '', '') let pylint_version = substitute(pylint_version, '\v^\S+\s+', '', '')
let ret = syntastic#util#versionIsAtLeast(syntastic#util#parseVersion(pylint_version), [1]) let ret = syntastic#util#versionIsAtLeast(syntastic#util#parseVersion(pylint_version), [1])
catch /\m^Vim\%((\a\+)\)\=:E684/ catch /\m^Vim\%((\a\+)\)\=:E684/

View file

@ -0,0 +1,78 @@
"============================================================================
"File: lint.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer: LCD 47 <lcd047 at gmail dot com>
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists("g:loaded_syntastic_r_lint_checker")
finish
endif
let g:loaded_syntastic_r_lint_checker = 1
if !exists('g:syntastic_r_lint_styles')
let g:syntastic_r_lint_styles = 'lint.style'
endif
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_r_lint_GetHighlightRegex(item)
let term = matchstr(a:item['text'], '\m`\zs[^`]\+\ze`')
if term == ''
let term = matchstr(a:item['text'], "\\m'\\zs[^']\\+\\ze'")
endif
return term != '' ? '\V' . escape(term, '\') : ''
endfunction
function! SyntaxCheckers_r_lint_IsAvailable() dict
if !executable(self.getExec())
return 0
endif
call system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(lint)'))
return v:shell_error == 0
endfunction
function! SyntaxCheckers_r_lint_GetLocList() dict
let makeprg = self.getExecEscaped() . ' --slave --restore --no-save' .
\ ' -e ' . syntastic#util#shescape('library(lint); try(lint(commandArgs(TRUE), ' . g:syntastic_r_lint_styles . '))') .
\ ' --args ' . syntastic#util#shexpand('%')
let errorformat =
\ '%t:%f:%l:%v: %m,' .
\ '%t:%f:%l: %m'
let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style',
\ 'preprocess': 'rparse',
\ 'returns': [0] })
for e in loclist
if e['type'] == 'F'
" parse error
let e['type'] = 'E'
call remove(e, 'subtype')
endif
endfor
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'r',
\ 'name': 'lint',
\ 'exec': 'R' })
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -0,0 +1,77 @@
"============================================================================
"File: svtools.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer: LCD 47 <lcd047 at gmail dot com>
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
"
" Security:
"
" This checker runs the code in your file. This is probably fine if you
" wrote the file yourself, but it can be a problem if you're trying to
" check third party files. If you are 100% willing to let Vim run the
" code in your file, set g:syntastic_enable_r_svtools_checker to 1 in
" your vimrc to enable this checker:
"
" let g:syntastic_enable_r_svtools_checker = 1
if exists("g:loaded_syntastic_r_svtools_checker")
finish
endif
let g:loaded_syntastic_r_svtools_checker = 1
if !exists('g:syntastic_r_svtools_styles')
let g:syntastic_r_svtools_styles = 'lint.style'
endif
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_r_svtools_GetHighlightRegex(item)
let term = matchstr(a:item['text'], "\\m'\\zs[^']\\+\\ze'")
return term != '' ? '\V' . escape(term, '\') : ''
endfunction
function! SyntaxCheckers_r_svtools_IsAvailable() dict
if !executable(self.getExec())
return 0
endif
call system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(svTools)'))
return v:shell_error == 0
endfunction
function! SyntaxCheckers_r_svtools_GetLocList() dict
if !exists('g:syntastic_enable_r_svtools_checker') || !g:syntastic_enable_r_svtools_checker
call syntastic#log#error('checker r/svtools: checks disabled for security reasons; set g:syntastic_enable_r_svtools_checker to 1 to override')
return []
endif
let makeprg = self.getExecEscaped() . ' --slave --restore --no-save' .
\ ' -e ' . syntastic#util#shescape('library(svTools); ' .
\ 'try(lint(commandArgs(TRUE), filename = commandArgs(TRUE), type = "flat", sep = ":"))') .
\ ' --args ' . syntastic#util#shexpand('%')
let errorformat =
\ '%trror:%f:%\s%#%l:%\s%#%v:%m,' .
\ '%tarning:%f:%\s%#%l:%\s%#%v:%m'
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'returns': [0] })
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'r',
\ 'name': 'svtools',
\ 'exec': 'R' })
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -38,13 +38,14 @@ function! SyntaxCheckers_racket_code_ayatollah_GetLocList() dict
let loclist = SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'subtype': 'Style', \ 'subtype': 'Style' })
\ 'postprocess': ['sort'] })
for e in loclist for e in loclist
let e['col'] += 1 let e['col'] += 1
endfor endfor
call self.setWantSort(1)
return loclist return loclist
endfunction endfunction

View file

@ -45,11 +45,14 @@ function! SyntaxCheckers_tex_chktex_GetLocList() dict
\ '%Z%p^,' . \ '%Z%p^,' .
\ '%-G%.%#' \ '%-G%.%#'
return SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'subtype': 'Style', \ 'subtype': 'Style' })
\ 'postprocess': ['sort'] })
call self.setWantSort(1)
return loclist
endfunction endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -23,11 +23,14 @@ function! SyntaxCheckers_typescript_tsc_GetLocList() dict
\ '%Eerror %m,' . \ '%Eerror %m,' .
\ '%C%\s%\+%m' \ '%C%\s%\+%m'
return SyntasticMake({ let loclist = SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,
\ 'errorformat': errorformat, \ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr("")}, \ 'defaults': {'bufnr': bufnr("")} })
\ 'postprocess': ['sort'] })
call self.setWantSort(1)
return loclist
endfunction endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -36,14 +36,9 @@ function! SyntaxCheckers_vim_vimlint_GetHighlightRegex(item)
endfunction endfunction
function! SyntaxCheckers_vim_vimlint_IsAvailable() dict function! SyntaxCheckers_vim_vimlint_IsAvailable() dict
let ret = 0 return
try \ globpath(&runtimepath, 'autoload/vimlparser.vim') != '' &&
call vimlint#vimlint(syntastic#util#DevNull(), { 'output': [], 'quiet': 1 }) \ globpath(&runtimepath, 'autoload/vimlint.vim') != ''
let ret = 1
catch /\m^Vim\%((\a\+)\)\=:E117/
" do nothing
endtry
return ret
endfunction endfunction
function! SyntaxCheckers_vim_vimlint_GetLocList() dict function! SyntaxCheckers_vim_vimlint_GetLocList() dict

View file

@ -30,19 +30,19 @@ set cpo&vim
" TODO: join this with html.vim DRY's sake? " TODO: join this with html.vim DRY's sake?
function! s:TidyEncOptByFenc() function! s:TidyEncOptByFenc()
let tidy_opts = { let tidy_opts = {
\'utf-8': '-utf8', \ 'utf-8': '-utf8',
\'ascii': '-ascii', \ 'ascii': '-ascii',
\'latin1': '-latin1', \ 'latin1': '-latin1',
\'iso-2022-jp': '-iso-2022', \ 'iso-2022-jp': '-iso-2022',
\'cp1252': '-win1252', \ 'cp1252': '-win1252',
\'macroman': '-mac', \ 'macroman': '-mac',
\'utf-16le': '-utf16le', \ 'utf-16le': '-utf16le',
\'utf-16': '-utf16', \ 'utf-16': '-utf16',
\'big5': '-big5', \ 'big5': '-big5',
\'cp932': '-shiftjis', \ 'cp932': '-shiftjis',
\'sjis': '-shiftjis', \ 'sjis': '-shiftjis',
\'cp850': '-ibm858', \ 'cp850': '-ibm858',
\} \ }
return get(tidy_opts, &fileencoding, '-utf8') return get(tidy_opts, &fileencoding, '-utf8')
endfunction endfunction

View file

@ -0,0 +1,42 @@
"============================================================================
"File: plutil.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer: LCD 47 <lcd047 at gmail dot com>
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists("g:loaded_syntastic_xml_plutil_checker")
finish
endif
let g:loaded_syntastic_xml_plutil_checker = 1
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_xml_plutil_GetLocList() dict
let makeprg = self.makeprgBuild({
\ 'args_before': '-lint -s',
\ 'fname_before': '--' })
let errorformat =
\ '%E%f: %m at line %l'
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'returns': [0, 1] })
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'xml',
\ 'name': 'plutil'})
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -1,7 +1,7 @@
" @Author: Tom Link (micathom AT gmail com?subject=[vim]) " @Author: Tom Link (micathom AT gmail com?subject=[vim])
" @Website: http://www.vim.org/account/profile.php?user_id=4037 " @Website: http://www.vim.org/account/profile.php?user_id=4037
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Revision: 1389 " @Revision: 1391
" :filedoc: " :filedoc:
" A prototype used by |tlib#input#List|. " A prototype used by |tlib#input#List|.
@ -985,7 +985,7 @@ function! s:prototype.DisplayHelp() dict "{{{3
endif endif
if stridx(self.type, 'm') != -1 if stridx(self.type, 'm') != -1
call self.PushHelp('<S-Up/Down>', '(Un)Select items') call self.PushHelp('<S-Up/Down>', '(Un)Select items')
call self.PushHelp('#, <C-Space>', '(Un)Select the current item') call self.PushHelp('#', '(Un)Select the current item')
call self.PushHelp('<C|M-a>', '(Un)Select all items') call self.PushHelp('<C|M-a>', '(Un)Select all items')
call self.PushHelp('<F9>', '(Un)Restrict view to selection') call self.PushHelp('<F9>', '(Un)Restrict view to selection')
" \ '<c-\> ... Show only selected', " \ '<c-\> ... Show only selected',

View file

@ -4,7 +4,7 @@
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Created: 2007-06-30. " @Created: 2007-06-30.
" @Last Change: 2013-09-25. " @Last Change: 2013-09-25.
" @Revision: 0.1.230 " @Revision: 0.1.243
" The cache directory. If empty, use |tlib#dir#MyRuntime|.'/cache'. " The cache directory. If empty, use |tlib#dir#MyRuntime|.'/cache'.
@ -88,7 +88,11 @@ function! tlib#cache#Filename(type, ...) "{{{3
" TLogVAR file, dir, mkdir " TLogVAR file, dir, mkdir
let cache_file = tlib#file#Join([dir, file]) let cache_file = tlib#file#Join([dir, file])
if len(cache_file) > g:tlib#cache#max_filename if len(cache_file) > g:tlib#cache#max_filename
if v:version >= 704
let shortfilename = pathshorten(file) .'_'. sha256(file)
else
let shortfilename = pathshorten(file) .'_'. tlib#hash#Adler32(file) let shortfilename = pathshorten(file) .'_'. tlib#hash#Adler32(file)
endif
let cache_file = tlib#cache#Filename(a:type, shortfilename, mkdir, dir0) let cache_file = tlib#cache#Filename(a:type, shortfilename, mkdir, dir0)
else else
if mkdir && !isdirectory(dir) if mkdir && !isdirectory(dir)
@ -108,9 +112,32 @@ function! tlib#cache#Filename(type, ...) "{{{3
endf endf
let s:timestamps = {}
function! s:SetTimestamp(cfile, type) "{{{3
if !has_key(s:timestamps, a:cfile)
let s:timestamps[a:cfile] = {}
endif
let s:timestamps[a:cfile].atime = getftime(a:cfile)
let s:timestamps[a:cfile][a:type] = s:timestamps[a:cfile].atime
endf
function! tlib#cache#Save(cfile, dictionary) "{{{3 function! tlib#cache#Save(cfile, dictionary) "{{{3
" TLogVAR a:cfile, a:dictionary " TLogVAR a:cfile, a:dictionary
call tlib#persistent#Save(a:cfile, a:dictionary) if !empty(a:cfile)
" TLogVAR a:dictionary
call writefile([string(a:dictionary)], a:cfile, 'b')
call s:SetTimestamp(a:cfile, 'write')
endif
endf
function! tlib#cache#MTime(cfile) "{{{3
let mtime = {'mtime': getftime(a:cfile)}
let mtime = extend(mtime, get(s:timestamps, a:cfile, {}))
return mtime
endf endf
@ -118,6 +145,7 @@ function! tlib#cache#Get(cfile, ...) "{{{3
call tlib#cache#MaybePurge() call tlib#cache#MaybePurge()
if !empty(a:cfile) && filereadable(a:cfile) if !empty(a:cfile) && filereadable(a:cfile)
let val = readfile(a:cfile, 'b') let val = readfile(a:cfile, 'b')
call s:SetTimestamp(a:cfile, 'read')
return eval(join(val, "\n")) return eval(join(val, "\n"))
else else
let default = a:0 >= 1 ? a:1 : {} let default = a:0 >= 1 ? a:1 : {}
@ -130,14 +158,9 @@ endf
" or does not exist, create it calling a generator function. " or does not exist, create it calling a generator function.
function! tlib#cache#Value(cfile, generator, ftime, ...) "{{{3 function! tlib#cache#Value(cfile, generator, ftime, ...) "{{{3
if !filereadable(a:cfile) || (a:ftime != 0 && getftime(a:cfile) < a:ftime) if !filereadable(a:cfile) || (a:ftime != 0 && getftime(a:cfile) < a:ftime)
if empty(a:generator) && a:0 >= 1
" TLogVAR a:1
let val = a:1
else
let args = a:0 >= 1 ? a:1 : [] let args = a:0 >= 1 ? a:1 : []
" TLogVAR a:generator, args " TLogVAR a:generator, args
let val = call(a:generator, args) let val = call(a:generator, args)
endif
" TLogVAR val " TLogVAR val
let cval = {'val': val} let cval = {'val': val}
" TLogVAR cval " TLogVAR cval

View file

@ -1,7 +1,7 @@
" @Author: Tom Link (micathom AT gmail com?subject=[vim]) " @Author: Tom Link (micathom AT gmail com?subject=[vim])
" @Website: http://www.vim.org/account/profile.php?user_id=4037 " @Website: http://www.vim.org/account/profile.php?user_id=4037
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Revision: 1315 " @Revision: 1317
" :filedoc: " :filedoc:
@ -325,6 +325,8 @@ function! tlib#input#ListW(world, ...) "{{{3
" TLogVAR world.state, world.sticky, world.initial_index " TLogVAR world.state, world.sticky, world.initial_index
" let statusline = &l:statusline " let statusline = &l:statusline
" let laststatus = &laststatus " let laststatus = &laststatus
let showmode = &showmode
set noshowmode
let lastsearch = @/ let lastsearch = @/
let scrolloff = &l:scrolloff let scrolloff = &l:scrolloff
let &l:scrolloff = 0 let &l:scrolloff = 0
@ -779,6 +781,9 @@ function! tlib#input#ListW(world, ...) "{{{3
" TLogVAR statusline " TLogVAR statusline
" let &l:statusline = statusline " let &l:statusline = statusline
" let &laststatus = laststatus " let &laststatus = laststatus
if &showmode != showmode
let &showmode = showmode
endif
silent! let @/ = lastsearch silent! let @/ = lastsearch
let &l:scrolloff = scrolloff let &l:scrolloff = scrolloff
if s:PopupmenuExists() == 1 if s:PopupmenuExists() == 1

View file

@ -4,7 +4,7 @@
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Created: 2007-06-30. " @Created: 2007-06-30.
" @Last Change: 2011-03-18. " @Last Change: 2011-03-18.
" @Revision: 36 " @Revision: 53
""" List related functions {{{1 """ List related functions {{{1
@ -140,25 +140,29 @@ endf
function! tlib#list#Uniq(list, ...) "{{{3 function! tlib#list#Uniq(list, ...) "{{{3
TVarArg ['get_value', ''] TVarArg ['get_value', ''], ['remove_empty', 0]
let s:uniq_values = {} if remove_empty
call filter(a:list, 'type(v:val) == 0 || !empty(v:val)')
endif
" CREDITS: Based on syntastic#util#unique(list) by scrooloose
let seen = {}
let uniques = []
if empty(get_value) if empty(get_value)
call filter(a:list, 's:UniqValue(v:val)') for e in a:list
else if !has_key(seen, e)
call filter(a:list, 's:UniqValue(eval(printf(get_value, string(v:val))))') let seen[e] = 1
call add(uniques, e)
endif endif
unlet s:uniq_values endfor
return a:list else
for e in a:list
let v = eval(printf(get_value, string(e)))
if !has_key(seen, v)
let seen[v] = 1
call add(uniques, e)
endif
endfor
endif
return uniques
endf endf
function! s:UniqValue(value) "{{{3
if get(s:uniq_values, a:value, 0)
return 0
else
let s:uniq_values[a:value] = 1
return 1
endif
endf

View file

@ -3,7 +3,7 @@
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Created: 2012-05-11. " @Created: 2012-05-11.
" @Last Change: 2012-05-11. " @Last Change: 2012-05-11.
" @Revision: 9 " @Revision: 12
" The directory for persistent data files. If empty, use " The directory for persistent data files. If empty, use
" |tlib#dir#MyRuntime|.'/share'. " |tlib#dir#MyRuntime|.'/share'.
@ -33,14 +33,15 @@ function! tlib#persistent#Get(...) "{{{3
return call('tlib#cache#Get', a:000) return call('tlib#cache#Get', a:000)
endf endf
function! tlib#persistent#MTime(cfile) "{{{3
return tlib#cache#MTime(a:cfile)
endf
function! tlib#persistent#Value(...) "{{{3 function! tlib#persistent#Value(...) "{{{3
return call('tlib#cache#Value', a:000) return call('tlib#cache#Value', a:000)
endf endf
function! tlib#persistent#Save(cfile, dictionary) "{{{3 function! tlib#persistent#Save(cfile, dictionary) "{{{3
if !empty(a:cfile) call tlib#cache#Save(a:cfile, a:dictionary)
" TLogVAR a:dictionary
call writefile([string(a:dictionary)], a:cfile, 'b')
endif
endf endf

View file

@ -52,6 +52,7 @@ Contents~
tlib#persistent#Dir .................... |tlib#persistent#Dir()| tlib#persistent#Dir .................... |tlib#persistent#Dir()|
tlib#persistent#Filename ............... |tlib#persistent#Filename()| tlib#persistent#Filename ............... |tlib#persistent#Filename()|
tlib#persistent#Get .................... |tlib#persistent#Get()| tlib#persistent#Get .................... |tlib#persistent#Get()|
tlib#persistent#MTime .................. |tlib#persistent#MTime()|
tlib#persistent#Value .................. |tlib#persistent#Value()| tlib#persistent#Value .................. |tlib#persistent#Value()|
tlib#persistent#Save ................... |tlib#persistent#Save()| tlib#persistent#Save ................... |tlib#persistent#Save()|
g:tlib#vim#simalt_maximize ............. |g:tlib#vim#simalt_maximize| g:tlib#vim#simalt_maximize ............. |g:tlib#vim#simalt_maximize|
@ -116,6 +117,7 @@ Contents~
tlib#cache#Dir ......................... |tlib#cache#Dir()| tlib#cache#Dir ......................... |tlib#cache#Dir()|
tlib#cache#Filename .................... |tlib#cache#Filename()| tlib#cache#Filename .................... |tlib#cache#Filename()|
tlib#cache#Save ........................ |tlib#cache#Save()| tlib#cache#Save ........................ |tlib#cache#Save()|
tlib#cache#MTime ....................... |tlib#cache#MTime()|
tlib#cache#Get ......................... |tlib#cache#Get()| tlib#cache#Get ......................... |tlib#cache#Get()|
tlib#cache#Value ....................... |tlib#cache#Value()| tlib#cache#Value ....................... |tlib#cache#Value()|
tlib#cache#MaybePurge .................. |tlib#cache#MaybePurge()| tlib#cache#MaybePurge .................. |tlib#cache#MaybePurge()|
@ -492,6 +494,9 @@ tlib#persistent#Filename(type, ?file=%, ?mkdir=0)
*tlib#persistent#Get()* *tlib#persistent#Get()*
tlib#persistent#Get(...) tlib#persistent#Get(...)
*tlib#persistent#MTime()*
tlib#persistent#MTime(cfile)
*tlib#persistent#Value()* *tlib#persistent#Value()*
tlib#persistent#Value(...) tlib#persistent#Value(...)
@ -889,6 +894,9 @@ tlib#cache#Filename(type, ?file=%, ?mkdir=0, ?dir='')
*tlib#cache#Save()* *tlib#cache#Save()*
tlib#cache#Save(cfile, dictionary) tlib#cache#Save(cfile, dictionary)
*tlib#cache#MTime()*
tlib#cache#MTime(cfile)
*tlib#cache#Get()* *tlib#cache#Get()*
tlib#cache#Get(cfile, ...) tlib#cache#Get(cfile, ...)

View file

@ -1,11 +1,11 @@
" tlib.vim -- Some utility functions
" @Author: Tom Link (micathom AT gmail com?subject=[vim]) " @Author: Tom Link (micathom AT gmail com?subject=[vim])
" @Website: http://www.vim.org/account/profile.php?user_id=4037
" @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Created: 2007-04-10. " @Created: 2007-04-10.
" @Last Change: 2013-09-25. " @Last Change: 2013-09-25.
" @Revision: 749 " @License: GPL (see http://www.gnu.org/licenses/gpl.txt)
" @Revision: 750
" @Website: http://www.vim.org/account/profile.php?user_id=4037
" GetLatestVimScripts: 1863 1 tlib.vim " GetLatestVimScripts: 1863 1 tlib.vim
" tlib.vim -- Some utility functions
if &cp || exists("loaded_tlib") if &cp || exists("loaded_tlib")
finish finish
@ -14,7 +14,7 @@ if v:version < 700 "{{{2
echoerr "tlib requires Vim >= 7" echoerr "tlib requires Vim >= 7"
finish finish
endif endif
let loaded_tlib = 108 let loaded_tlib = 109
let s:save_cpo = &cpo let s:save_cpo = &cpo
set cpo&vim set cpo&vim

View file

@ -207,7 +207,8 @@ function! airline#extensions#load()
call airline#extensions#promptline#init(s:ext) call airline#extensions#promptline#init(s:ext)
endif endif
" load all other extensions not part of the default distribution " Load all other extensions, which are not part of the default distribution.
" (autoload/airline/extensions/*.vim outside of our s:script_path).
for file in split(globpath(&rtp, "autoload/airline/extensions/*.vim"), "\n") for file in split(globpath(&rtp, "autoload/airline/extensions/*.vim"), "\n")
" we have to check both resolved and unresolved paths, since it's possible " we have to check both resolved and unresolved paths, since it's possible
" that they might not get resolved properly (see #187) " that they might not get resolved properly (see #187)

View file

@ -2,7 +2,6 @@
" vim: et ts=2 sts=2 sw=2 " vim: et ts=2 sts=2 sw=2
let s:has_fugitive = exists('*fugitive#head') let s:has_fugitive = exists('*fugitive#head')
let s:has_fugitive_detect = exists('*fugitive#detect')
let s:has_lawrencium = exists('*lawrencium#statusline') let s:has_lawrencium = exists('*lawrencium#statusline')
let s:has_vcscommand = get(g:, 'airline#extensions#branch#use_vcscommand', 0) && exists('*VCSCommandGetStatusLine') let s:has_vcscommand = get(g:, 'airline#extensions#branch#use_vcscommand', 0) && exists('*VCSCommandGetStatusLine')
@ -10,36 +9,63 @@ if !s:has_fugitive && !s:has_lawrencium && !s:has_vcscommand
finish finish
endif endif
let s:git_dirs = {}
function! s:get_git_branch(path)
if has_key(s:git_dirs, a:path)
return s:git_dirs[a:path]
endif
let dir = fugitive#extract_git_dir(a:path)
if empty(dir)
let name = ''
else
try
let line = join(readfile(dir . '/HEAD'))
let name = strpart(line, 16)
catch
let name = ''
endtry
endif
let s:git_dirs[a:path] = name
return name
endfunction
function! airline#extensions#branch#head() function! airline#extensions#branch#head()
let head = '' if exists('b:airline_head') && !empty(b:airline_head)
return b:airline_head
endif
let b:airline_head = ''
if s:has_fugitive && !exists('b:mercurial_dir') if s:has_fugitive && !exists('b:mercurial_dir')
let head = fugitive#head() let b:airline_head = fugitive#head()
if empty(head) && s:has_fugitive_detect && !exists('b:git_dir') if empty(b:airline_head) && !exists('b:git_dir')
call fugitive#detect(getcwd()) let b:airline_head = s:get_git_branch(getcwd())
let head = fugitive#head()
endif endif
endif endif
if empty(head) if empty(b:airline_head)
if s:has_lawrencium if s:has_lawrencium
let head = lawrencium#statusline() let b:airline_head = lawrencium#statusline()
endif endif
endif endif
if empty(head) if empty(b:airline_head)
if s:has_vcscommand if s:has_vcscommand
call VCSCommandEnableBufferSetup() call VCSCommandEnableBufferSetup()
if exists('b:VCSCommandBufferInfo') if exists('b:VCSCommandBufferInfo')
let head = get(b:VCSCommandBufferInfo, 0, '') let b:airline_head = get(b:VCSCommandBufferInfo, 0, '')
endif endif
endif endif
endif endif
return empty(head) || !s:check_in_path() if empty(b:airline_head) || !s:check_in_path()
\ ? '' let b:airline_head = ''
\ : head endif
return b:airline_head
endfunction endfunction
function! airline#extensions#branch#get_head() function! airline#extensions#branch#get_head()
@ -78,5 +104,5 @@ function! airline#extensions#branch#init(ext)
call airline#parts#define_function('branch', 'airline#extensions#branch#get_head') call airline#parts#define_function('branch', 'airline#extensions#branch#get_head')
autocmd BufReadPost * unlet! b:airline_file_in_root autocmd BufReadPost * unlet! b:airline_file_in_root
autocmd CursorHold,ShellCmdPost,CmdwinLeave * unlet! b:airline_head
endfunction endfunction

View file

@ -20,7 +20,7 @@ function! airline#extensions#eclim#get_warnings()
if !empty(eclimList) if !empty(eclimList)
" Remove any non-eclim signs (see eclim#display#signs#Update) " Remove any non-eclim signs (see eclim#display#signs#Update)
call filter(eclimList, "v:val.name =~ '^\(qf_\)\?\(error\|info\|warning\)$'") call filter(eclimList, 'v:val.name =~ "^\\(qf_\\)\\?\\(error\\|info\\|warning\\)$"')
if !empty(eclimList) if !empty(eclimList)
let errorsLine = eclimList[0]['line'] let errorsLine = eclimList[0]['line']

View file

@ -6,6 +6,8 @@ let s:excludes = get(g:, 'airline#extensions#tabline#excludes', [])
let s:tab_nr_type = get(g:, 'airline#extensions#tabline#tab_nr_type', 0) let s:tab_nr_type = get(g:, 'airline#extensions#tabline#tab_nr_type', 0)
let s:show_buffers = get(g:, 'airline#extensions#tabline#show_buffers', 1) let s:show_buffers = get(g:, 'airline#extensions#tabline#show_buffers', 1)
let s:show_tab_nr = get(g:, 'airline#extensions#tabline#show_tab_nr', 1) let s:show_tab_nr = get(g:, 'airline#extensions#tabline#show_tab_nr', 1)
let s:show_tab_type = get(g:, 'airline#extensions#tabline#show_tab_type', 1)
let s:close_symbol = get(g:, 'airline#extensions#tabline#close_symbol', 'X')
let s:builder_context = { let s:builder_context = {
\ 'active' : 1, \ 'active' : 1,
@ -264,8 +266,10 @@ function! s:get_tabs()
call b.add_raw('%T') call b.add_raw('%T')
call b.add_section('airline_tabfill', '') call b.add_section('airline_tabfill', '')
call b.split() call b.split()
call b.add_section('airline_tab', ' %999XX ') call b.add_section('airline_tab', ' %999X'.s:close_symbol.' ')
if s:show_tab_type
call b.add_section('airline_tabtype', ' tabs ') call b.add_section('airline_tabtype', ' tabs ')
endif
let s:current_bufnr = curbuf let s:current_bufnr = curbuf
let s:current_tabnr = curtab let s:current_tabnr = curtab

View file

@ -31,12 +31,18 @@ function! airline#extensions#whitespace#check()
let trailing = 0 let trailing = 0
if index(checks, 'trailing') > -1 if index(checks, 'trailing') > -1
let trailing = search(' $', 'nw') let trailing = search('\s$', 'nw')
endif endif
let mixed = 0 let mixed = 0
if index(checks, 'indent') > -1 if index(checks, 'indent') > -1
let mixed = search('\v(^\t+ +)|(^ +\t+)', 'nw') " [<tab>]<space><tab>
" Spaces before or between tabs are not allowed
let t_s_t = '(^\t* +\t\s*\S)'
" <tab>(<space> x count)
" Count of spaces at the end of tabs should be less then tabstop value
let t_l_s = '(^\t+ {' . &ts . ',}' . '\S)'
let mixed = search('\v' . t_s_t . '|' . t_l_s, 'nw')
endif endif
if trailing != 0 || mixed != 0 if trailing != 0 || mixed != 0

View file

@ -44,7 +44,7 @@ let g:airline#themes#luna#palette.visual_modified = {
let s:IA = [ '#4e4e4e' , '#002b2b' , 59 , 23 , '' ] let s:IA = [ '#4e4e4e' , '#002b2b' , 59 , 23 , '' ]
let g:airline#themes#luna#palette.inactive = airline#themes#generate_color_map(s:IA, s:IA, s:IA) let g:airline#themes#luna#palette.inactive = airline#themes#generate_color_map(s:IA, s:IA, s:IA)
let g:airline#themes#luna#palette.inactive_modified = { let g:airline#themes#luna#palette.inactive_modified = {
\ 'airline_c': [ '#450000' , '' , 52 , '' , '' ] , \ 'airline_c': [ '#e20000' , '' , 166 , '' , '' ] ,
\ } \ }
let g:airline#themes#luna#palette.tabline = { let g:airline#themes#luna#palette.tabline = {

View file

@ -12,7 +12,7 @@ let s:N2 = [ '#343434' , '#b3b3b3' , 237 , 250 ]
let s:N3 = [ '#343434' , '#c7c7c7' , 237 , 252 ] let s:N3 = [ '#343434' , '#c7c7c7' , 237 , 252 ]
let g:airline#themes#sol#palette.normal = airline#themes#generate_color_map(s:N1, s:N2, s:N3) let g:airline#themes#sol#palette.normal = airline#themes#generate_color_map(s:N1, s:N2, s:N3)
let g:airline#themes#sol#palette.normal_modified = { let g:airline#themes#sol#palette.normal_modified = {
\ 'airline_c': [ '#ffffff' , '#ff3535' , 231 , 203 , '' ] , \ 'airline_c': [ '#ffffff' , '#ff6868' , 237 , 209 , '' ] ,
\ } \ }
@ -21,7 +21,7 @@ let s:I2 = [ '#343434' , '#a3a3a3' , 237 , 249 ]
let s:I3 = [ '#343434' , '#b0b0b0' , 237 , 250 ] let s:I3 = [ '#343434' , '#b0b0b0' , 237 , 250 ]
let g:airline#themes#sol#palette.insert = airline#themes#generate_color_map(s:I1, s:I2, s:I3) let g:airline#themes#sol#palette.insert = airline#themes#generate_color_map(s:I1, s:I2, s:I3)
let g:airline#themes#sol#palette.insert_modified = { let g:airline#themes#sol#palette.insert_modified = {
\ 'airline_c': [ '#ffffff' , '#ff6868' , 225 , 167 , '' ] , \ 'airline_c': [ '#343434' , '#ffdbc7' , 237 , 216 , '' ] ,
\ } \ }
let g:airline#themes#sol#palette.insert_paste = { let g:airline#themes#sol#palette.insert_paste = {
\ 'airline_a': [ s:I1[0] , '#09643f' , s:I1[2] , 30 , '' ] , \ 'airline_a': [ s:I1[0] , '#09643f' , s:I1[2] , 30 , '' ] ,
@ -38,7 +38,7 @@ let s:V2 = [ '#343434' , '#a3a3a3' , 237 , 249 ]
let s:V3 = [ '#343434' , '#b0b0b0' , 237 , 250 ] let s:V3 = [ '#343434' , '#b0b0b0' , 237 , 250 ]
let g:airline#themes#sol#palette.visual = airline#themes#generate_color_map(s:V1, s:V2, s:V3) let g:airline#themes#sol#palette.visual = airline#themes#generate_color_map(s:V1, s:V2, s:V3)
let g:airline#themes#sol#palette.visual_modified = { let g:airline#themes#sol#palette.visual_modified = {
\ 'airline_c': [ '#ffffff' , '#ff3535' , 231 , 203 , '' ] , \ 'airline_c': [ '#343434' , '#ffdbc7' , 237 , 216 , '' ] ,
\ } \ }
let s:IA = [ '#777777' , '#c7c7c7' , 244 , 251 , '' ] let s:IA = [ '#777777' , '#c7c7c7' , 244 , 251 , '' ]
@ -52,10 +52,10 @@ let g:airline#themes#sol#palette.tabline = {
\ 'airline_tabsel': ['#ffffff', '#004b9a', 231, 31 , ''], \ 'airline_tabsel': ['#ffffff', '#004b9a', 231, 31 , ''],
\ 'airline_tabtype': ['#343434', '#a0a0a0', 237, 248, ''], \ 'airline_tabtype': ['#343434', '#a0a0a0', 237, 248, ''],
\ 'airline_tabfill': ['#343434', '#c7c7c7', 237, 251, ''], \ 'airline_tabfill': ['#343434', '#c7c7c7', 237, 251, ''],
\ 'airline_tabmod': ['#ffffff', '#ff6868', 231, 167, ''], \ 'airline_tabmod': ['#343434', '#ffdbc7', 237, 216, ''],
\ } \ }
let s:WI = [ '#eeeeee', '#ff0f38', 255, 201 ] let s:WI = [ '#eeeeee', '#e33900', 255, 166 ]
let g:airline#themes#sol#palette.normal.airline_warning = [ let g:airline#themes#sol#palette.normal.airline_warning = [
\ s:WI[0], s:WI[1], s:WI[2], s:WI[3] \ s:WI[0], s:WI[1], s:WI[2], s:WI[3]
\ ] \ ]

View file

@ -382,6 +382,9 @@ eclim <https://eclim.org>
* enable/disable displaying tab number in tabs mode. > * enable/disable displaying tab number in tabs mode. >
let g:airline#extensions#tabline#show_tab_nr = 1 let g:airline#extensions#tabline#show_tab_nr = 1
* enable/disable displaying tab type (far right)
let g:airline#extensions#tabline#show_tab_type = 1
* defines the name of a formatter for how buffer names are displayed. > * defines the name of a formatter for how buffer names are displayed. >
let g:airline#extensions#tabline#formatter = 'default' let g:airline#extensions#tabline#formatter = 'default'
@ -430,6 +433,10 @@ eclim <https://eclim.org>
let g:airline#extensions#tabline#left_alt_sep = '' let g:airline#extensions#tabline#left_alt_sep = ''
let g:airline#extensions#tabline#right_sep = '' let g:airline#extensions#tabline#right_sep = ''
let g:airline#extensions#tabline#right_alt_sep = '' let g:airline#extensions#tabline#right_alt_sep = ''
* configure symbol used to represent close button
let g:airline#extensions#tabline#close_symbol = 'X'
< <
Note: Enabling this extension will modify 'showtabline' and 'guioptions'. Note: Enabling this extension will modify 'showtabline' and 'guioptions'.
@ -616,7 +623,7 @@ to your liking. Here is an example: >
return 1 return 1
endfunction endfunction
< <
The above example uses various some example highlight groups to demonstrate The above example uses various example highlight groups to demonstrate
that you can use any combination from the loaded colorscheme. However, if that you can use any combination from the loaded colorscheme. However, if
you want colors to change between modes, you should use one of the section you want colors to change between modes, you should use one of the section
highlight groups, e.g. `airline_a` and `airline_b`. highlight groups, e.g. `airline_a` and `airline_b`.

View file

@ -2,8 +2,8 @@
Comment stuff out. Use `gcc` to comment out a line (takes a count), Comment stuff out. Use `gcc` to comment out a line (takes a count),
`gc` to comment out the target of a motion (for example, `gcap` to `gc` to comment out the target of a motion (for example, `gcap` to
comment out a paragraph), and `gc` in visual mode to comment out the comment out a paragraph), `gc` in visual mode to comment out the selection,
selection. That's it. and `gc` in operator pending mode to target a comment. That's it.
I wrote this because 5 years after Vim added support for mapping an I wrote this because 5 years after Vim added support for mapping an
operator, I still couldn't find a commenting plugin that leveraged that operator, I still couldn't find a commenting plugin that leveraged that
@ -11,10 +11,8 @@ feature (I overlooked
[tcomment.vim](https://github.com/tomtom/tcomment_vim)). Striving for [tcomment.vim](https://github.com/tomtom/tcomment_vim)). Striving for
minimalism, it weighs in at under 100 lines of code. minimalism, it weighs in at under 100 lines of code.
Oh, and it uncomments, too. The above maps actually toggle, and `gcu` Oh, and it uncomments, too. The above maps actually toggle, and `gcgc`
uncomments a set of adjacent commented lines. Install uncomments a set of adjacent commented lines.
[repeat.vim](https://github.com/tpope/vim-repeat) to enable
repeating `gcu` with `.`. (The other maps are repeatable without it.)
## Installation ## Installation

View file

@ -9,21 +9,22 @@ correctly set, or uses b:commentary_format if it is set.
The gc mappings are preferred, while the \\ mappings are provided for The gc mappings are preferred, while the \\ mappings are provided for
backwards compatibility. backwards compatibility.
*gc* *\\* *gc*
gc{motion} Comment or uncomment lines that {motion} moves over. gc{motion} Comment or uncomment lines that {motion} moves over.
\\{motion}
*gcc* *\\\* *gcc*
gcc Comment or uncomment [count] lines. gcc Comment or uncomment [count] lines.
\\\
*v_gc* *v_\\* *v_gc*
{Visual}gc Comment or uncomment the highlighted lines. {Visual}gc Comment or uncomment the highlighted lines.
{Visual}\\
*gcu* *\\u* *o_gc*
gcu Uncomment the current and adjacent commented lines. gc Text object for a comment (operator pending mode
\\u only.)
*gcgc* *gcu*
gcgc Uncomment the current and adjacent commented lines.
gcu
The |User| CommentaryPost autocommand fires after a successful operation and The |User| CommentaryPost autocommand fires after a successful operation and
can be used for advanced customization. can be used for advanced customization.

View file

@ -44,10 +44,16 @@ function! s:go(type,...) abort
endif endif
call setline(lnum,line) call setline(lnum,line)
endfor endfor
let modelines = &modelines
try
set modelines=0
silent doautocmd User CommentaryPost silent doautocmd User CommentaryPost
finally
let &modelines = modelines
endtry
endfunction endfunction
function! s:undo() abort function! s:textobject(inner) abort
let [l, r] = s:surroundings() let [l, r] = s:surroundings()
let lnums = [line('.')+1, line('.')-2] let lnums = [line('.')+1, line('.')-2]
for [index, dir, bound, line] in [[0, -1, 1, ''], [1, 1, line('$'), '']] for [index, dir, bound, line] in [[0, -1, 1, ''], [1, 1, line('$'), '']]
@ -56,27 +62,38 @@ function! s:undo() abort
let line = matchstr(getline(lnums[index]+dir),'\S.*\s\@<!') let line = matchstr(getline(lnums[index]+dir),'\S.*\s\@<!')
endwhile endwhile
endfor endfor
call s:go(lnums[0], lnums[1]) while (a:inner || lnums[1] != line('$')) && empty(getline(lnums[0]))
silent! call repeat#set("\<Plug>CommentaryUndo") let lnums[0] += 1
endwhile
while a:inner && empty(getline(lnums[1]))
let lnums[1] -= 1
endwhile
if lnums[0] <= lnums[1]
execute 'normal! 'lnums[0].'GV'.lnums[1].'G'
endif
endfunction endfunction
xnoremap <silent> <Plug>Commentary :<C-U>call <SID>go(line("'<"),line("'>"))<CR> xnoremap <silent> <Plug>Commentary :<C-U>call <SID>go(line("'<"),line("'>"))<CR>
nnoremap <silent> <Plug>Commentary :<C-U>set opfunc=<SID>go<CR>g@ nnoremap <silent> <Plug>Commentary :<C-U>set opfunc=<SID>go<CR>g@
nnoremap <silent> <Plug>CommentaryLine :<C-U>set opfunc=<SID>go<Bar>exe 'norm! 'v:count1.'g@_'<CR> nnoremap <silent> <Plug>CommentaryLine :<C-U>set opfunc=<SID>go<Bar>exe 'norm! 'v:count1.'g@_'<CR>
nnoremap <silent> <Plug>CommentaryUndo :<C-U>call <SID>undo()<CR> onoremap <silent> <Plug>Commentary :<C-U>call <SID>textobject(0)<CR>
nnoremap <silent> <Plug>ChangeCommentary c:<C-U>call <SID>textobject(1)<CR>
nmap <silent> <Plug>CommentaryUndo <Plug>Commentary<Plug>Commentary
if !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# '' if 1 || !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# ''
xmap gc <Plug>Commentary xmap gc <Plug>Commentary
nmap gc <Plug>Commentary nmap gc <Plug>Commentary
omap gc <Plug>Commentary
nmap gcc <Plug>CommentaryLine nmap gcc <Plug>CommentaryLine
nmap gcu <Plug>CommentaryUndo nmap cgc <Plug>ChangeCommentary
nmap gcu <Plug>Commentary<Plug>Commentary
endif endif
if maparg('\\','n') ==# '' && maparg('\','n') ==# '' && get(g:, 'commentary_map_backslash', 1) if maparg('\\','n') ==# '' && maparg('\','n') ==# '' && get(g:, 'commentary_map_backslash', 1)
xmap \\ <Plug>Commentary xmap \\ <Plug>Commentary:echomsg '\\ is deprecated. Use gc'<CR>
nmap \\ <Plug>Commentary nmap \\ :echomsg '\\ is deprecated. Use gc'<CR><Plug>Commentary
nmap \\\ <Plug>CommentaryLine nmap \\\ <Plug>CommentaryLine:echomsg '\\ is deprecated. Use gc'<CR>
nmap \\u <Plug>CommentaryUndo nmap \\u <Plug>CommentaryUndo:echomsg '\\ is deprecated. Use gc'<CR>
endif endif
" vim:set et sw=2: " vim:set et sw=2:

View file

@ -34,6 +34,7 @@ that are part of Git repositories).
window. The following maps, which work on the cursor window. The following maps, which work on the cursor
line file where sensible, are provided: line file where sensible, are provided:
g? show this help
<C-N> next file <C-N> next file
<C-P> previous file <C-P> previous file
<CR> |:Gedit| <CR> |:Gedit|
@ -177,6 +178,7 @@ that are part of Git repositories).
along to git-blame. The following maps, which work on along to git-blame. The following maps, which work on
the cursor line commit where sensible, are provided: the cursor line commit where sensible, are provided:
g? show this help
A resize to end of author column A resize to end of author column
C resize to end of commit column C resize to end of commit column
D resize to end of date/time column D resize to end of date/time column

View file

@ -29,7 +29,7 @@ endfunction
function! s:shellesc(arg) abort function! s:shellesc(arg) abort
if a:arg =~ '^[A-Za-z0-9_/.-]\+$' if a:arg =~ '^[A-Za-z0-9_/.-]\+$'
return a:arg return a:arg
elseif &shell =~# 'cmd' elseif &shell =~# 'cmd' || &shell =~# 'power'
return '"'.s:gsub(s:gsub(a:arg, '"', '""'), '\%', '"%"').'"' return '"'.s:gsub(s:gsub(a:arg, '"', '""'), '\%', '"%"').'"'
else else
return shellescape(a:arg) return shellescape(a:arg)
@ -49,14 +49,14 @@ function! s:throw(string) abort
throw v:errmsg throw v:errmsg
endfunction endfunction
function! s:warn(str) function! s:warn(str) abort
echohl WarningMsg echohl WarningMsg
echomsg a:str echomsg a:str
echohl None echohl None
let v:warningmsg = a:str let v:warningmsg = a:str
endfunction endfunction
function! s:shellslash(path) function! s:shellslash(path) abort
if exists('+shellslash') && !&shellslash if exists('+shellslash') && !&shellslash
return s:gsub(a:path,'\\','/') return s:gsub(a:path,'\\','/')
else else
@ -73,7 +73,7 @@ function! fugitive#git_version(...) abort
return s:git_versions[g:fugitive_git_executable] return s:git_versions[g:fugitive_git_executable]
endfunction endfunction
function! s:recall() function! s:recall() abort
let rev = s:sub(s:buffer().rev(), '^/', '') let rev = s:sub(s:buffer().rev(), '^/', '')
if rev ==# ':' if rev ==# ':'
return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*') return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*')
@ -102,7 +102,7 @@ function! s:command(definition) abort
let s:commands += [a:definition] let s:commands += [a:definition]
endfunction endfunction
function! s:define_commands() function! s:define_commands() abort
for command in s:commands for command in s:commands
exe 'command! -buffer '.command exe 'command! -buffer '.command
endfor endfor
@ -164,7 +164,7 @@ function! fugitive#extract_git_dir(path) abort
return '' return ''
endfunction endfunction
function! fugitive#detect(path) function! fugitive#detect(path) abort
if exists('b:git_dir') && (b:git_dir ==# '' || b:git_dir =~# '/$') if exists('b:git_dir') && (b:git_dir ==# '' || b:git_dir =~# '/$')
unlet b:git_dir unlet b:git_dir
endif endif
@ -198,6 +198,7 @@ augroup fugitive
autocmd FileType netrw call fugitive#detect(expand('%:p')) autocmd FileType netrw call fugitive#detect(expand('%:p'))
autocmd User NERDTreeInit,NERDTreeNewRoot call fugitive#detect(b:NERDTreeRoot.path.str()) autocmd User NERDTreeInit,NERDTreeNewRoot call fugitive#detect(b:NERDTreeRoot.path.str())
autocmd VimEnter * if expand('<amatch>')==''|call fugitive#detect(getcwd())|endif autocmd VimEnter * if expand('<amatch>')==''|call fugitive#detect(getcwd())|endif
autocmd CmdWinEnter * call fugitive#detect(expand('#:p'))
autocmd BufWinLeave * execute getwinvar(+bufwinnr(+expand('<abuf>')), 'fugitive_leave') autocmd BufWinLeave * execute getwinvar(+bufwinnr(+expand('<abuf>')), 'fugitive_leave')
augroup END augroup END
@ -221,7 +222,7 @@ function! s:repo(...) abort
call s:throw('not a git repository: '.expand('%:p')) call s:throw('not a git repository: '.expand('%:p'))
endfunction endfunction
function! fugitive#repo(...) function! fugitive#repo(...) abort
return call('s:repo', a:000) return call('s:repo', a:000)
endfunction endfunction
@ -322,6 +323,8 @@ function! s:repo_head(...) dict abort
" truncate hash to a:1 characters if we're in detached head mode " truncate hash to a:1 characters if we're in detached head mode
let len = a:0 ? a:1 : 0 let len = a:0 ? a:1 : 0
let branch = len ? head[0:len-1] : '' let branch = len ? head[0:len-1] : ''
else
return ''
endif endif
return branch return branch
@ -466,7 +469,7 @@ function! s:buffer_setvar(var,value) dict abort
endfunction endfunction
function! s:buffer_getline(lnum) dict abort function! s:buffer_getline(lnum) dict abort
return getbufline(self['#'],a:lnum)[0] return get(getbufline(self['#'], a:lnum), 0, '')
endfunction endfunction
function! s:buffer_repo() dict abort function! s:buffer_repo() dict abort
@ -752,15 +755,15 @@ function! s:stage_info(lnum) abort
endif endif
endfunction endfunction
function! s:StageNext(count) function! s:StageNext(count) abort
for i in range(a:count) for i in range(a:count)
call search('^#\t.*','W') call search('^#\t.*','W')
endfor endfor
return '.' return '.'
endfunction endfunction
function! s:StagePrevious(count) function! s:StagePrevious(count) abort
if line('.') == 1 && exists(':CtrlP') if line('.') == 1 && exists(':CtrlP') && get(g:, 'ctrl_p_map') =~? '^<c-p>$'
return 'CtrlP '.fnameescape(s:repo().tree()) return 'CtrlP '.fnameescape(s:repo().tree())
else else
for i in range(a:count) for i in range(a:count)
@ -770,7 +773,7 @@ function! s:StagePrevious(count)
endif endif
endfunction endfunction
function! s:StageReloadSeek(target,lnum1,lnum2) function! s:StageReloadSeek(target,lnum1,lnum2) abort
let jump = a:target let jump = a:target
let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*') let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*')
if f !=# '' | let jump = f | endif if f !=# '' | let jump = f | endif
@ -949,7 +952,7 @@ function! s:Commit(args) abort
try try
try try
execute cd.s:fnameescape(s:repo().tree()) execute cd.s:fnameescape(s:repo().tree())
if &shell =~# 'cmd' if &shell =~# 'cmd' || &shell =~# 'power'
let command = '' let command = ''
let old_editor = $GIT_EDITOR let old_editor = $GIT_EDITOR
let $GIT_EDITOR = 'false' let $GIT_EDITOR = 'false'
@ -959,7 +962,7 @@ function! s:Commit(args) abort
let command .= s:repo().git_command('commit').' '.a:args let command .= s:repo().git_command('commit').' '.a:args
if &shell =~# 'csh' if &shell =~# 'csh'
noautocmd silent execute '!('.command.' > '.outfile.') >& '.errorfile noautocmd silent execute '!('.command.' > '.outfile.') >& '.errorfile
elseif a:args =~# '\%(^\| \)--interactive\>' elseif a:args =~# '\%(^\| \)-\%(-interactive\|p\|-patch\)\>'
noautocmd execute '!'.command.' 2> '.errorfile noautocmd execute '!'.command.' 2> '.errorfile
else else
noautocmd silent execute '!'.command.' > '.outfile.' 2> '.errorfile noautocmd silent execute '!'.command.' > '.outfile.' 2> '.errorfile
@ -982,7 +985,7 @@ function! s:Commit(args) abort
let error = get(errors,-2,get(errors,-1,'!')) let error = get(errors,-2,get(errors,-1,'!'))
if error =~# 'false''\=\.$' if error =~# 'false''\=\.$'
let args = a:args let args = a:args
let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-[es]|--edit|--interactive|--signoff)%($| )','') let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-[esp]|--edit|--interactive|patch|--signoff)%($| )','')
let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-F|--file|-m|--message)%(\s+|\=)%(''[^'']*''|"%(\\.|[^"])*"|\\.|\S)*','') let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-F|--file|-m|--message)%(\s+|\=)%(''[^'']*''|"%(\\.|[^"])*"|\\.|\S)*','')
let args = s:gsub(args,'%(^| )@<=[%#]%(:\w)*','\=expand(submatch(0))') let args = s:gsub(args,'%(^| )@<=[%#]%(:\w)*','\=expand(submatch(0))')
let args = '-F '.s:shellesc(msgfile).' '.args let args = '-F '.s:shellesc(msgfile).' '.args
@ -1028,7 +1031,7 @@ function! s:CommitComplete(A,L,P) abort
endif endif
endfunction endfunction
function! s:FinishCommit() function! s:FinishCommit() abort
let args = getbufvar(+expand('<abuf>'),'fugitive_commit_arguments') let args = getbufvar(+expand('<abuf>'),'fugitive_commit_arguments')
if !empty(args) if !empty(args)
call setbufvar(+expand('<abuf>'),'fugitive_commit_arguments','') call setbufvar(+expand('<abuf>'),'fugitive_commit_arguments','')
@ -1091,7 +1094,7 @@ function! s:Grep(cmd,bang,arg) abort
endtry endtry
endfunction endfunction
function! s:Log(cmd,...) function! s:Log(cmd,...) abort
let path = s:buffer().path('/') let path = s:buffer().path('/')
if path =~# '^/\.git\%(/\|$\)' || index(a:000,'--') != -1 if path =~# '^/\.git\%(/\|$\)' || index(a:000,'--') != -1
let path = '' let path = ''
@ -1389,11 +1392,11 @@ call s:command("-bar -nargs=* -complete=customlist,s:EditComplete Gsdiff :execut
augroup fugitive_diff augroup fugitive_diff
autocmd! autocmd!
autocmd BufWinLeave * if s:diff_window_count() == 2 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff_all(getbufvar(+expand('<abuf>'), 'git_dir')) | endif autocmd BufWinLeave * if &diff && s:diff_window_count() == 2 && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff_all(getbufvar(+expand('<abuf>'), 'git_dir')) | endif
autocmd BufWinEnter * if s:diff_window_count() == 1 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff() | endif autocmd BufWinEnter * if &diff && s:diff_window_count() == 1 && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff() | endif
augroup END augroup END
function! s:diff_window_count() function! s:diff_window_count() abort
let c = 0 let c = 0
for nr in range(1,winnr('$')) for nr in range(1,winnr('$'))
let c += getwinvar(nr,'&diff') let c += getwinvar(nr,'&diff')
@ -1401,7 +1404,7 @@ function! s:diff_window_count()
return c return c
endfunction endfunction
function! s:diff_restore() function! s:diff_restore() abort
let restore = 'setlocal nodiff noscrollbind' let restore = 'setlocal nodiff noscrollbind'
\ . ' scrollopt=' . &l:scrollopt \ . ' scrollopt=' . &l:scrollopt
\ . (&l:wrap ? ' wrap' : ' nowrap') \ . (&l:wrap ? ' wrap' : ' nowrap')
@ -1415,14 +1418,14 @@ function! s:diff_restore()
return restore return restore
endfunction endfunction
function! s:diffthis() function! s:diffthis() abort
if !&diff if !&diff
let w:fugitive_diff_restore = s:diff_restore() let w:fugitive_diff_restore = s:diff_restore()
diffthis diffthis
endif endif
endfunction endfunction
function! s:diffoff() function! s:diffoff() abort
if exists('w:fugitive_diff_restore') if exists('w:fugitive_diff_restore')
execute w:fugitive_diff_restore execute w:fugitive_diff_restore
unlet w:fugitive_diff_restore unlet w:fugitive_diff_restore
@ -1431,7 +1434,7 @@ function! s:diffoff()
endif endif
endfunction endfunction
function! s:diffoff_all(dir) function! s:diffoff_all(dir) abort
for nr in range(1,winnr('$')) for nr in range(1,winnr('$'))
if getwinvar(nr,'&diff') if getwinvar(nr,'&diff')
if nr != winnr() if nr != winnr()
@ -1467,7 +1470,7 @@ endfunction
call s:add_methods('buffer',['compare_age']) call s:add_methods('buffer',['compare_age'])
function! s:Diff(bang,...) function! s:Diff(bang,...) abort
let vert = a:bang ? '' : 'vertical ' let vert = a:bang ? '' : 'vertical '
if exists(':DiffGitCached') if exists(':DiffGitCached')
return 'DiffGitCached' return 'DiffGitCached'
@ -1510,6 +1513,9 @@ function! s:Diff(bang,...)
let spec = s:repo().translate(file) let spec = s:repo().translate(file)
let commit = matchstr(spec,'\C[^:/]//\zs\x\+') let commit = matchstr(spec,'\C[^:/]//\zs\x\+')
let restore = s:diff_restore() let restore = s:diff_restore()
if exists('+cursorbind')
setlocal cursorbind
endif
let w:fugitive_diff_restore = restore let w:fugitive_diff_restore = restore
if s:buffer().compare_age(commit) < 0 if s:buffer().compare_age(commit) < 0
execute 'rightbelow '.vert.'diffsplit '.s:fnameescape(spec) execute 'rightbelow '.vert.'diffsplit '.s:fnameescape(spec)
@ -1517,6 +1523,11 @@ function! s:Diff(bang,...)
execute 'leftabove '.vert.'diffsplit '.s:fnameescape(spec) execute 'leftabove '.vert.'diffsplit '.s:fnameescape(spec)
endif endif
let w:fugitive_diff_restore = restore let w:fugitive_diff_restore = restore
let winnr = winnr()
if getwinvar('#', '&diff')
wincmd p
call feedkeys("\<C-W>p", 'n')
endif
return '' return ''
catch /^fugitive:/ catch /^fugitive:/
return 'echoerr v:errmsg' return 'echoerr v:errmsg'
@ -1526,7 +1537,7 @@ endfunction
" }}}1 " }}}1
" Gmove, Gremove {{{1 " Gmove, Gremove {{{1
function! s:Move(force,destination) function! s:Move(force,destination) abort
if a:destination =~# '^/' if a:destination =~# '^/'
let destination = a:destination[1:-1] let destination = a:destination[1:-1]
else else
@ -1560,7 +1571,7 @@ function! s:Move(force,destination)
endif endif
endfunction endfunction
function! s:MoveComplete(A,L,P) function! s:MoveComplete(A,L,P) abort
if a:A =~ '^/' if a:A =~ '^/'
return s:repo().superglob(a:A) return s:repo().superglob(a:A)
else else
@ -1570,7 +1581,7 @@ function! s:MoveComplete(A,L,P)
endif endif
endfunction endfunction
function! s:Remove(force) function! s:Remove(force) abort
if s:buffer().commit() ==# '' if s:buffer().commit() ==# ''
let cmd = ['rm'] let cmd = ['rm']
elseif s:buffer().commit() ==# '0' elseif s:buffer().commit() ==# '0'
@ -1611,7 +1622,7 @@ augroup fugitive_blame
autocmd User Fugitive if s:buffer().type('file', 'blob') | exe "command! -buffer -bar -bang -range=0 -nargs=* Gblame :execute s:Blame(<bang>0,<line1>,<line2>,<count>,[<f-args>])" | endif autocmd User Fugitive if s:buffer().type('file', 'blob') | exe "command! -buffer -bar -bang -range=0 -nargs=* Gblame :execute s:Blame(<bang>0,<line1>,<line2>,<count>,[<f-args>])" | endif
augroup END augroup END
function! s:linechars(pattern) function! s:linechars(pattern) abort
let chars = strlen(s:gsub(matchstr(getline('.'), a:pattern), '.', '.')) let chars = strlen(s:gsub(matchstr(getline('.'), a:pattern), '.', '.'))
if exists('*synconcealed') && &conceallevel > 1 if exists('*synconcealed') && &conceallevel > 1
for col in range(1, chars) for col in range(1, chars)
@ -1686,7 +1697,7 @@ function! s:Blame(bang,line1,line2,count,args) abort
execute top execute top
normal! zt normal! zt
execute current execute current
setlocal nomodified nomodifiable nonumber scrollbind nowrap foldcolumn=0 nofoldenable filetype=fugitiveblame setlocal nomodified nomodifiable nonumber scrollbind nowrap foldcolumn=0 nofoldenable winfixwidth filetype=fugitiveblame
if exists('+concealcursor') if exists('+concealcursor')
setlocal concealcursor=nc conceallevel=2 setlocal concealcursor=nc conceallevel=2
endif endif
@ -1694,6 +1705,8 @@ function! s:Blame(bang,line1,line2,count,args) abort
setlocal norelativenumber setlocal norelativenumber
endif endif
execute "vertical resize ".(s:linechars('.\{-\}\ze\s\+\d\+)')+1) execute "vertical resize ".(s:linechars('.\{-\}\ze\s\+\d\+)')+1)
nnoremap <buffer> <silent> <F1> :help fugitive-:Gblame<CR>
nnoremap <buffer> <silent> g? :help fugitive-:Gblame<CR>
nnoremap <buffer> <silent> q :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete','^-1','','')<CR> nnoremap <buffer> <silent> q :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete','^-1','','')<CR>
nnoremap <buffer> <silent> gq :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete<Bar>if expand("%:p") =~# "^fugitive:[\\/][\\/]"<Bar>Gedit<Bar>endif','^-1','','')<CR> nnoremap <buffer> <silent> gq :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete<Bar>if expand("%:p") =~# "^fugitive:[\\/][\\/]"<Bar>Gedit<Bar>endif','^-1','','')<CR>
nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>BlameCommit("exe 'norm q'<Bar>edit")<CR> nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>BlameCommit("exe 'norm q'<Bar>edit")<CR>
@ -1933,7 +1946,7 @@ function! s:github_url(repo,url,rev,commit,path,type,line1,line2) abort
for domain in domains for domain in domains
let domain_pattern .= '\|' . escape(split(domain, '://')[-1], '.') let domain_pattern .= '\|' . escape(split(domain, '://')[-1], '.')
endfor endfor
let repo = matchstr(a:url,'^\%(https\=://\|git://\|git@\)\zs\('.domain_pattern.'\)[/:].\{-\}\ze\%(\.git\)\=$') let repo = matchstr(a:url,'^\%(https\=://\|git://\|git@\)\=\zs\('.domain_pattern.'\)[/:].\{-\}\ze\%(\.git\)\=$')
if repo ==# '' if repo ==# ''
return '' return ''
endif endif
@ -2035,14 +2048,14 @@ function! s:ReplaceCmd(cmd,...) abort
let prefix = '' let prefix = ''
try try
if a:0 && a:1 != '' if a:0 && a:1 != ''
if &shell =~# 'cmd' if &shell =~# 'cmd' || &shell =~# 'power'
let old_index = $GIT_INDEX_FILE let old_index = $GIT_INDEX_FILE
let $GIT_INDEX_FILE = a:1 let $GIT_INDEX_FILE = a:1
else else
let prefix = 'env GIT_INDEX_FILE='.s:shellesc(a:1).' ' let prefix = 'env GIT_INDEX_FILE='.s:shellesc(a:1).' '
endif endif
endif endif
if &shell =~# 'cmd' if &shell =~# 'cmd' || &shell =~# 'power'
let cmd_escape_char = &shellxquote == '(' ? '^' : '^^^' let cmd_escape_char = &shellxquote == '(' ? '^' : '^^^'
call system('cmd /c "'.prefix.s:gsub(a:cmd,'[<>]', cmd_escape_char.'&').' > '.tmp.'"') call system('cmd /c "'.prefix.s:gsub(a:cmd,'[<>]', cmd_escape_char.'&').' > '.tmp.'"')
else else
@ -2066,7 +2079,7 @@ function! s:ReplaceCmd(cmd,...) abort
endtry endtry
endfunction endfunction
function! s:BufReadIndex() function! s:BufReadIndex() abort
if !exists('b:fugitive_display_format') if !exists('b:fugitive_display_format')
let b:fugitive_display_format = filereadable(expand('%').'.lock') let b:fugitive_display_format = filereadable(expand('%').'.lock')
endif endif
@ -2086,7 +2099,7 @@ function! s:BufReadIndex()
else else
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd() let dir = getcwd()
if fugitive#git_version() =~# '^0\|1\.[1-7]\.' if fugitive#git_version() =~# '^0\|^1\.[1-7]\.'
let cmd = s:repo().git_command('status') let cmd = s:repo().git_command('status')
else else
let cmd = s:repo().git_command( let cmd = s:repo().git_command(
@ -2132,12 +2145,14 @@ function! s:BufReadIndex()
xnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line("'<"),line("'>"))<CR> xnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line("'<"),line("'>"))<CR>
nnoremap <buffer> <silent> q :<C-U>if bufnr('$') == 1<Bar>quit<Bar>else<Bar>bdelete<Bar>endif<CR> nnoremap <buffer> <silent> q :<C-U>if bufnr('$') == 1<Bar>quit<Bar>else<Bar>bdelete<Bar>endif<CR>
nnoremap <buffer> <silent> R :<C-U>edit<CR> nnoremap <buffer> <silent> R :<C-U>edit<CR>
nnoremap <buffer> <silent> g? :help fugitive-:Gstatus<CR>
nnoremap <buffer> <silent> <F1> :help fugitive-:Gstatus<CR>
catch /^fugitive:/ catch /^fugitive:/
return 'echoerr v:errmsg' return 'echoerr v:errmsg'
endtry endtry
endfunction endfunction
function! s:FileRead() function! s:FileRead() abort
try try
let repo = s:repo(fugitive#extract_git_dir(expand('<amatch>'))) let repo = s:repo(fugitive#extract_git_dir(expand('<amatch>')))
let path = s:sub(s:sub(matchstr(expand('<amatch>'),'fugitive://.\{-\}//\zs.*'),'/',':'),'^\d:',':&') let path = s:sub(s:sub(matchstr(expand('<amatch>'),'fugitive://.\{-\}//\zs.*'),'/',':'),'^\d:',':&')
@ -2154,7 +2169,7 @@ function! s:FileRead()
endtry endtry
endfunction endfunction
function! s:BufReadIndexFile() function! s:BufReadIndexFile() abort
try try
let b:fugitive_type = 'blob' let b:fugitive_type = 'blob'
let b:git_dir = s:repo().dir() let b:git_dir = s:repo().dir()
@ -2164,6 +2179,7 @@ function! s:BufReadIndexFile()
if &bufhidden ==# '' if &bufhidden ==# ''
setlocal bufhidden=delete setlocal bufhidden=delete
endif endif
setlocal noswapfile
endtry endtry
return '' return ''
catch /^fugitive: rev-parse/ catch /^fugitive: rev-parse/
@ -2174,7 +2190,7 @@ function! s:BufReadIndexFile()
endtry endtry
endfunction endfunction
function! s:BufWriteIndexFile() function! s:BufWriteIndexFile() abort
let tmp = tempname() let tmp = tempname()
try try
let path = matchstr(expand('<amatch>'),'//\d/\zs.*') let path = matchstr(expand('<amatch>'),'//\d/\zs.*')
@ -2187,7 +2203,7 @@ function! s:BufWriteIndexFile()
endif endif
let info = old_mode.' '.sha1.' '.stage."\t".path let info = old_mode.' '.sha1.' '.stage."\t".path
call writefile([info],tmp) call writefile([info],tmp)
if &shell =~# 'cmd' if &shell =~# 'cmd' || &shell =~# 'power'
let error = system('type '.s:gsub(tmp,'/','\\').'|'.s:repo().git_command('update-index','--index-info')) let error = system('type '.s:gsub(tmp,'/','\\').'|'.s:repo().git_command('update-index','--index-info'))
else else
let error = system(s:repo().git_command('update-index','--index-info').' < '.tmp) let error = system(s:repo().git_command('update-index','--index-info').' < '.tmp)
@ -2205,7 +2221,7 @@ function! s:BufWriteIndexFile()
endtry endtry
endfunction endfunction
function! s:BufReadObject() function! s:BufReadObject() abort
try try
setlocal noro ma setlocal noro ma
let b:git_dir = s:repo().dir() let b:git_dir = s:repo().dir()
@ -2226,7 +2242,7 @@ function! s:BufReadObject()
endif endif
let pos = getpos('.') let pos = getpos('.')
silent %delete silent keepjumps %delete_
setlocal endofline setlocal endofline
try try
@ -2250,23 +2266,25 @@ function! s:BufReadObject()
call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash))
else else
call s:ReplaceCmd(s:repo().git_command('show','--no-color','--pretty=format:tree %T%nparent %P%nauthor %an <%ae> %ad%ncommitter %cn <%ce> %cd%nencoding %e%n%n%s%n%n%b',hash)) call s:ReplaceCmd(s:repo().git_command('show','--no-color','--pretty=format:tree %T%nparent %P%nauthor %an <%ae> %ad%ncommitter %cn <%ce> %cd%nencoding %e%n%n%s%n%n%b',hash))
call search('^parent ') keepjumps call search('^parent ')
if getline('.') ==# 'parent ' if getline('.') ==# 'parent '
silent delete_ silent keepjumps delete_
else else
silent s/\%(^parent\)\@<! /\rparent /ge silent keepjumps s/\%(^parent\)\@<! /\rparent /ge
endif endif
if search('^encoding \%(<unknown>\)\=$','W',line('.')+3) keepjumps let lnum = search('^encoding \%(<unknown>\)\=$','W',line('.')+3)
silent delete_ if lnum
silent keepjumps delete_
end end
1 keepjumps 1
endif endif
elseif b:fugitive_type ==# 'blob' elseif b:fugitive_type ==# 'blob'
call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash))
setlocal nomodeline
endif endif
finally finally
call setpos('.',pos) keepjumps call setpos('.',pos)
setlocal ro noma nomod setlocal ro noma nomod noswapfile
if &bufhidden ==# '' if &bufhidden ==# ''
setlocal bufhidden=delete setlocal bufhidden=delete
endif endif
@ -2331,9 +2349,6 @@ augroup END
function! s:JumpInit() abort function! s:JumpInit() abort
nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>GF("edit")<CR> nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>GF("edit")<CR>
if !&modifiable if !&modifiable
if exists(':CtrlP')
nnoremap <buffer> <silent> <C-P> :<C-U>exe 'CtrlP '.fnameescape(<SID>repo().tree())<CR>
endif
nnoremap <buffer> <silent> o :<C-U>exe <SID>GF("split")<CR> nnoremap <buffer> <silent> o :<C-U>exe <SID>GF("split")<CR>
nnoremap <buffer> <silent> S :<C-U>exe <SID>GF("vsplit")<CR> nnoremap <buffer> <silent> S :<C-U>exe <SID>GF("vsplit")<CR>
nnoremap <buffer> <silent> O :<C-U>exe <SID>GF("tabedit")<CR> nnoremap <buffer> <silent> O :<C-U>exe <SID>GF("tabedit")<CR>
@ -2522,12 +2537,15 @@ endfunction
" Statusline {{{1 " Statusline {{{1
function! s:repo_head_ref() dict abort function! s:repo_head_ref() dict abort
if !filereadable(self.dir('HEAD'))
return ''
endif
return readfile(self.dir('HEAD'))[0] return readfile(self.dir('HEAD'))[0]
endfunction endfunction
call s:add_methods('repo',['head_ref']) call s:add_methods('repo',['head_ref'])
function! fugitive#statusline(...) function! fugitive#statusline(...) abort
if !exists('b:git_dir') if !exists('b:git_dir')
return '' return ''
endif endif
@ -2543,7 +2561,7 @@ function! fugitive#statusline(...)
endif endif
endfunction endfunction
function! fugitive#head(...) function! fugitive#head(...) abort
if !exists('b:git_dir') if !exists('b:git_dir')
return '' return ''
endif endif

View file

@ -19,4 +19,32 @@ else
let b:undo_ftplugin = "setl cms< com< fo< flp<" let b:undo_ftplugin = "setl cms< com< fo< flp<"
endif endif
function! MarkdownFold()
let line = getline(v:lnum)
" Regular headers
let depth = match(line, '\(^#\+\)\@<=\( .*$\)\@=')
if depth > 0
return ">" . depth
endif
" Setext style headings
let nextline = getline(v:lnum + 1)
if (line =~ '^.\+$') && (nextline =~ '^=\+$')
return ">1"
endif
if (line =~ '^.\+$') && (nextline =~ '^-\+$')
return ">2"
endif
return "="
endfunction
if has("folding") && exists("g:markdown_folding")
setlocal foldexpr=MarkdownFold()
setlocal foldmethod=expr
let b:undo_ftplugin .= " foldexpr< foldmethod<"
endif
" vim:set sw=2: " vim:set sw=2:

View file

@ -9,6 +9,7 @@ Weber](marco-oweber@gmx.de), and [Adnan Zafar](https://github.com/ajzafar) with
additional contributions from: additional contributions from:
* [907th](https://github.com/907th) * [907th](https://github.com/907th)
* [adkron](https://github.com/adkron)
* [alderz](https://github.com/alderz) * [alderz](https://github.com/alderz)
* [asymmetric](https://github.com/asymmetric) * [asymmetric](https://github.com/asymmetric)
* [bpugh](https://github.com/bpugh) * [bpugh](https://github.com/bpugh)

View file

@ -44,6 +44,30 @@ looking at the [vim-snippets][vim-snippets] repository.
" Optional: " Optional:
Bundle "honza/vim-snippets" Bundle "honza/vim-snippets"
## FAQ ##
> How does SnipMate determine which snippets to load? How can I separate, for
> example, my Rails snippets from my Ruby snippets?
Primarily SnipMate looks at the `'filetype'` and `'syntax'` settings. Taking
"scopes" from these options, it looks in each `snippets/` directory in
`'runtimepath'` for files named `scope.snippets`, `scope/*.snippets`, or
`scope_*.snippets`.
However we understand this may not allow for the flexibility desired by some
languages. For this we provide two options: scope aliases and the
`:SnipMateLoadScope` command. Scope aliases simply say "whenever this scope is
loaded, also load this other scope:
let g:snipMate = {}
let g:snipMate.scope_aliases = {}
let g:snipMate.scope_aliases['ruby'] = 'ruby,rails'
will load the `ruby-rails` scope whenever the `ruby` scope is active. The
`:SnipMateLoadScope foo` command will always load the foo scope in the current
buffer. The [vim-rails](https://github.com/tpope/vim-rails) plugin automatically
does `:SnipMateLoadScope rails` when editing a Rails project for example.
## Release Notes ## ## Release Notes ##
### Master ### ### Master ###
@ -53,6 +77,10 @@ looking at the [vim-snippets][vim-snippets] repository.
* Fix bug with mirrors in the first column * Fix bug with mirrors in the first column
* Fix bug with tabs in indents ([#143][143]) * Fix bug with tabs in indents ([#143][143])
* Fix bug with mirrors in placeholders * Fix bug with mirrors in placeholders
* Fix reading single snippet files
* Fix the use of the visual map at the end of a line
* Add `:SnipMateLoadScope` command and buffer-local scope aliases
* Load `<scope>_*.snippets` files
### 0.87 - 2014-01-04 ### ### 0.87 - 2014-01-04 ###

View file

@ -2,7 +2,6 @@
if !exists('g:snipMate') if !exists('g:snipMate')
let g:snipMate = {} let g:snipMate = {}
endif endif
let s:c = g:snipMate
try try
call tlib#input#List('mi', '', []) call tlib#input#List('mi', '', [])
@ -13,26 +12,6 @@ endtry
" match $ which doesn't follow a \ " match $ which doesn't follow a \
let s:d = '\%([\\]\@<!\$\)' let s:d = '\%([\\]\@<!\$\)'
" if filetype is objc, cpp, cs or cu also append snippets from scope 'c'
" you can add multiple by separating scopes by ',', see s:AddScopeAliases
let s:c.scope_aliases = get(s:c, 'scope_aliases', {})
if !exists('g:snipMate_no_default_aliases') || !g:snipMate_no_default_aliases
let s:c.scope_aliases.objc = get(s:c.scope_aliases, 'objc', 'c')
let s:c.scope_aliases.cpp = get(s:c.scope_aliases, 'cpp', 'c')
let s:c.scope_aliases.cu = get(s:c.scope_aliases, 'cu', 'c')
let s:c.scope_aliases.xhtml = get(s:c.scope_aliases, 'xhtml', 'html')
let s:c.scope_aliases.html = get(s:c.scope_aliases, 'html', 'javascript')
let s:c.scope_aliases.php = get(s:c.scope_aliases, 'php', 'php,html,javascript')
let s:c.scope_aliases.ur = get(s:c.scope_aliases, 'ur', 'html,javascript')
let s:c.scope_aliases.mxml = get(s:c.scope_aliases, 'mxml', 'actionscript')
let s:c.scope_aliases.eruby = get(s:c.scope_aliases, 'eruby', 'eruby-rails,html')
endif
" set this to "\<tab>" to make snipmate not swallow tab (make sure to not have
" expandtab set). Remember that you can always enter tabs by <c-v> <tab> then
" you don't need this
let s:c['no_match_completion_feedkeys_chars'] = get(s:c, 'no_match_completion_feedkeys_chars', "\t")
fun! Filename(...) fun! Filename(...)
let filename = expand('%:t:r') let filename = expand('%:t:r')
if filename == '' | return a:0 == 2 ? a:2 : '' | endif if filename == '' | return a:0 == 2 ? a:2 : '' | endif
@ -85,11 +64,20 @@ fun! snipMate#expandSnip(snip, col)
if b:snip_state.stop_count if b:snip_state.stop_count
aug snipmate_changes aug snipmate_changes
au CursorMoved,CursorMovedI <buffer> call b:snip_state.update_changes() au CursorMoved,CursorMovedI <buffer> if exists('b:snip_state') |
\ call b:snip_state.update_changes() |
\ else |
\ silent! au! snipmate_changes * <buffer> |
\ endif
aug END aug END
call b:snip_state.set_stop(0) call b:snip_state.set_stop(0)
let ret = b:snip_state.select_word()
return b:snip_state.select_word() if b:snip_state.stop_count == 1
call b:snip_state.remove()
endif
return ret
else else
unlet b:snip_state unlet b:snip_state
" Place cursor at end of snippet if no tab stop is given " Place cursor at end of snippet if no tab stop is given
@ -426,12 +414,26 @@ fun! snipMate#ReadSnippetsFile(file)
return [result, new_scopes] return [result, new_scopes]
endf endf
function! s:GetScopes()
let ret = exists('b:snipMate_scope_aliases') ? copy(b:snipMate.scope_aliases) : {}
let global = get(g:snipMate, 'scope_aliases', {})
for alias in keys(global)
if has_key(ret, alias)
let ret[alias] = join(split(ret[alias], ',')
\ + split(global[alias], ','), ',')
else
let ret[alias] = global[alias]
endif
endfor
return ret
endfunction
" adds scope aliases to list. " adds scope aliases to list.
" returns new list " returns new list
" the aliases of aliases are added recursively " the aliases of aliases are added recursively
fun! s:AddScopeAliases(list) fun! s:AddScopeAliases(list)
let did = {} let did = {}
let scope_aliases = get(s:c,'scope_aliases', {}) let scope_aliases = s:GetScopes()
let new = a:list let new = a:list
let new2 = [] let new2 = []
while !empty(new) while !empty(new)
@ -447,16 +449,22 @@ fun! s:AddScopeAliases(list)
return keys(did) return keys(did)
endf endf
function! s:Glob(path, expr) if v:version >= 704
function! s:Glob(path, expr)
return split(globpath(a:path, a:expr), "\n")
endfunction
else
function! s:Glob(path, expr)
let res = [] let res = []
for p in split(a:path, ',') for p in split(a:path, ',')
let h = fnamemodify(a:expr, ':h') let h = split(fnamemodify(a:expr, ':h'), '/')[0]
if isdirectory(p . '/' . h) if isdirectory(p . '/' . h)
call extend(res, split(glob(p . '/' . a:expr), "\n")) call extend(res, split(glob(p . '/' . a:expr), "\n"))
endif endif
endfor endfor
return filter(res, 'filereadable(v:val)') return filter(res, 'filereadable(v:val)')
endfunction endfunction
endif
" returns dict of " returns dict of
" { path: { 'type': one of 'snippet' 'snippets', " { path: { 'type': one of 'snippet' 'snippets',
@ -466,12 +474,11 @@ endfunction
" 'trigger': trigger of snippet " 'trigger': trigger of snippet
" } " }
" } " }
" use trigger = '*' to match all snippet files
" use mustExist = 1 to return existing files only " use mustExist = 1 to return existing files only
" "
" mustExist = 0 is used by OpenSnippetFiles " mustExist = 0 is used by OpenSnippetFiles
function! snipMate#GetSnippetFiles(mustExist, scopes, trigger) function! snipMate#GetSnippetFiles(mustExist, scopes, trigger)
let paths = join(funcref#Call(s:c.snippet_dirs), ',') let paths = join(funcref#Call(g:snipMate.snippet_dirs), ',')
let result = {} let result = {}
let scopes = s:AddScopeAliases(a:scopes) let scopes = s:AddScopeAliases(a:scopes)
let trigger = escape(a:trigger, "*[]?{}`'$") let trigger = escape(a:trigger, "*[]?{}`'$")
@ -480,19 +487,22 @@ function! snipMate#GetSnippetFiles(mustExist, scopes, trigger)
for scope in scopes for scope in scopes
for f in s:Glob(paths, 'snippets/' . scope . '.snippets') + for f in s:Glob(paths, 'snippets/' . scope . '.snippets') +
\ s:Glob(paths, 'snippets/' . scope . '_*.snippets') +
\ s:Glob(paths, 'snippets/' . scope . '/*.snippets') \ s:Glob(paths, 'snippets/' . scope . '/*.snippets')
let result[f] = { 'exists' : 1, 'type' : 'snippets', let result[f] = { 'exists' : 1, 'type' : 'snippets',
\ 'name_prefix' : fnamemodify(f, ':t:r') } \ 'name_prefix' : fnamemodify(f, ':t:r') }
endfor endfor
for f in s:Glob(paths, 'snippets/'.scope.'/'.trigger.'.snippet') " We check for trigger* in the next two loops. In the case of an exact
" match, that'll be handled in snipMate#GetSnippetsForWordBelowCursor.
for f in s:Glob(paths, 'snippets/' . scope . '/' . trigger . '*.snippet')
let result[f] = {'exists': 1, 'type': 'snippet', 'name': 'default', let result[f] = {'exists': 1, 'type': 'snippet', 'name': 'default',
\ 'trigger': a:trigger, 'name_prefix' : scope } \ 'trigger': fnamemodify(f, ':t:r'), 'name_prefix' : scope }
endfor endfor
for f in s:Glob(paths, 'snippets/'.scope.'/'.trigger.'/*.snippet') for f in s:Glob(paths, 'snippets/' . scope . '/' . trigger . '*/*.snippet')
let result[f] = {'exists': 1, 'type': 'snippet', 'name' : fnamemodify(f, ':t:r'), let result[f] = {'exists': 1, 'type': 'snippet', 'name' : fnamemodify(f, ':t:r'),
\ 'trigger': a:trigger, 'name_prefix' : scope } \ 'trigger': fnamemodify(f, ':h:t'), 'name_prefix' : scope }
endfor endfor
if !a:mustExist if !a:mustExist
@ -507,21 +517,12 @@ function! snipMate#GetSnippetFiles(mustExist, scopes, trigger)
endfunction endfunction
" should be moved to utils or such? " should be moved to utils or such?
function! snipMate#SetByPath(dict, path, value) function! snipMate#SetByPath(dict, trigger, path, snippet)
let d = a:dict let d = a:dict
for p in a:path[:-2] if !has_key(d, a:trigger)
if !has_key(d,p) | let d[p] = {} | endif let d[a:trigger] = {}
let d = d[p]
endfor
let d[a:path[-1]] = a:value
endfunction
function! s:ReadFile(file)
if a:file =~ '\.snippet$'
return [['', '', readfile(a:file), '1']]
else
return snipMate#ReadSnippetsFile(a:file)
endif endif
let d[a:trigger][a:path] = a:snippet
endfunction endfunction
function! s:CachedSnips(file) function! s:CachedSnips(file)
@ -545,13 +546,13 @@ function! snipMate#DefaultPool(scopes, trigger, result)
call extend(extra_scopes, new_scopes) call extend(extra_scopes, new_scopes)
for [trigger, name, contents] in snippets for [trigger, name, contents] in snippets
if trigger =~ '\V\^' . escape(a:trigger, '\') if trigger =~ '\V\^' . escape(a:trigger, '\')
call snipMate#SetByPath(a:result, call snipMate#SetByPath(a:result, trigger,
\ [trigger, opts.name_prefix . ' ' . name], \ opts.name_prefix . ' ' . name, contents)
\ contents)
endif endif
endfor endfor
elseif opts.type == 'snippet' elseif opts.type == 'snippet'
call snipMate#SetByPath(a:result, [opts.trigger, opts.name_prefix.' '.opts.name], readfile(f)) call snipMate#SetByPath(a:result, opts.trigger,
\ opts.name_prefix . ' ' . opts.name, readfile(f))
else else
throw "unexpected" throw "unexpected"
endif endif
@ -636,7 +637,7 @@ endf
fun! snipMate#ScopesByFile() fun! snipMate#ScopesByFile()
" duplicates are removed in AddScopeAliases " duplicates are removed in AddScopeAliases
return filter(funcref#Call(s:c.get_scopes), "v:val != ''") return filter(funcref#Call(g:snipMate.get_scopes), "v:val != ''")
endf endf
" used by both: completion and insert snippet " used by both: completion and insert snippet
@ -669,8 +670,8 @@ fun! snipMate#GetSnippetsForWordBelowCursor(word, exact)
let snippet = '' let snippet = ''
" prefer longest word " prefer longest word
for word in lookups for word in lookups
let s:c.word = word let g:snipMate.word = word
for [k,snippetD] in items(funcref#Call(s:c['get_snippets'], [snipMate#ScopesByFile(), word])) for [k,snippetD] in items(funcref#Call(g:snipMate['get_snippets'], [snipMate#ScopesByFile(), word]))
" hack: require exact match " hack: require exact match
if a:exact && k !=# word if a:exact && k !=# word
continue continue
@ -730,7 +731,7 @@ fun! snipMate#ShowAvailableSnips()
" Pretty hacky, but really can't have the tab swallowed! " Pretty hacky, but really can't have the tab swallowed!
if len(matches) == 0 if len(matches) == 0
call feedkeys(s:c['no_match_completion_feedkeys_chars'], 'n') call feedkeys(g:snipMate['no_match_completion_feedkeys_chars'], 'n')
return "" return ""
endif endif

View file

@ -74,6 +74,14 @@ Commands~
files will be shown, with the existing files files will be shown, with the existing files
shown first. shown first.
:SnipMateLoadScope[!] scope [scope ...]
Load snippets from additional scopes. Without
[!] the additional scopes are loaded only in
the current buffer. For example >
:SnipMateLoadScopes rails
< will load all rails.snippets in the current
buffer.
*SnipMate-options* *SnipMate-options*
Options~ Options~
@ -103,7 +111,9 @@ g:snipMate.scope_aliases A |Dictionary| associating certain filetypes
addition to "ruby" snippets should be loaded addition to "ruby" snippets should be loaded
when editing files with 'filetype' set to when editing files with 'filetype' set to
"ruby" or contains "ruby" as an entry in the "ruby" or contains "ruby" as an entry in the
case of dotted filetypes. case of dotted filetypes. A buffer local
variant b:snipMate_scope_aliases is merged
with the global variant.
g:snipMate_no_default_aliases g:snipMate_no_default_aliases
When set to 1, prevents SnipMate from loading When set to 1, prevents SnipMate from loading
@ -178,6 +188,7 @@ settings (taking into account the dotted syntax), the following files are read
for snippets: > for snippets: >
.../snippets/<scope>.snippets .../snippets/<scope>.snippets
.../snippets/<scope>_<name>.snippets
.../snippets/<scope>/<name>.snippets .../snippets/<scope>/<name>.snippets
.../snippets/<scope>/<trigger>.snippet .../snippets/<scope>/<trigger>.snippet
.../snippets/<scope>/<trigger>/<description>.snippet .../snippets/<scope>/<trigger>/<description>.snippet

View file

@ -11,8 +11,8 @@ if exists('loaded_snips') || &cp || version < 700
finish finish
endif endif
let loaded_snips = 1 let loaded_snips = 1
if !exists('snips_author') | let snips_author = 'Me' | endif
" save and reset 'cpo' " Save and reset 'cpo'
let s:save_cpo = &cpo let s:save_cpo = &cpo
set cpo&vim set cpo&vim
@ -24,7 +24,7 @@ endtry
if (!exists('g:snipMateSources')) if (!exists('g:snipMateSources'))
let g:snipMateSources = {} let g:snipMateSources = {}
" default source: get snippets based on runtimepath: " Default source: get snippets based on runtimepath
let g:snipMateSources['default'] = funcref#Function('snipMate#DefaultPool') let g:snipMateSources['default'] = funcref#Function('snipMate#DefaultPool')
endif endif
@ -40,52 +40,73 @@ inoremap <silent> <Plug>snipMateTrigger <C-R>=snipMate#TriggerSnippet(1)<
inoremap <silent> <Plug>snipMateBack <C-R>=snipMate#BackwardsSnippet()<CR> inoremap <silent> <Plug>snipMateBack <C-R>=snipMate#BackwardsSnippet()<CR>
snoremap <silent> <Plug>snipMateBack <Esc>a<C-R>=snipMate#BackwardsSnippet()<CR> snoremap <silent> <Plug>snipMateBack <Esc>a<C-R>=snipMate#BackwardsSnippet()<CR>
inoremap <silent> <Plug>snipMateShow <C-R>=snipMate#ShowAvailableSnips()<CR> inoremap <silent> <Plug>snipMateShow <C-R>=snipMate#ShowAvailableSnips()<CR>
xnoremap <silent> <Plug>snipMateVisual :<C-U>call <SID>grab_visual()<CR>i xnoremap <silent> <Plug>snipMateVisual :<C-U>call <SID>grab_visual()<CR>gv"_c
" config which can be overridden (shared lines) " config variables
if !exists('g:snips_author')
let g:snips_author = 'Me'
endif
if !exists('g:snipMate') if !exists('g:snipMate')
let g:snipMate = {} let g:snipMate = {}
endif endif
let s:snipMate = g:snipMate
let s:snipMate['get_snippets'] = get(s:snipMate, 'get_snippets', funcref#Function("snipMate#GetSnippets")) " SnipMate inserts this string when no snippet expansion can be done
let g:snipMate['no_match_completion_feedkeys_chars'] =
\ get(g:snipMate, 'no_match_completion_feedkeys_chars', "\t")
" old snippets_dir: function returning list of paths which is used to read " Add default scope aliases, without overriding user settings
" snippets. You can replace it with your own implementation. Defaults to all let g:snipMate.scope_aliases = get(g:snipMate, 'scope_aliases', {})
" directories in &rtp/snippets/* if !exists('g:snipMate_no_default_aliases') || !g:snipMate_no_default_aliases
let s:snipMate['snippet_dirs'] = get(s:snipMate, 'snippet_dirs', funcref#Function('return split(&runtimepath,",")')) let g:snipMate.scope_aliases.objc = get(g:snipMate.scope_aliases, 'objc', 'c')
if type(s:snipMate['snippet_dirs']) == type([]) let g:snipMate.scope_aliases.cpp = get(g:snipMate.scope_aliases, 'cpp', 'c')
call map(s:snipMate['snippet_dirs'], 'expand(v:val)') let g:snipMate.scope_aliases.cu = get(g:snipMate.scope_aliases, 'cu', 'c')
let g:snipMate.scope_aliases.xhtml = get(g:snipMate.scope_aliases, 'xhtml', 'html')
let g:snipMate.scope_aliases.html = get(g:snipMate.scope_aliases, 'html', 'javascript')
let g:snipMate.scope_aliases.php = get(g:snipMate.scope_aliases, 'php', 'php,html,javascript')
let g:snipMate.scope_aliases.ur = get(g:snipMate.scope_aliases, 'ur', 'html,javascript')
let g:snipMate.scope_aliases.mxml = get(g:snipMate.scope_aliases, 'mxml', 'actionscript')
let g:snipMate.scope_aliases.eruby = get(g:snipMate.scope_aliases, 'eruby', 'eruby-rails,html')
endif
let g:snipMate['get_snippets'] = get(g:snipMate, 'get_snippets', funcref#Function("snipMate#GetSnippets"))
" List of paths where snippets/ dirs are located, or a function returning such
" a list
let g:snipMate['snippet_dirs'] = get(g:snipMate, 'snippet_dirs', funcref#Function('return split(&runtimepath,",")'))
if type(g:snipMate['snippet_dirs']) == type([])
call map(g:snipMate['snippet_dirs'], 'expand(v:val)')
endif endif
" _ is default scope added always " _ is default scope added always
" "
" &ft honors multiple filetypes and syntax such as in set ft=html.javascript syntax=FOO " &ft honors multiple filetypes and syntax such as in set ft=html.javascript syntax=FOO
let s:snipMate['get_scopes'] = get(s:snipMate, 'get_scopes', funcref#Function('return split(&ft,"\\.")+[&syntax, "_"]')) let g:snipMate['get_scopes'] = get(g:snipMate, 'get_scopes', funcref#Function('return split(&ft,"\\.")+[&syntax, "_"]'))
" dummy for compatibility - will be removed
" moving to autoload to improve loading speed and debugging
fun! TriggerSnippet()
echoe "replace TriggerSnippet by snipMate#TriggerSnippet, please!"
return snipMate#TriggerSnippet()
endf
fun! BackwardSnippet()
echoe "replace BackwardSnippet by snipMate#BackwardsSnippet, please!"
return snipMate#BackwardsSnippet()
endf
" Modified from Luc Hermitte's function on StackOverflow " Modified from Luc Hermitte's function on StackOverflow
" <http://stackoverflow.com/a/1534347> " <http://stackoverflow.com/a/1534347>
function! s:grab_visual() function! s:grab_visual()
let a_save = @a let a_save = @a
try try
normal! gv"ad normal! gv"ay
let b:snipmate_content_visual = @a let b:snipmate_content_visual = @a
finally finally
let @a = a_save let @a = a_save
endtry endtry
endfunction endfunction
function! s:load_scopes(bang, ...)
let gb = a:bang ? g: : b:
let gb.snipMate = get(gb, 'snipMate', {})
let gb.snipMate.scope_aliases = get(gb.snipMate, 'scope_aliases', {})
let gb.snipMate.scope_aliases['_'] = join(split(get(gb.snipMate.scope_aliases, '_', ''), ',') + a:000, ',')
endfunction
command! -bang -bar -nargs=+ SnipMateLoadScopes
\ call s:load_scopes(<bang>0, <f-args>)
" Edit snippet files
command! SnipMateOpenSnippetFiles call snipMate#OpenSnippetFiles()
" restore 'cpo' " restore 'cpo'
let &cpo = s:save_cpo let &cpo = s:save_cpo

View file

@ -1,2 +0,0 @@
" some useful commands
command! SnipMateOpenSnippetFiles call snipMate#OpenSnippetFiles()

View file

@ -194,7 +194,7 @@ endsnippet
snippet head "XHTML <head>" snippet head "XHTML <head>"
<head> <head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"`!p x(snip)`> <meta charset="utf-8">
<title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title> <title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title>
$0 $0
</head> </head>

View file

@ -25,8 +25,13 @@ def getArgs(group):
return [i.split(" ") for i in word.findall(group) ] return [i.split(" ") for i in word.findall(group) ]
def camel(word): def camel(word):
if not word: return ''
return word[0].upper() + word[1:] return word[0].upper() + word[1:]
def mixedCase(word):
if not word: return ''
return word[0].lower() + word[1:]
endglobal endglobal
snippet sleep "try sleep catch" b snippet sleep "try sleep catch" b
@ -173,13 +178,13 @@ default:
$0 $0
endsnippet endsnippet
snippet elif "else if" b snippet elif "else if"
else if ($1)`!p nl(snip)`{ else if ($1)`!p nl(snip)`{
$0 $0
} }
endsnippet endsnippet
snippet /el(se)?/ "else" br snippet /el(se)?/ "else" r
else`!p nl(snip)`{ else`!p nl(snip)`{
$0 $0
} }
@ -338,23 +343,23 @@ endsnippet
snippet /get(ter)?/ "getter" br snippet /get(ter)?/ "getter" br
public ${1:String} get${2:Name}() { public ${1:String} get${2:Name}() {
return `!p snip.rv = t[2].lower()`; return `!p snip.rv = mixedCase(t[2])`;
} }
endsnippet endsnippet
snippet /set(ter)?/ "setter" br snippet /set(ter)?/ "setter" br
public void set${1:Name}(${2:String} $1) { public void set${1:Name}(${2:String} `!p snip.rv = mixedCase(t[1])`) {
return this.`!p snip.rv = t[1].lower()` = `!p snip.rv = t[1].lower()`; this.`!p snip.rv = mixedCase(t[1])` = `!p snip.rv = mixedCase(t[1])`;
} }
endsnippet endsnippet
snippet /se?tge?t|ge?tse?t|gs/ "setter and getter" br snippet /se?tge?t|ge?tse?t|gs/ "setter and getter" br
public void set${1:Name}(${2:String} `!p snip.rv = t[1].lower()`) { public void set${1:Name}(${2:String} `!p snip.rv = mixedCase(t[1])`) {
this.`!p snip.rv = t[1].lower()` = `!p snip.rv = t[1].lower()`; this.`!p snip.rv = mixedCase(t[1])` = `!p snip.rv = mixedCase(t[1])`;
} }
public $2 get$1() { public $2 get$1() {
return `!p snip.rv = t[1].lower()`; return `!p snip.rv = mixedCase(t[1])`;
} }
endsnippet endsnippet

View file

@ -120,19 +120,19 @@ endsnippet
snippet gs "PHP Class Getter Setter" b snippet gs "PHP Class Getter Setter" b
/* /*
* Getter for ${1/(\w+)\s*;/$1/} * Getter for $1
*/ */
public function get${1/(\w+)\s*;/\u$1/}() public function get${1/\w+\s*/\u$0/}()
{ {
return $this->${1/(\w+)\s*;/$1/};$2 return $this->$1;$2
} }
/* /*
* Setter for ${1/(\w+)\s*;/$1/} * Setter for $1
*/ */
public function set${1/(\w+)\s*;/\u$1/}($${1/(\w+)\s*;/$1/}) public function set${1/\w+\s*/\u$0/}($$1)
{ {
$this->${1/(\w+)\s*;/$1/} = $${1/(\w+)\s*;/$1/};$3 $this->$1 = $$1;$3
${4:return $this;} ${4:return $this;}
} }
$0 $0

View file

@ -0,0 +1,52 @@
priority -50
global !p
from vimsnippets import complete
FIELD_TYPES = [
'double',
'float',
'int32',
'int64',
'uint32',
'uint64',
'sint32',
'sint64',
'fixed32',
'fixed64',
'sfixed32',
'sfixed64',
'bool',
'string',
'bytes']
endglobal
snippet mess "Proto message" b
// ${2:TODO(`whoami`): Describe this message.}
message ${1:Name} {
$0
// Next available id: 1
}
endsnippet
snippet reqf "Required field" b
// ${4:TODO(`whoami`): Describe this field.}
optional ${1}`!p snip.rv = complete(t[1], FIELD_TYPES)` ${2:name} = ${3:1}; // Required
endsnippet
snippet optf "Optional field" b
// ${4:TODO(`whoami`): Describe this field.}
optional ${1}`!p snip.rv = complete(t[1], FIELD_TYPES)` ${2:name} = ${3:1};
endsnippet
snippet repf "Repeated field" b
// ${4:TODO(`whoami`): Describe this field.}
repeated ${1}`!p snip.rv = complete(t[1], FIELD_TYPES)` ${2:name} = ${3:1};
endsnippet
snippet enum "Enumeration" b
// ${2:TODO(`whoami`): Describe this enum.}
enum ${1:Name} {
}
endsnippet

View file

@ -34,13 +34,30 @@ global !p
NORMAL = 0x1 NORMAL = 0x1
DOXYGEN = 0x2 DOXYGEN = 0x2
SPHINX = 0x3 SPHINX = 0x3
GOOGLE = 0x4
SINGLE_QUOTES = 0x1 SINGLE_QUOTES = 0x1
DOUBLE_QUOTES = 0x2 DOUBLE_QUOTES = 0x2
class Arg(object):
def __init__(self, arg):
self.arg = arg
self.name = arg.split('=')[0].strip()
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def is_kwarg(self):
return '=' in self.arg
def get_args(arglist): def get_args(arglist):
args = [arg.split('=')[0].strip() for arg in arglist.split(',') if arg] args = [Arg(arg) for arg in arglist.split(',') if arg]
args = [arg for arg in args if arg and arg != "self"] args = [arg for arg in args if arg.name != 'self']
return args return args
@ -51,7 +68,7 @@ def get_quoting_style(snip):
return SINGLE_QUOTES return SINGLE_QUOTES
return DOUBLE_QUOTES return DOUBLE_QUOTES
def tripple_quotes(snip): def triple_quotes(snip):
if get_quoting_style(snip) == SINGLE_QUOTES: if get_quoting_style(snip) == SINGLE_QUOTES:
return "'''" return "'''"
return '"""' return '"""'
@ -61,6 +78,7 @@ def get_style(snip):
if style == "doxygen": return DOXYGEN if style == "doxygen": return DOXYGEN
elif style == "sphinx": return SPHINX elif style == "sphinx": return SPHINX
elif style == "google": return GOOGLE
else: return NORMAL else: return NORMAL
@ -71,6 +89,8 @@ def format_arg(arg, style):
return ":param %s: @todo" % arg return ":param %s: @todo" % arg
elif style == NORMAL: elif style == NORMAL:
return ":%s: @todo" % arg return ":%s: @todo" % arg
elif style == GOOGLE:
return "%s (@todo): @todo" % arg
def format_return(style): def format_return(style):
@ -78,21 +98,47 @@ def format_return(style):
return "@return: @todo" return "@return: @todo"
elif style in (NORMAL, SPHINX): elif style in (NORMAL, SPHINX):
return ":returns: @todo" return ":returns: @todo"
elif style == GOOGLE:
return "Returns: @todo"
def write_docstring_args(args, snip): def write_docstring_args(args, snip):
if not args: if not args:
snip.rv += ' {0}'.format(tripple_quotes(snip)) snip.rv += ' {0}'.format(triple_quotes(snip))
return return
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
style = get_style(snip) style = get_style(snip)
if style == GOOGLE:
write_google_docstring_args(args, snip)
else:
for arg in args: for arg in args:
snip += format_arg(arg, style) snip += format_arg(arg, style)
def write_google_docstring_args(args, snip):
kwargs = [arg for arg in args if arg.is_kwarg()]
args = [arg for arg in args if not arg.is_kwarg()]
if args:
snip += "Args:"
snip.shift()
for arg in args:
snip += format_arg(arg, GOOGLE)
snip.unshift()
snip.rv += '\n' + snip.mkline('', indent='')
if kwargs:
snip += "Kwargs:"
snip.shift()
for kwarg in kwargs:
snip += format_arg(kwarg, GOOGLE)
snip.unshift()
snip.rv += '\n' + snip.mkline('', indent='')
def write_init_body(args, parents, snip): def write_init_body(args, parents, snip):
parents = [p.strip() for p in parents.split(",")] parents = [p.strip() for p in parents.split(",")]
parents = [p for p in parents if p != 'object'] parents = [p for p in parents if p != 'object']
@ -120,10 +166,10 @@ endglobal
snippet class "class with docstrings" b snippet class "class with docstrings" b
class ${1:MyClass}(${2:object}): class ${1:MyClass}(${2:object}):
`!p snip.rv = tripple_quotes(snip)`${3:Docstring for $1. }`!p snip.rv = tripple_quotes(snip)` `!p snip.rv = triple_quotes(snip)`${3:Docstring for $1. }`!p snip.rv = triple_quotes(snip)`
def __init__(self$4): def __init__(self$4):
`!p snip.rv = tripple_quotes(snip)`${5:@todo: to be defined1.}`!p `!p snip.rv = triple_quotes(snip)`${5:@todo: to be defined1.}`!p
snip.rv = "" snip.rv = ""
snip >> 2 snip >> 2
@ -132,7 +178,7 @@ args = get_args(t[4])
write_docstring_args(args, snip) write_docstring_args(args, snip)
if args: if args:
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
snip += '{0}'.format(tripple_quotes(snip)) snip += '{0}'.format(triple_quotes(snip))
write_init_body(args, t[2], snip) write_init_body(args, t[2], snip)
` `
@ -143,7 +189,7 @@ endsnippet
snippet slotclass "class with slots and docstrings" b snippet slotclass "class with slots and docstrings" b
class ${1:MyClass}(${2:object}): class ${1:MyClass}(${2:object}):
`!p snip.rv = tripple_quotes(snip)`${3:Docstring for $1. }`!p snip.rv = tripple_quotes(snip)` `!p snip.rv = triple_quotes(snip)`${3:Docstring for $1. }`!p snip.rv = triple_quotes(snip)`
`!p `!p
snip >> 1 snip >> 1
args = get_args(t[4]) args = get_args(t[4])
@ -151,7 +197,7 @@ write_slots_args(args, snip)
` `
def __init__(self$4): def __init__(self$4):
`!p snip.rv = tripple_quotes(snip)`${5:@todo: to be defined.}`!p `!p snip.rv = triple_quotes(snip)`${5:@todo: to be defined.}`!p
snip.rv = "" snip.rv = ""
snip >> 2 snip >> 2
@ -160,7 +206,7 @@ args = get_args(t[4])
write_docstring_args(args, snip) write_docstring_args(args, snip)
if args: if args:
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
snip += tripple_quotes(snip) snip += triple_quotes(snip)
write_init_body(args, t[2], snip) write_init_body(args, t[2], snip)
` `
@ -353,7 +399,7 @@ snippet def "function with docstrings" b
def ${1:function}(`!p def ${1:function}(`!p
if snip.indent: if snip.indent:
snip.rv = 'self' + (", " if len(t[2]) else "")`${2:arg1}): snip.rv = 'self' + (", " if len(t[2]) else "")`${2:arg1}):
`!p snip.rv = tripple_quotes(snip)`${4:@todo: Docstring for $1.}`!p `!p snip.rv = triple_quotes(snip)`${4:@todo: Docstring for $1.}`!p
snip.rv = "" snip.rv = ""
snip >> 1 snip >> 1
@ -364,7 +410,7 @@ if args:
style = get_style(snip) style = get_style(snip)
snip += format_return(style) snip += format_return(style)
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
snip += tripple_quotes(snip) ` snip += triple_quotes(snip) `
${0:pass} ${0:pass}
endsnippet endsnippet
@ -390,7 +436,7 @@ endsnippet
snippet rwprop "Read write property" b snippet rwprop "Read write property" b
def ${1:name}(): def ${1:name}():
`!p snip.rv = tripple_quotes(snip) if t[2] else '' `!p snip.rv = triple_quotes(snip) if t[2] else ''
`${2:@todo: Docstring for $1.}`!p `${2:@todo: Docstring for $1.}`!p
if t[2]: if t[2]:
snip >> 1 snip >> 1
@ -399,7 +445,7 @@ if t[2]:
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
snip += format_return(style) snip += format_return(style)
snip.rv += '\n' + snip.mkline('', indent='') snip.rv += '\n' + snip.mkline('', indent='')
snip += tripple_quotes(snip) snip += triple_quotes(snip)
else: else:
snip.rv = ""` snip.rv = ""`
def fget(self): def fget(self):
@ -518,7 +564,7 @@ endsnippet
snippet testcase "pyunit testcase" b snippet testcase "pyunit testcase" b
class Test${1:Class}(${2:unittest.TestCase}): class Test${1:Class}(${2:unittest.TestCase}):
`!p snip.rv = tripple_quotes(snip)`${3:Test case docstring.}`!p snip.rv = tripple_quotes(snip)` `!p snip.rv = triple_quotes(snip)`${3:Test case docstring.}`!p snip.rv = triple_quotes(snip)`
def setUp(self): def setUp(self):
${4:pass} ${4:pass}

View file

@ -0,0 +1,144 @@
priority -50
snippet #! "Hashbang for Rscript (#!)" b
#!/usr/bin/env Rscript
endsnippet
snippet lib "Import a library"
library(${0:package})
endsnippet
snippet req "Require a file"
require(${0:package})
endsnippet
snippet source "Source a file"
source('${0:file}')
endsnippet
snippet if "If statement"
if (${1}) {
${0}
}
endsnippet
snippet eif "Else-If statement"
else if (${1}) {
${0}
}
snippet el "Else statement"
else {
${0}
}
endsnippet
snippet ife "if .. else"
if (${1}) {
${2}
} else {
${3}
}
endsnippet
snippet wh "while loop"
while(${1}) {
${2}
}
endsnippet
snippet for "for loop"
for ({${1:item} in ${2:list}) {
${3}
}
endsnippet
snippet fun "Function definition"
${1:name} <- function (${2}) {
${0}
}
endsnippet
snippet ret "Return call"
return(${0})
endsnippet
snippet df "Data frame"
${1:name}[${2:rows}, ${0:cols}]
endsnippet
snippet c "c function"
c(${0:items})
endsnippet
snippet li "list function"
list(${0:items})
endsnippet
snippet mat "matrix function"
matrix(${1:data}, nrow = ${2:rows}, ncol = ${0:cols})
endsnippet
snippet apply "apply function"
apply(${1:array}, ${2:margin}, ${0:function})
endsnippet
snippet lapply "lapply function"
lapply(${1:list}, ${0:function})
endsnippet
snippet sapply "sapply function"
lapply(${1:list}, ${0:function})
endsnippet
snippet vapply "vapply function"
vapply(${1:list}, ${2:function}, ${0:type})
endsnippet
snippet mapply "mapply function"
mapply(${1:function}, ${0:...})
endsnippet
snippet tapply "tapply function"
tapply(${1:vector}, ${2:index}, ${0:function})
endsnippet
snippet rapply "rapply function"
rapply(${1:list}, ${0:function})
endsnippet
snippet pl "Plot function"
plot(${1:x}, ${0:y})
endsnippet
snippet ggp "ggplot2 plot"
ggplot(${1:data}, aes(${0:aesthetics}))
endsnippet
snippet fis "Fisher test"
fisher.test(${1:x}, ${0:y})
endsnippet
snippet chi "Chi Squared test"
chisq.test(${1:x}, ${0:y})
endsnippet
snippet tt "t-test"
t.test(${1:x}, ${0:y})
endsnippet
snippet wil "Wilcox test"
wilcox.test(${1:x}, ${0:y})
endsnippet
snippet cor "Correlation test"
cor.test(${1:x}, ${0:y})
endsnippet
snippet fte "FTE test"
var.test(${1:x}, ${0:y})
endsnippet
snippet kvt "KV test"
kv.test(${1:x}, ${0:y})
endsnippet

View file

@ -0,0 +1,3 @@
priority -50
extends tex, r

View file

@ -12,6 +12,8 @@ from string import Template
import re import re
from collections import Counter from collections import Counter
from vimsnippets import complete
#http://docutils.sourceforge.net/docs/ref/rst/roles.html #http://docutils.sourceforge.net/docs/ref/rst/roles.html
TEXT_ROLES = ['emphasis','literal','code','math', TEXT_ROLES = ['emphasis','literal','code','math',
'pep-reference','rfc-reference', 'pep-reference','rfc-reference',
@ -130,27 +132,6 @@ def get_popular_code_type():
except IndexError: except IndexError:
popular_type = "lua" # Don't break default popular_type = "lua" # Don't break default
return popular_type return popular_type
def complete(t, opts):
"""
get options that start with t
:param t: query string
:param opts: list that needs to be completed
:return: a string that start with t
"""
msg = "({0})"
if t:
opts = [ m[len(t):] for m in opts if m.startswith(t) ]
if len(opts) == 1:
return opts[0]
if not len(opts):
msg = "{0}"
return msg.format("|".join(opts))
endglobal endglobal
snippet part "Part" b snippet part "Part" b

View file

@ -0,0 +1,215 @@
#######################################################################
# Rust Snippets #
#######################################################################
###############
# Functions #
###############
snippet fn "A function, optionally with arguments and return type."
fn ${1:function_name}(${2})${3/..*/ -> /}${3} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet test "Test function"
#[test]
fn ${1:test_function_name}() {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet new "A new function"
pub fn new(${2}) -> ${1:Name} {
${VISUAL}${0}return $1 { ${3} };
}
endsnippet
snippet main "The main function"
pub fn main() {
${VISUAL}${0}
}
endsnippet
snippet let "A let statement"
let ${1:name}${3} = ${VISUAL}${2};
endsnippet
snippet pln "println!(..)" b
println!("${1}"${2/..*/, /}${2});
endsnippet
snippet ec "extern crate ..." b
extern crate ${1:sync};
endsnippet
snippet ecl "...extern crate log;" b
#![feature(phase)]
#[phase(syntax, link)] extern crate log;
endsnippet
snippet mod "A mod." b
mod ${1:`!p snip.rv = snip.basename.lower() or "name"`} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
} /* $1 */
endsnippet
snippet crate "Create header information" b
// Crate ID
#![crate_id = "${1:crate_name}#${2:0.0.1}"]
// Additional metadata attributes
#![desc = "${3:Descrption.}"]
#![license = "${4:BSD}"]
#![comment = "${5:Comment.}"]
// Specify the output type
#![crate_type = "${6:lib}"]
endsnippet
snippet allow "#[allow(..)]" b
#[allow(${1:unused_variable})]
endsnippet
snippet feat "#![feature(..)]" b
#![feature(${1:macro_rules})]
endsnippet
##################
# Common types #
##################
snippet opt "Option<..>"
Option<${1:int}>
endsnippet
snippet res "Result<.., ..>"
Result<${1:~str}, ${2:()}>
endsnippet
snippet if "if .. (if)" b
if ${1:/* condition */} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet mat "match"
match ${1} {
${2} => ${3},
}
endsnippet
snippet while "while .. {}" b
while ${1:condition} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet for "for .. in .." b
for ${1:i} in ${2:range(0u, 10)} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet spawn "spawn(proc() { .. });" b
spawn(proc() {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
});
endsnippet
snippet chan "A channel" b
let (${1:tx}, ${2:rx}): (Sender<${3:int}>, Receiver<${4:int}>) = channel();
endsnippet
snippet duplex "Duplex stream" b
let (${1:from_child}, ${2:to_child}) = sync::duplex();
endsnippet
#####################
# TODO commenting #
#####################
snippet todo "A Todo comment"
// [TODO]: ${1:Description} - `!v strftime("%Y-%m-%d %I:%M%P")`
endsnippet
############
# Struct #
############
snippet st "Struct" b
struct ${1:`!p snip.rv = snip.basename.title() or "name"`} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet stn "Struct with new constructor." b
pub struct ${1:`!p snip.rv = snip.basename.title() or "name"`} {
${3:/* code */}
}
impl $1 {
pub fn new(${2}) -> $1 {
${4}return $1 {
${5}
};
}
}
endsnippet
##########
# Enum #
##########
snippet enum "An enum" b
enum ${1:enum_name} {
${VISUAL}${0},
}
endsnippet
##########
# Impl #
##########
snippet imp "An impl" b
impl ${1:Name} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
snippet drop "Drop implementation" b
impl Drop for ${1:Name} {
fn drop(&mut self) {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
}
endsnippet
############
# Traits #
############
snippet trait "Trait block" b
trait ${1:Name} {
${VISUAL}${0:${VISUAL/(.*)/(?1::\/* code *\/)/}}
}
endsnippet
#############
# Statics #
#############
snippet ss "A static string."
static ${1}: &'static str = "${VISUAL}${0}";
endsnippet
snippet stat "A static variable."
static ${1}: ${2:uint} = ${VISUAL}${0};
endsnippet
# vim:ft=snippets:

View file

@ -0,0 +1,63 @@
priority -50
extends html
snippet ns "Namespace" b
{namespace ${1:name}}
endsnippet
snippet tmpl "Template" b
/**
* ${2:TODO(`whoami`): Describe this template.}
*/
{template .${1:name}}
$0
{/template}
endsnippet
snippet msg "Message" b
{msg desc="${1:description}"}
$0
{/msg}
endsnippet
snippet let "let command" b
{let $${1:identifier}: ${2:expression} /}
endsnippet
snippet if "if .. (if)" b
{if ${1:expression}}
$0
{/if}
endsnippet
snippet ife "if .. else (ife)" b
{if ${1:expression}}
$2
{else}
$0
{/if}
endsnippet
snippet eli "else if .. (eli)" b
{elif ${1:expression}}
$0
endsnippet
snippet fore "foreach command" b
{foreach $${1:var} in ${2:ref}}
$0
{/foreach}
endsnippet
snippet for "for command" b
{for $${1:var} in range(${2:rangeexpr})}
$0
{/for}
endsnippet
snippet call "template call" b
{call ${1:tmpl}}
$0
{/call}
endsnippet

View file

@ -0,0 +1,37 @@
if exists("b:done_vimsnippets")
finish
endif
let b:done_vimsnippets = 1
" Expanding the path is not needed on Vim 7.4
if &cp || version >= 704
finish
endif
" Add pythonx to the python search path if needed (i.e. <= Vim 7.3).
if !has("python") && !has("python3")
finish
end
" This will fail if UltiSnips is not installed.
try
call UltiSnips#bootstrap#Bootstrap()
catch /E117/
finish
endtry
" This should have been set by UltiSnips, otherwise something is wrong.
if !exists("g:_uspy")
finish
end
" Expand our path
let s:SourcedFile=expand("<sfile>")
exec g:_uspy "import vim, os, sys"
exec g:_uspy "sourced_file = vim.eval('s:SourcedFile')"
exec g:_uspy "while not os.path.exists(os.path.join(sourced_file, 'pythonx')):
\ sourced_file = os.path.dirname(sourced_file)"
exec g:_uspy "module_path = os.path.join(sourced_file, 'pythonx')"
exec g:_uspy "sys.path.append(module_path)"

View file

@ -0,0 +1,20 @@
"""Helper methods used in UltiSnips snippets."""
def complete(tab, opts):
"""
get options that start with tab
:param tab: query string
:param opts: list that needs to be completed
:return: a string that start with tab
"""
msg = "({0})"
if tab:
opts = [m[len(tab):] for m in opts if m.startswith(tab)]
if len(opts) == 1:
return opts[0]
if not len(opts):
msg = "{0}"
return msg.format("|".join(opts))

View file

@ -10,6 +10,10 @@
snippet auto snippet auto
${1:FIELDNAME} = models.AutoField(${0}) ${1:FIELDNAME} = models.AutoField(${0})
snippet bigint
${1:FIELDNAME} = models.BigIntegerField(${0})
snippet binary
${1:FIELDNAME} = models.BinaryField(${0})
snippet bool snippet bool
${1:FIELDNAME} = models.BooleanField(${0:default=True}) ${1:FIELDNAME} = models.BooleanField(${0:default=True})
snippet char snippet char
@ -80,7 +84,7 @@ snippet model
def __unicode__(self): def __unicode__(self):
${5} ${5}
def save(self, force_insert=False, force_update=False): def save(self, *args, **kwargs):
${6} ${6}
@models.permalink @models.permalink

View file

@ -120,8 +120,12 @@ snippet gen_server
]). ]).
%% gen_server callbacks %% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, -export([init/1,
terminate/2, code_change/3]). handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-define(SERVER, ?MODULE). -define(SERVER, ?MODULE).
@ -157,6 +161,320 @@ snippet gen_server
code_change(_OldVsn, State, _Extra) -> code_change(_OldVsn, State, _Extra) ->
{ok, State}. {ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
# OTP gen_fsm
snippet gen_fsm
-module(${0:`vim_snippets#Filename('', 'my')`}).
-behaviour(gen_fsm).
%% API
-export([start_link/0]).
%% gen_fsm callbacks
-export([init/1,
state_name/2,
state_name/3,
handle_event/3,
handle_sync_event/4,
handle_info/3,
terminate/3,
code_change/4]).
-record(state, {}).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Creates a gen_fsm process which calls Module:init/1 to
%% initialize. To ensure a synchronized start-up procedure, this
%% function does not return until Module:init/1 has returned.
%%
%% @spec start_link() -> {ok, Pid} | ignore | {error, Error}
%% @end
%%--------------------------------------------------------------------
start_link() ->
gen_fsm:start_link({local, ?MODULE}, ?MODULE, [], []).
%%%===================================================================
%%% gen_fsm callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever a gen_fsm is started using gen_fsm:start/[3,4] or
%% gen_fsm:start_link/[3,4], this function is called by the new
%% process to initialize.
%%
%% @spec init(Args) -> {ok, StateName, State} |
%% {ok, StateName, State, Timeout} |
%% ignore |
%% {stop, StopReason}
%% @end
%%--------------------------------------------------------------------
init([]) ->
{ok, state_name, #state{}}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% There should be one instance of this function for each possible
%% state name. Whenever a gen_fsm receives an event sent using
%% gen_fsm:send_event/2, the instance of this function with the same
%% name as the current state name StateName is called to handle
%% the event. It is also called if a timeout occurs.
%%
%% @spec state_name(Event, State) ->
%% {next_state, NextStateName, NextState} |
%% {next_state, NextStateName, NextState, Timeout} |
%% {stop, Reason, NewState}
%% @end
%%--------------------------------------------------------------------
state_name(_Event, State) ->
{next_state, state_name, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% There should be one instance of this function for each possible
%% state name. Whenever a gen_fsm receives an event sent using
%% gen_fsm:sync_send_event/[2,3], the instance of this function with
%% the same name as the current state name StateName is called to
%% handle the event.
%%
%% @spec state_name(Event, From, State) ->
%% {next_state, NextStateName, NextState} |
%% {next_state, NextStateName, NextState, Timeout} |
%% {reply, Reply, NextStateName, NextState} |
%% {reply, Reply, NextStateName, NextState, Timeout} |
%% {stop, Reason, NewState} |
%% {stop, Reason, Reply, NewState}
%% @end
%%--------------------------------------------------------------------
state_name(_Event, _From, State) ->
Reply = ok,
{reply, Reply, state_name, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever a gen_fsm receives an event sent using
%% gen_fsm:send_all_state_event/2, this function is called to handle
%% the event.
%%
%% @spec handle_event(Event, StateName, State) ->
%% {next_state, NextStateName, NextState} |
%% {next_state, NextStateName, NextState, Timeout} |
%% {stop, Reason, NewState}
%% @end
%%--------------------------------------------------------------------
handle_event(_Event, StateName, State) ->
{next_state, StateName, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever a gen_fsm receives an event sent using
%% gen_fsm:sync_send_all_state_event/[2,3], this function is called
%% to handle the event.
%%
%% @spec handle_sync_event(Event, From, StateName, State) ->
%% {next_state, NextStateName, NextState} |
%% {next_state, NextStateName, NextState, Timeout} |
%% {reply, Reply, NextStateName, NextState} |
%% {reply, Reply, NextStateName, NextState, Timeout} |
%% {stop, Reason, NewState} |
%% {stop, Reason, Reply, NewState}
%% @end
%%--------------------------------------------------------------------
handle_sync_event(_Event, _From, StateName, State) ->
Reply = ok,
{reply, Reply, StateName, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_fsm when it receives any
%% message other than a synchronous or asynchronous event
%% (or a system message).
%%
%% @spec handle_info(Info,StateName,State)->
%% {next_state, NextStateName, NextState} |
%% {next_state, NextStateName, NextState, Timeout} |
%% {stop, Reason, NewState}
%% @end
%%--------------------------------------------------------------------
handle_info(_Info, StateName, State) ->
{next_state, StateName, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_fsm when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_fsm terminates with
%% Reason. The return value is ignored.
%%
%% @spec terminate(Reason, StateName, State) -> void()
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, _StateName, _State) ->
ok.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, StateName, State, Extra) ->
%% {ok, StateName, NewState}
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, StateName, State, _Extra) ->
{ok, StateName, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
# OTP gen_event
snippet gen_event
-module(${0:`vim_snippets#Filename('', 'my')`}).
-behaviour(gen_event).
%% API
-export([start_link/0,
add_handler/2]).
%% gen_event callbacks
-export([init/1,
handle_event/2,
handle_call/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {}).
%%%===================================================================
%%% gen_event callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Creates an event manager
%%
%% @spec start_link() -> {ok, Pid} | {error, Error}
%% @end
%%--------------------------------------------------------------------
start_link() ->
gen_event:start_link({local, ?MODULE}).
%%--------------------------------------------------------------------
%% @doc
%% Adds an event handler
%%
%% @spec add_handler(Handler, Args) -> ok | {'EXIT', Reason} | term()
%% @end
%%--------------------------------------------------------------------
add_handler(Handler, Args) ->
gen_event:add_handler(?MODULE, Handler, Args).
%%%===================================================================
%%% gen_event callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever a new event handler is added to an event manager,
%% this function is called to initialize the event handler.
%%
%% @spec init(Args) -> {ok, State}
%% @end
%%--------------------------------------------------------------------
init([]) ->
{ok, #state{}}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever an event manager receives an event sent using
%% gen_event:notify/2 or gen_event:sync_notify/2, this function is
%% called for each installed event handler to handle the event.
%%
%% @spec handle_event(Event, State) ->
%% {ok, State} |
%% {swap_handler, Args1, State1, Mod2, Args2} |
%% remove_handler
%% @end
%%--------------------------------------------------------------------
handle_event(_Event, State) ->
{ok, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever an event manager receives a request sent using
%% gen_event:call/3,4, this function is called for the specified
%% event handler to handle the request.
%%
%% @spec handle_call(Request, State) ->
%% {ok, Reply, State} |
%% {swap_handler, Reply, Args1, State1, Mod2, Args2} |
%% {remove_handler, Reply}
%% @end
%%--------------------------------------------------------------------
handle_call(_Request, State) ->
Reply = ok,
{ok, Reply, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called for each installed event handler when
%% an event manager receives any other message than an event or a
%% synchronous request (or a system message).
%%
%% @spec handle_info(Info, State) ->
%% {ok, State} |
%% {swap_handler, Args1, State1, Mod2, Args2} |
%% remove_handler
%% @end
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
{ok, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever an event handler is deleted from an event manager, this
%% function is called. It should be the opposite of Module:init/1 and
%% do any necessary cleaning up.
%%
%% @spec terminate(Reason, State) -> void()
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%=================================================================== %%%===================================================================
%%% Internal functions %%% Internal functions
%%%=================================================================== %%%===================================================================

View file

@ -107,6 +107,8 @@ snippet ntc
<%= number_to_currency(${1}) %> <%= number_to_currency(${1}) %>
snippet ofcfs snippet ofcfs
<%= options_from_collection_for_select ${1:collection}, ${2:value_method}, ${3:text_method}, ${0:selected_value} %> <%= options_from_collection_for_select ${1:collection}, ${2:value_method}, ${3:text_method}, ${0:selected_value} %>
snippet ofs
<%= options_for_select ${1:collection}, ${2:value_method} %>
snippet rf snippet rf
<%= render :file => "${1:file}"${0} %> <%= render :file => "${1:file}"${0} %>
snippet rt snippet rt

View file

@ -1,5 +1,7 @@
snippet lang snippet lang
{-# LANGUAGE ${0:OverloadedStrings} #-} {-# LANGUAGE ${0:OverloadedStrings} #-}
snippet haddock
{-# OPTIONS_HADDOCK ${0:hide} #-}
snippet info snippet info
-- | -- |
-- Module : ${1:Module.Namespace} -- Module : ${1:Module.Namespace}

View file

@ -0,0 +1,18 @@
# Angular HTML
snippet rep
div(ng-repeat='${1} in ${2}')
snippet repf
div(ng-repeat='${1} in ${2}' | ${3})
snippet repi
div(ng-repeat='${1} in ${2}' track by $index)
snippet hide
div(ng-hide='${1}')
snippet show
div(ng-show='${1}')
snippet if
div(ng-if='${1}')

View file

@ -1,5 +1,6 @@
snippet #! snippet #!
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
snippet imp snippet imp
import ${0:module} import ${0:module}
snippet uni snippet uni
@ -200,3 +201,10 @@ snippet epydoc
@raise e: ${0: Description} @raise e: ${0: Description}
""" """
snippet dol
def ${1:__init__}(self, *args, **kwargs):
super(${0:ClassName}, self).$1(*args, **kwargs)
snippet kwg
self.${1:var_name} = kwargs.get('$1', ${2:None})
snippet lkwg
${1:var_name} = kwargs.get('$1', ${2:None})

View file

@ -479,6 +479,8 @@ snippet asne
assert_not_equal ${1:unexpected}, ${2:actual} assert_not_equal ${1:unexpected}, ${2:actual}
snippet asid snippet asid
assert_in_delta ${1:expected_float}, ${2:actual_float}, ${3:2 ** -20} assert_in_delta ${1:expected_float}, ${2:actual_float}, ${3:2 ** -20}
snippet asi
assert_includes ${1:collection}, ${2:object}
snippet asio snippet asio
assert_instance_of ${1:ExpectedClass}, ${2:actual_instance} assert_instance_of ${1:ExpectedClass}, ${2:actual_instance}
snippet asko snippet asko
@ -749,8 +751,49 @@ snippet mapwo
${1:map}.with_options :${2:controller} => '${3:thing}' do |$3| ${1:map}.with_options :${2:controller} => '${3:thing}' do |$3|
${0} ${0}
end end
###############################
# model callback snippets #
###############################
# before callback
snippet mbv
before_validation :${0:method}
snippet mbc
before_create :${0:method}
snippet mbu
before_update :${0:method}
snippet mbs snippet mbs
before_save :${0:method} before_save :${0:method}
snippet mbd
before_destroy :${0:method}
# after callback
snippet mav
after_validation :${0:method}
snippet maf
after_find :${0:method}
snippet mat
after_touch :${0:method}
snippet macr
after_create :${0:method}
snippet mau
after_update :${0:method}
snippet mas
after_save :${0:method}
snippet mad
after_destroy :${0:method}
# around callback
snippet marc
around_create :${0:method}
snippet maru
around_update :${0:method}
snippet mars
around_save :${0:method}
snippet mard
around_destroy :${0:method}
snippet mcht snippet mcht
change_table :${1:table_name} do |t| change_table :${1:table_name} do |t|
${0} ${0}

View file

@ -194,8 +194,9 @@ snippet mhmap
snippet as snippet as
${1:name}.asInstanceOf[${2:T}] ${1:name}.asInstanceOf[${2:T}]
#isInstanceOf[] #isInstanceOf[]
snippet is
${1:name}.isInstanceOf[${2:T}] ${1:name}.isInstanceOf[${2:T}]
#end
#collections methods #collections methods
#scope() with one arg #scope() with one arg