1
0
mirror of https://github.com/gryf/.vim.git synced 2026-05-03 18:00:55 +02:00

Added branch pathogen

This commit is contained in:
2012-02-13 21:19:34 +01:00
parent b989a7b269
commit 5047146e53
261 changed files with 5724 additions and 3107 deletions
-1115
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-50
View File
@@ -1,50 +0,0 @@
" NOTE: You must, of course, install the ack script
" in your path.
" On Ubuntu:
" sudo apt-get install ack-grep
" ln -s /usr/bin/ack-grep /usr/bin/ack
" With MacPorts:
" sudo port install p5-app-ack
let g:ackprg="ack\\ -H\\ --nocolor\\ --nogroup"
function! Ack(args)
let grepprg_bak=&grepprg
exec "set grepprg=" . g:ackprg
execute "silent! grep " . a:args
botright copen
let &grepprg=grepprg_bak
exec "redraw!"
endfunction
function! AckAdd(args)
let grepprg_bak=&grepprg
exec "set grepprg=" . g:ackprg
execute "silent! grepadd " . a:args
botright copen
let &grepprg=grepprg_bak
exec "redraw!"
endfunction
function! LAck(args)
let grepprg_bak=&grepprg
exec "set grepprg=" . g:ackprg
execute "silent! lgrep " . a:args
botright lopen
let &grepprg=grepprg_bak
exec "redraw!"
endfunction
function! LAckAdd(args)
let grepprg_bak=&grepprg
exec "set grepprg=" . g:ackprg
execute "silent! lgrepadd " . a:args
botright lopen
let &grepprg=grepprg_bak
exec "redraw!"
endfunction
command! -nargs=* -complete=file Ack call Ack(<q-args>)
command! -nargs=* -complete=file AckAdd call AckAdd(<q-args>)
command! -nargs=* -complete=file LAck call LAck(<q-args>)
command! -nargs=* -complete=file LAckAdd call LAckAdd(<q-args>)
File diff suppressed because it is too large Load Diff
-547
View File
@@ -1,547 +0,0 @@
" ============================================================================
" File: buffers.vim
" Description: vim plugin that provides buffers helpers. Almost all of parts
" are taken from Eclim project <http://eclim.sourceforge.net>
" Maintainer: Roman 'gryf' Dobosz <gryf73@gmail.com>
" Last Change: 2011-07-16
" License: This program is free software: you can redistribute it and/or
" modify it under the terms of the GNU General Public License as
" published by the Free Software Foundation, either version 3 of
" the License, or (at your option) any later version.
"
" This program is distributed in the hope that it will be useful,
" but WITHOUT ANY WARRANTY; without even the implied warranty of
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
" GNU General Public License for more details.
"
" You should have received a copy of the GNU General Public
" License along with this program. If not, see
" <http://www.gnu.org/licenses/>.
" ============================================================================
let s:Eclim_ver = '1.7.1'
" Eclim: {{{1
" files:
" - plugin/eclim.vim (global vars)
" - plugin/common.vim (commands)
" Global Variables {{{2
if has("signs")
if !exists("g:EclimSignLevel")
let g:EclimSignLevel = 5
endif
else
let g:EclimSignLevel = 0
endif
if !exists("g:EclimInfoHighlight")
let g:EclimInfoHighlight = "Statement"
endif
if !exists("g:EclimLogLevel")
let g:EclimLogLevel = 4
endif
if !exists("g:EclimTraceHighlight")
let g:EclimTraceHighlight = "Normal"
endif
if !exists("g:EclimDebugHighlight")
let g:EclimDebugHighlight = "Normal"
endif
if !exists("g:EclimInfoHighlight")
let g:EclimInfoHighlight = "Statement"
endif
if !exists("g:EclimWarningHighlight")
let g:EclimWarningHighlight = "WarningMsg"
endif
if !exists("g:EclimErrorHighlight")
let g:EclimErrorHighlight = "Error"
endif
if !exists("g:EclimFatalHighlight")
let g:EclimFatalHighlight = "Error"
endif
if !exists("g:EclimShowCurrentError")
let g:EclimShowCurrentError = 1
endif
if !exists("g:EclimShowCurrentErrorBalloon")
let g:EclimShowCurrentErrorBalloon = 1
endif
if !exists("g:EclimOpenQFLists")
let g:EclimOpenQFLists = 1
endif
" }}}
" Command Declarations {{{2
if !exists(":Buffers")
command Buffers :call s:Buffers()
endif
" }}}
" End Eclim: }}}
" Common Buffers: {{{1
" Global Variables {{{2
if !exists('g:EclimBuffersSort')
let g:EclimBuffersSort = 'file'
endif
if !exists('g:EclimBuffersSortDirection')
let g:EclimBuffersSortDirection = 'asc'
endif
if !exists('g:EclimBuffersDefaultAction')
let g:EclimBuffersDefaultAction = 'edit'
endif
" }}}
" Buffers() eclim/autoload/eclim/common/buffers.vim {{{2
" Like, :buffers, but opens a temporary buffer.
function! s:Buffers()
redir => list
silent exec 'buffers'
redir END
let buffers = []
let filelength = 0
for entry in split(list, '\n')
let buffer = {}
let buffer.status = substitute(entry, '\s*[0-9]\+\s\+\(.\{-}\)\s\+".*', '\1', '')
let buffer.path = substitute(entry, '.\{-}"\(.\{-}\)".*', '\1', '')
let buffer.path = fnamemodify(buffer.path, ':p')
let buffer.file = fnamemodify(buffer.path, ':p:t')
let buffer.dir = fnamemodify(buffer.path, ':p:h')
exec 'let buffer.bufnr = ' . substitute(entry, '\s*\([0-9]\+\).*', '\1', '')
exec 'let buffer.lnum = ' .
\ substitute(entry, '.*"\s\+line\s\+\([0-9]\+\).*', '\1', '')
call add(buffers, buffer)
if len(buffer.file) > filelength
let filelength = len(buffer.file)
endif
endfor
if g:EclimBuffersSort != ''
call sort(buffers, 'BufferCompare')
endif
let lines = []
for buffer in buffers
call add(lines, s:BufferEntryToLine(buffer, filelength))
endfor
call TempWindow('[buffers]', lines)
setlocal modifiable noreadonly
call append(line('$'), ['', '" use ? to view help'])
setlocal nomodifiable readonly
let b:eclim_buffers = buffers
" syntax
set ft=eclim_buffers
hi link BufferActive Special
hi link BufferHidden Comment
syntax match BufferActive /+\?active\s\+\(\[RO\]\)\?/
syntax match BufferHidden /+\?hidden\s\+\(\[RO\]\)\?/
syntax match Comment /^".*/
" mappings
nnoremap <silent> <buffer> <cr> :call <SID>BufferOpen2(g:EclimBuffersDefaultAction)<cr>
nnoremap <silent> <buffer> E :call <SID>BufferOpen2('edit')<cr>
nnoremap <silent> <buffer> S :call <SID>BufferOpen2('split')<cr>
nnoremap <silent> <buffer> T :call <SID>BufferOpen('tablast \| tabnew')<cr>
nnoremap <silent> <buffer> D :call <SID>BufferDelete()<cr>
nnoremap <silent> <buffer> R :Buffers<cr>
" assign to buffer var to get around weird vim issue passing list containing
" a string w/ a '<' in it on execution of mapping.
let b:buffers_help = [
\ '<cr> - open buffer with default action',
\ 'E - open with :edit',
\ 'S - open in a new split window',
\ 'T - open in a new tab',
\ 'D - delete the buffer',
\ 'R - refresh the buffer list',
\ ]
nnoremap <buffer> <silent> ?
\ :call BufferHelp(b:buffers_help, 'vertical', 40)<cr>
"augroup eclim_buffers
" autocmd!
" autocmd BufAdd,BufWinEnter,BufDelete,BufWinLeave *
" \ call eclim#common#buffers#BuffersUpdate()
" autocmd BufUnload <buffer> autocmd! eclim_buffers
"augroup END
endfunction " }}}
" BufferCompare(buffer1, buffer2) eclim/autoload/eclim/common/buffers.vim {{{2
function! BufferCompare(buffer1, buffer2)
exec 'let attr1 = a:buffer1.' . g:EclimBuffersSort
exec 'let attr2 = a:buffer2.' . g:EclimBuffersSort
let compare = attr1 == attr2 ? 0 : attr1 > attr2 ? 1 : -1
if g:EclimBuffersSortDirection == 'desc'
let compare = 0 - compare
endif
return compare
endfunction " }}}
" s:BufferDelete() {{{2
function! s:BufferDelete()
let line = line('.')
if line > len(b:eclim_buffers)
return
endif
let index = line - 1
setlocal modifiable
setlocal noreadonly
exec line . ',' . line . 'delete _'
setlocal nomodifiable
setlocal readonly
let buffer = b:eclim_buffers[index]
call remove(b:eclim_buffers, index)
let winnr = bufwinnr(buffer.bufnr)
if winnr != -1
" if active in a window, go to the window to delete the buffer since that
" keeps eclim's prevention of closing the last non-utility window working
" properly.
let curwin = winnr()
exec winnr . 'winc w'
bdelete
exec curwin . 'winc w'
else
exec 'bd ' . buffer.bufnr
endif
endfunction " }}}
" s:BufferEntryToLine(buffer, filelength) eclim/autoload/eclim/common/buffers.vim {{{2
function! s:BufferEntryToLine(buffer, filelength)
let line = ''
let line .= a:buffer.status =~ '+' ? '+' : ' '
let line .= a:buffer.status =~ 'a' ? 'active' : 'hidden'
let line .= a:buffer.status =~ '[-=]' ? ' [RO] ' : ' '
let line .= a:buffer.file
let pad = a:filelength - len(a:buffer.file) + 2
while pad > 0
let line .= ' '
let pad -= 1
endwhile
let line .= a:buffer.dir
return line
endfunction " }}}
" s:BufferOpen(cmd) eclim/autoload/eclim/common/buffers.vim {{{2
function! s:BufferOpen(cmd)
let line = line('.')
if line > len(b:eclim_buffers)
return
endif
let file = bufname(b:eclim_buffers[line - 1].bufnr)
let winnr = b:winnr
close
exec winnr . 'winc w'
call GoToBufferWindowOrOpen(file, a:cmd)
endfunction " }}}
" End Common Buffers: }}}
" Util: {{{1
" Script Variables eclim/autoload/eclim/util.vim {{{2
let s:buffer_write_closing_commands = '^\s*\(' .
\ 'wq\|xa\|' .
\ '\d*w[nN]\|\d*wp\|' .
\ 'ZZ' .
\ '\)'
let s:bourne_shells = ['sh', 'bash', 'dash', 'ksh', 'zsh']
let s:c_shells = ['csh', 'tcsh']
let s:show_current_error_displaying = 0
" }}}
" DelayedCommand(command, [delay]) eclim/autoload/eclim/util.vim {{{2
" Executes a delayed command. Useful in cases where one would expect an
" autocommand event (WinEnter, etc) to fire, but doesn't, or you need a
" command to execute after other autocommands have finished.
" Note: Nesting is not supported. A delayed command cannot be invoke off
" another delayed command.
function! DelayedCommand(command, ...)
let uid = fnamemodify(tempname(), ':t:r')
if &updatetime > 1
exec 'let g:eclim_updatetime_save' . uid . ' = &updatetime'
endif
exec 'let g:eclim_delayed_command' . uid . ' = a:command'
let &updatetime = len(a:000) ? a:000[0] : 1
exec 'augroup delayed_command' . uid
exec 'autocmd CursorHold * ' .
\ ' if exists("g:eclim_updatetime_save' . uid . '") | ' .
\ ' let &updatetime = g:eclim_updatetime_save' . uid . ' | ' .
\ ' unlet g:eclim_updatetime_save' . uid . ' | ' .
\ ' endif | ' .
\ ' exec g:eclim_delayed_command' . uid . ' | ' .
\ ' unlet g:eclim_delayed_command' . uid . ' | ' .
\ ' autocmd! delayed_command' . uid
exec 'augroup END'
endfunction " }}}
" EscapeBufferName(name) eclim/autoload/eclim/util.vim {{{2
" Escapes the supplied buffer name so that it can be safely used by buf*
" functions.
function! EscapeBufferName(name)
let name = a:name
" escaping the space in cygwin could lead to the dos path error message that
" cygwin throws when a dos path is referenced.
if !has('win32unix')
let name = escape(a:name, ' ')
endif
return substitute(name, '\(.\{-}\)\[\(.\{-}\)\]\(.\{-}\)', '\1[[]\2[]]\3', 'g')
endfunction " }}}
" GoToBufferWindow(buf) eclim/autoload/eclim/util.vim {{{2
" Focuses the window containing the supplied buffer name or buffer number.
" Returns 1 if the window was found, 0 otherwise.
function! GoToBufferWindow(buf)
if type(a:buf) == 0
let winnr = bufwinnr(a:buf)
else
let name = EscapeBufferName(a:buf)
let winnr = bufwinnr(bufnr('^' . name . '$'))
endif
if winnr != -1
exec winnr . "winc w"
call DelayedCommand('doautocmd WinEnter')
return 1
endif
return 0
endfunction " }}}
" GoToBufferWindowOrOpen(name, cmd) eclim/autoload/eclim/util.vim {{{2
" Gives focus to the window containing the buffer for the supplied file, or if
" none, opens the file using the supplied command.
function! GoToBufferWindowOrOpen(name, cmd)
let name = EscapeBufferName(a:name)
let winnr = bufwinnr(bufnr('^' . name))
if winnr != -1
exec winnr . "winc w"
call DelayedCommand('doautocmd WinEnter')
else
let cmd = a:cmd
" if splitting and the buffer is a unamed empty buffer, then switch to an
" edit.
if cmd == 'split' && expand('%') == '' &&
\ !&modified && line('$') == 1 && getline(1) == ''
let cmd = 'edit'
endif
silent exec cmd . ' ' . escape(Simplify(a:name), ' ')
endif
endfunction " }}}
" GoToBufferWindowRegister(buf) eclim/autoload/eclim/util.vim {{{2
" Registers the autocmd for returning the user to the supplied buffer when the
" current buffer is closed.
function! GoToBufferWindowRegister(buf)
exec 'autocmd BufWinLeave <buffer> ' .
\ 'call GoToBufferWindow("' . escape(a:buf, '\') . '") | ' .
\ 'doautocmd BufEnter'
endfunction " }}}
" Simplify(file) eclim/autoload/eclim/util.vim {{{2
" Simply the supplied file to the shortest valid name.
function! Simplify(file)
let file = a:file
" Don't run simplify on url files, it will screw them up.
if file !~ '://'
let file = simplify(file)
endif
" replace all '\' chars with '/' except those escaping spaces.
let file = substitute(file, '\\\([^[:space:]]\)', '/\1', 'g')
let cwd = substitute(getcwd(), '\', '/', 'g')
if cwd !~ '/$'
let cwd .= '/'
endif
if file =~ '^' . cwd
let file = substitute(file, '^' . cwd, '', '')
endif
return file
endfunction " }}}
" TempWindow(name, lines, [readonly]) eclim/autoload/eclim/util.vim {{{2
" Opens a temp window w/ the given name and contents which is readonly unless
" specified otherwise.
function! TempWindow(name, lines, ...)
let filename = expand('%:p')
let winnr = winnr()
call TempWindowClear(a:name)
let name = EscapeBufferName(a:name)
if bufwinnr(name) == -1
silent! noautocmd exec "botright 10sview " . escape(a:name, ' []')
setlocal nowrap
setlocal winfixheight
setlocal noswapfile
setlocal nobuflisted
setlocal buftype=nofile
setlocal bufhidden=delete
silent doautocmd WinEnter
else
let temp_winnr = bufwinnr(name)
if temp_winnr != winnr()
exec temp_winnr . 'winc w'
silent doautocmd WinEnter
endif
endif
setlocal modifiable
setlocal noreadonly
call append(1, a:lines)
retab
silent 1,1delete _
if len(a:000) == 0 || a:000[0]
setlocal nomodified
setlocal nomodifiable
setlocal readonly
endif
silent doautocmd BufEnter
" Store filename and window number so that plugins can use it if necessary.
if filename != expand('%:p')
let b:filename = filename
let b:winnr = winnr
augroup eclim_temp_window
autocmd! BufWinLeave <buffer>
call GoToBufferWindowRegister(b:filename)
augroup END
endif
endfunction " }}}
" TempWindowClear(name) eclim/autoload/eclim/util.vim {{{2
" Clears the contents of the temp window with the given name.
function! TempWindowClear(name)
let name = EscapeBufferName(a:name)
if bufwinnr(name) != -1
let curwinnr = winnr()
exec bufwinnr(name) . "winc w"
setlocal modifiable
setlocal noreadonly
silent 1,$delete _
exec curwinnr . "winc w"
endif
endfunction " }}}
" End Util: }}}
" Eclim Help: {{{1
" BufferHelp(lines, orientation, size) eclim/autoload/eclim/help.vim {{{
" Function to display a help window for the current buffer.
function! BufferHelp(lines, orientation, size)
let orig_bufnr = bufnr('%')
let name = expand('%')
if name =~ '^\W.*\W$'
let name = name[:-2] . ' Help' . name[len(name) - 1]
else
let name .= ' Help'
endif
let bname = EscapeBufferName(name)
let orient = a:orientation == 'vertical' ? 'v' : ''
if bufwinnr(bname) != -1
exec 'bd ' . bufnr(bname)
return
endif
silent! noautocmd exec a:size . orient . "new " . escape(name, ' ')
if a:orientation == 'vertical'
setlocal winfixwidth
else
setlocal winfixheight
endif
setlocal nowrap
setlocal noswapfile nobuflisted nonumber
setlocal buftype=nofile bufhidden=delete
nnoremap <buffer> <silent> ? :bd<cr>
nnoremap <buffer> <silent> q :bd<cr>
setlocal modifiable noreadonly
silent 1,$delete _
call append(1, a:lines)
retab
silent 1,1delete _
if len(a:000) == 0 || a:000[0]
setlocal nomodified nomodifiable readonly
endif
let help_bufnr = bufnr('%')
augroup eclim_help_buffer
autocmd! BufWinLeave <buffer>
autocmd BufWinLeave <buffer> nested autocmd! eclim_help_buffer * <buffer>
exec 'autocmd BufWinLeave <buffer> nested ' .
\ 'autocmd! eclim_help_buffer * <buffer=' . orig_bufnr . '>'
exec 'autocmd! BufWinLeave <buffer=' . orig_bufnr . '>'
exec 'autocmd BufWinLeave <buffer=' . orig_bufnr . '> nested bd ' . help_bufnr
augroup END
return help_bufnr
endfunction " }}}
" }}}
" Gryfs Mods: {{{
" s:BufferOpen2(cmd) (gryf) {{{2
function! s:BufferOpen2(cmd)
let line = line('.')
if line > len(b:eclim_buffers)
return
endif
let bufnr = b:eclim_buffers[line - 1].bufnr
let winnr = b:winnr
close
exec winnr . 'winc w'
call s:GoToBufferWindowOrOpen2(bufnr, a:cmd)
endfunction " }}}
" GoToBufferWindowOrOpen2(nr, cmd) (gryf) {{{2
" modified function GoToBufferWindowOrOpen. instead of buffer name it accepts
" buffer number.
function! s:GoToBufferWindowOrOpen2(nr, cmd)
let winnr = bufwinnr(a:nr)
if winnr != -1
exec winnr . "winc w"
call DelayedCommand('doautocmd WinEnter')
else
if a:cmd == 'edit'
silent exec 'buffer ' . a:nr
elseif a:cmd == 'split'
silent exec 'sbuffer ' . a:nr
endif
endif
endfunction " }}}
" End Gryfs Mods: }}}
" vim:ft=vim:fdm=marker
-1328
View File
File diff suppressed because it is too large Load Diff
-158
View File
@@ -1,158 +0,0 @@
"=============================================================================
" Copyright (c) 2007-2010 Takeshi NISHIDA
"
" GetLatestVimScripts: 1984 1 :AutoInstall: FuzzyFinder
"=============================================================================
" LOAD GUARD {{{1
try
if !l9#guardScriptLoading(expand('<sfile>:p'), 702, 101, [])
finish
endif
catch /E117/
echoerr '***** L9 library must be installed! *****'
finish
endtry
" }}}1
"=============================================================================
" LOCAL FUNCTIONS {{{1
"
function s:initialize()
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_modesDisable' , [ 'mrufile', 'mrucmd', ])
call l9#defineVariableDefault('g:fuf_keyOpen' , '<CR>')
call l9#defineVariableDefault('g:fuf_keyOpenSplit' , '<C-j>')
call l9#defineVariableDefault('g:fuf_keyOpenVsplit' , '<C-k>')
call l9#defineVariableDefault('g:fuf_keyOpenTabpage' , '<C-l>')
call l9#defineVariableDefault('g:fuf_keyPreview' , '<C-@>')
call l9#defineVariableDefault('g:fuf_keyNextMode' , '<C-t>')
call l9#defineVariableDefault('g:fuf_keyPrevMode' , '<C-y>')
call l9#defineVariableDefault('g:fuf_keyPrevPattern' , '<C-s>')
call l9#defineVariableDefault('g:fuf_keyNextPattern' , '<C-_>')
call l9#defineVariableDefault('g:fuf_keySwitchMatching', '<C-\><C-\>')
call l9#defineVariableDefault('g:fuf_dataDir' , '~/.vim-fuf-data')
call l9#defineVariableDefault('g:fuf_abbrevMap' , {})
call l9#defineVariableDefault('g:fuf_patternSeparator' , ';')
call l9#defineVariableDefault('g:fuf_promptHighlight' , 'Question')
call l9#defineVariableDefault('g:fuf_ignoreCase' , 1)
call l9#defineVariableDefault('g:fuf_splitPathMatching', 1)
call l9#defineVariableDefault('g:fuf_fuzzyRefining' , 0)
call l9#defineVariableDefault('g:fuf_smartBs' , 1)
call l9#defineVariableDefault('g:fuf_reuseWindow' , 1)
call l9#defineVariableDefault('g:fuf_timeFormat' , '(%Y-%m-%d %H:%M:%S)')
call l9#defineVariableDefault('g:fuf_learningLimit' , 100)
call l9#defineVariableDefault('g:fuf_enumeratingLimit' , 50)
call l9#defineVariableDefault('g:fuf_maxMenuWidth' , 78)
call l9#defineVariableDefault('g:fuf_previewHeight' , 0)
call l9#defineVariableDefault('g:fuf_autoPreview' , 0)
call l9#defineVariableDefault('g:fuf_useMigemo' , 0)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_buffer_prompt' , '>Buffer[]>')
call l9#defineVariableDefault('g:fuf_buffer_switchOrder', 10)
call l9#defineVariableDefault('g:fuf_buffer_mruOrder' , 1)
call l9#defineVariableDefault('g:fuf_buffer_keyDelete' , '<C-]>')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_file_prompt' , '>File[]>')
call l9#defineVariableDefault('g:fuf_file_switchOrder', 20)
call l9#defineVariableDefault('g:fuf_file_exclude' , '\v\~$|\.(o|exe|dll|bak|orig|sw[po])$|(^|[/\\])\.(hg|git|bzr)($|[/\\])')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_coveragefile_prompt' , '>CoverageFile[]>')
call l9#defineVariableDefault('g:fuf_coveragefile_switchOrder', 30)
call l9#defineVariableDefault('g:fuf_coveragefile_exclude' , '\v\~$|\.(o|exe|dll|bak|orig|sw[po])$|(^|[/\\])\.(hg|git|bzr)($|[/\\])')
call l9#defineVariableDefault('g:fuf_coveragefile_globPatterns', ['**/.*', '**/*'])
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_dir_prompt' , '>Dir[]>')
call l9#defineVariableDefault('g:fuf_dir_switchOrder', 40)
call l9#defineVariableDefault('g:fuf_dir_exclude' , '\v(^|[/\\])\.(hg|git|bzr)($|[/\\])')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_mrufile_prompt' , '>MRU-File[]>')
call l9#defineVariableDefault('g:fuf_mrufile_switchOrder', 50)
call l9#defineVariableDefault('g:fuf_mrufile_exclude' , '\v\~$|\.(o|exe|dll|bak|orig|sw[po])$|^(\/\/|\\\\|\/mnt\/|\/media\/)')
call l9#defineVariableDefault('g:fuf_mrufile_maxItem' , 200)
call l9#defineVariableDefault('g:fuf_mrufile_maxItemDir' , 50)
call l9#defineVariableDefault('g:fuf_mrufile_keyExpand' , '<C-]>')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_mrucmd_prompt' , '>MRU-Cmd[]>')
call l9#defineVariableDefault('g:fuf_mrucmd_switchOrder', 60)
call l9#defineVariableDefault('g:fuf_mrucmd_exclude' , '^$')
call l9#defineVariableDefault('g:fuf_mrucmd_maxItem' , 200)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_bookmarkfile_prompt' , '>Bookmark-File[]>')
call l9#defineVariableDefault('g:fuf_bookmarkfile_switchOrder', 70)
call l9#defineVariableDefault('g:fuf_bookmarkfile_searchRange', 400)
call l9#defineVariableDefault('g:fuf_bookmarkfile_keyDelete' , '<C-]>')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_bookmarkdir_prompt' , '>Bookmark-Dir[]>')
call l9#defineVariableDefault('g:fuf_bookmarkdir_switchOrder', 80)
call l9#defineVariableDefault('g:fuf_bookmarkdir_keyDelete' , '<C-]>')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_tag_prompt' , '>Tag[]>')
call l9#defineVariableDefault('g:fuf_tag_switchOrder', 90)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_buffertag_prompt' , '>Buffer-Tag[]>')
call l9#defineVariableDefault('g:fuf_buffertag_switchOrder', 100)
call l9#defineVariableDefault('g:fuf_buffertag_ctagsPath' , 'ctags')
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_taggedfile_prompt' , '>Tagged-File[]>')
call l9#defineVariableDefault('g:fuf_taggedfile_switchOrder', 110)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_jumplist_prompt' , '>Jump-List[]>')
call l9#defineVariableDefault('g:fuf_jumplist_switchOrder', 120)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_changelist_prompt' , '>Change-List[]>')
call l9#defineVariableDefault('g:fuf_changelist_switchOrder', 130)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_quickfix_prompt' , '>Quickfix[]>')
call l9#defineVariableDefault('g:fuf_quickfix_switchOrder', 140)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_line_prompt' , '>Line[]>')
call l9#defineVariableDefault('g:fuf_line_switchOrder', 150)
"---------------------------------------------------------------------------
call l9#defineVariableDefault('g:fuf_help_prompt' , '>Help[]>')
call l9#defineVariableDefault('g:fuf_help_switchOrder', 160)
"---------------------------------------------------------------------------
command! -bang -narg=0 FufEditDataFile call fuf#editDataFile()
command! -bang -narg=0 FufRenewCache call s:renewCachesOfAllModes()
"---------------------------------------------------------------------------
call fuf#addMode('buffer')
call fuf#addMode('file')
call fuf#addMode('coveragefile')
call fuf#addMode('dir')
call fuf#addMode('mrufile')
call fuf#addMode('mrucmd')
call fuf#addMode('bookmarkfile')
call fuf#addMode('bookmarkdir')
call fuf#addMode('tag')
call fuf#addMode('buffertag')
call fuf#addMode('taggedfile')
call fuf#addMode('jumplist')
call fuf#addMode('changelist')
call fuf#addMode('quickfix')
call fuf#addMode('line')
call fuf#addMode('help')
call fuf#addMode('givenfile')
call fuf#addMode('givendir')
call fuf#addMode('givencmd')
call fuf#addMode('callbackfile')
call fuf#addMode('callbackitem')
"---------------------------------------------------------------------------
endfunction
"
function s:renewCachesOfAllModes()
for m in fuf#getModeNames()
call fuf#{m}#renewCache()
endfor
endfunction
" }}}1
"=============================================================================
" INITIALIZATION {{{1
call s:initialize()
" }}}1
"=============================================================================
" vim: set fdm=marker:
-854
View File
@@ -1,854 +0,0 @@
" File: grep.vim
" Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com)
" Version: 1.9
" Last Modified: September 10, 2007
"
" Overview
" --------
" The grep plugin integrates the grep, fgrep, egrep, and agrep tools with
" Vim and allows you to search for a pattern in one or more files and jump
" to them.
"
" To use this plugin, you need the grep, fgrep, egrep, agrep, find and
" xargs utilities. These tools are present in most of the Unix installations.
" For MS-Windows systems, you can download the GNU grep and find utilities
" from the following sites:
"
" http://gnuwin32.sourceforge.net/packages/grep.htm
" http://gnuwin32.sourceforge.net/packages/findutils.htm
"
" Installation
" ------------
" 1. Copy the grep.vim file to the $HOME/.vim/plugin or $HOME/vimfiles/plugin
" or $VIM/vimfiles/plugin directory.
" Refer to the following Vim help topics for more information about Vim
" plugins:
" :help add-plugin
" :help add-global-plugin
" :help runtimepath
" 2. If the grep executables are not already present in one of the directories
" in the PATH environment variable, then set the Grep_Path and other _Path
" variables to point to the location of the grep utilites in the .vimrc
" file.
" 3. Restart Vim.
" 4. You can now use the ":Grep" and other commands to search for patterns in
" files.
"
" Usage
" -----
" The grep.vim plugin introduces the following Vim commands:
"
" :Grep - Search for the specified pattern in the specified files
" :GrepAdd - Same as ":Grep" but adds the results to the current results
" :Rgrep - Run recursive grep
" :RgrepAdd - Same as ":Rgrep" but adds the results to the current results
" :GrepBuffer - Search for a pattern on all open buffers
" :GrepBufferAdd - Same as ":GrepBuffer" but adds the results to the current
" results
" :Bgrep - Same as :GrepBuffer
" :BgrepAdd - Same as :GrepBufferAdd
" :GrepArgs - Search for a pattern on all the Vim argument
" filenames (:args)
" :GrepArgsAdd - Same as ":GrepArgs" but adds the results to the current
" results
" :Fgrep - Run fgrep
" :FgrepAdd - Same as ":Fgrep" but adds the results to the current
" results
" :Rfgrep - Run recursive fgrep
" :RfgrepAdd - Same as ":Rfgrep" but adds the results to the current
" results
" :Egrep - Run egrep
" :EgrepAdd - Same as ":Egrep" but adds the results to the current
" results
" :Regrep - Run recursive egrep
" :RegrepAdd - Same as ":Regrep" but adds the results to the current
" results
" :Agrep - Run agrep
" :AgrepAdd - Same as ":Agrep" but adds the results to the current
" results
" :Ragrep - Run recursive agrep
" :RagrepAdd - Same as ":Ragrep" but adds the results to the current
" results
"
" The above commands can be invoked like this:
"
" :Grep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Rgrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Fgrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Rfgrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Egrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Regrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Agrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :Ragrep [<grep_options>] [<search_pattern> [<file_name(s)>]]
"
" :GrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :RgrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :FgrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :RfgrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :EgrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :RegrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :AgrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
" :RagrepAdd [<grep_options>] [<search_pattern> [<file_name(s)>]]
"
" :GrepBuffer [<grep_options>] [<search_pattern>]
" :Bgrep [<grep_options>] [<search_pattern>]
" :GrepArgs [<grep_options>] [<search_pattern>]
"
" :GrepBufferAdd [<grep_options>] [<search_pattern>]
" :BgrepAdd [<grep_options>] [<search_pattern>]
" :GrepArgsAdd [<grep_options>] [<search_pattern>]
"
" In the above commands, all the arguments are optional.
"
" You can specify grep options like -i (ignore case) or -w (search for a word)
" to the above commands. If the <grep_options> are not specified, then the
" default grep options specified by the variable Grep_Default_Options is
" used.
"
" You can specify the grep pattern to search as an argument to the above
" commands. If the <search_pattern> is not specified, then you will be
" prompted to enter a search pattern. By default, the keyword under the cursor
" is displayed for the search pattern prompt. You can accept the default or
" modify it.
"
" The search pattern is automatically enclosed by the character specified in
" the Grep_Shell_Quote_Char variable. You should not enclose the search
" pattern with a shell escape character.
"
" If you want to specify a search pattern with space characters or a
" multi-word pattern, then you should use the Grep command pattern input
" prompt to supply the pattern.
"
" You can specify one or more file names (or file patterns) to the above
" commands. If the <file_names> are not specified, then you will be prompted
" to enter file names. By default, the pattern specified by the
" Grep_Default_Filelist variable is used. To specify the file name(s) as an
" argument to the above commands, you have to specify the search pattern also.
"
" When you enter only the command name, you will be prompted to enter the
" search pattern and the files in which to search for the pattern. By default,
" the keyword under the cursor is displayed for the search pattern prompt.
" Depending on the command, you may prompted for additional parameters like
" the directories to search for the pattern.
"
" You can retrieve previously entered values for the Grep prompts using the up
" and down arrow keys. You can cancel the command by pressing the escape key.
" You can use CTRL-U to erase the default shown for the prompt and CTRL-W to
" erase the previous word in the prompt. For more information about editing
" the prompt, read ':help cmdline-editing' Vim help topic.
"
" After invoking any of the grep commands, you can cancel the command, when
" you are prompted for a search pattern or file names or a directory by
" pressing the <Esc> key. You cannot cancel (or kill) the
" grep/fgrep/egrep/agrep commands after the external command is invoked.
"
" The GrepAdd, RgrepAdd and other *Add commands append the search output to
" the current search output. This is useful if you want to see the search
" results for multiple patterns at the same time. These commands are available
" only in Vim version 7.0 and above.
"
" You can map a key to invoke any of the above commands. For example, the
" following map invokes the :Grep command to search for the keyword under the
" cursor:
"
" nnoremap <silent> <F3> :Grep<CR>
"
" The output of the grep command will be listed in the Vim quickfix window.
" 1. You can select a line in the quickfix window and press <Enter> or double
" click on a match to jump to that line.
" 2. You can use the ":cnext" and ":cprev" commands to the jump to the next or
" previous output line.
" 3. You can use the ":colder" and ":cnewer" commands to go between multiple
" grep quickfix output windows.
" 4. The quickfix window need not be opened always to use the grep output.
" You can close the quickfix window and use the quickfix commands to jump
" to the grep matches. Use the ":copen" command to open the quickfix
" window again.
"
" For more information about other quickfix commands read ":help quickfix"
"
" When using GUI Vim, the Tools->Search menu item with a few sub-menu items is
" created for few variations of the search command.
"
" Configuration
" -------------
" By changing the following variables you can configure the behavior of this
" plugin. Set the following variables in your .vimrc file using the 'let'
" command.
"
" The 'Grep_Path' variable is used to locate the grep utility. By default,
" this is set to grep. You can change this using the let command:
"
" :let Grep_Path = 'd:\tools\grep.exe'
"
" The 'Fgrep_Path' variable is used to locate the fgrep utility. By default,
" this is set to fgrep. You can change this using the let command:
"
" :let Fgrep_Path = 'd:\tools\fgrep.exe'
"
" The 'Egrep_Path' variable is used to locate the egrep utility. By default,
" this is set to egrep. You can change this using the let command:
"
" :let Egrep_Path = 'd:\tools\egrep.exe'
"
" The 'Agrep_Path' variable is used to locate the agrep utility. By default,
" this is set to agrep. You can change this using the let command:
"
" :let Agrep_Path = 'd:\tools\agrep.exe'
"
" The 'Grep_Find_Path' variable is used to locate the find utility. By
" default, this is set to d:\tools\find.exe. You can change this using the let
" command:
"
" :let Grep_Find_Path = 'd:\tools\find.exe'
"
" The 'Grep_Xargs_Path' variable is used to locate the xargs utility. By
" default, this is set to xargs. You can change this using the let
" command:
"
" :let Grep_Xargs_Path = 'd:\tools\xargs.exe'
"
" When running any one of the Grep commands, you will be prompted for the
" files in which to search for the pattern. The 'Grep_Default_Filelist'
" variable is used to specify to default for this prompt. By default, this
" variable is set to '*'. You can specify multiple matching patterns separated
" by spaces. You can change this settings using the let command:
"
" :let Grep_Default_Filelist = '*.[chS]'
" :let Grep_Default_Filelist = '*.c *.cpp *.asm'
"
" The 'Grep_Default_Options' is used to pass default command line options to
" the grep/fgrep/egrep/agrep utilities. By default, this is set to an empty
" string. You can change this using the let command:
"
" :let Grep_Default_Options = '-i'
"
" The 'Grep_Skip_Dirs' variable specifies the list of directories to skip
" while doing recursive searches. By default, this is set to 'RCS CVS SCCS'.
" You can change this using the let command:
"
" :let Grep_Skip_Dirs = 'dir1 dir2 dir3'
"
" The 'Grep_Skip_Files' variable specifies the list of files to skip while
" doing recursive searches. By default, this is set to '*~ *,v s.*'. You can
" change this using the let command:
"
" :let Grep_Skip_Files = '*.bak *~'
"
" By default, when you invoke the Grep commands the quickfix window will be
" opened with the grep output. You can disable opening the quickfix window,
" by setting the 'Grep_OpenQuickfixWindow' variable to zero:
"
" :let Grep_OpenQuickfixWindow = 0
"
" You can manually open the quickfix window using the :cwindow command.
"
" By default, for recursive searches, the 'find' and 'xargs' utilities are
" used. If you don't have the 'xargs' utility or don't want to use the
" 'xargs' utility, " then you can set the 'Grep_Find_Use_Xargs' variable to
" zero. If this is set to zero, then only the 'find' utility is used for
" recursive searches:
"
" :let Grep_Find_Use_Xargs = 0
"
" To handle file names with space characters in them, the xargs utility
" is invoked with the '--null' argument. If the xargs utility in your system
" doesn't accept the '--null' argument, then you can change the
" Grep_Xargs_Options variable. For example, to use the '--print0' xargs
" argument, you can use the following command:
"
" :let Grep_Xargs_Options = '--print0'
"
" The Grep_Cygwin_Find variable should be set to 1, if you are using the find
" utility from the cygwin package. This setting is used to handle the
" difference between the backslash and forward slash path separators.
"
" :let Grep_Cygwin_Find = 1
"
" The 'Grep_Null_Device' variable specifies the name of the null device to
" pass to the grep commands. This is needed to force the grep commands to
" print the name of the file in which a match is found, if only one filename
" is specified. For Unix systems, this is set to /dev/null and for MS-Windows
" systems, this is set to NUL. You can modify this by using the let command:
"
" :let Grep_Null_Device = '/dev/null'
"
" The 'Grep_Shell_Quote_Char' variable specifies the quote character to use
" for protecting patterns from being interpreted by the shell. For Unix
" systems, this is set to "'" and for MS-Window systems, this is set to an
" empty string. You can change this using the let command:
"
" :let Grep_Shell_Quote_Char = "'"
"
" The 'Grep_Shell_Escape_Char' variable specifies the escape character to use
" for protecting special characters from being interpreted by the shell. For
" Unix systems, this is set to '\' and for MS-Window systems, this is set to
" an empty string. You can change this using the let command:
"
" :let Grep_Shell_Escape_Char = "'"
"
" --------------------- Do not modify after this line ---------------------
if exists("loaded_grep")
finish
endif
let loaded_grep = 1
" Line continuation used here
let s:cpo_save = &cpo
set cpo&vim
" Location of the grep utility
if !exists("Grep_Path")
let Grep_Path = 'grep'
endif
" Location of the fgrep utility
if !exists("Fgrep_Path")
let Fgrep_Path = 'fgrep'
endif
" Location of the egrep utility
if !exists("Egrep_Path")
let Egrep_Path = 'egrep'
endif
" Location of the agrep utility
if !exists("Agrep_Path")
let Agrep_Path = 'agrep'
endif
" Location of the find utility
if !exists("Grep_Find_Path")
let Grep_Find_Path = 'find'
endif
" Location of the xargs utility
if !exists("Grep_Xargs_Path")
let Grep_Xargs_Path = 'xargs'
endif
" Open the Grep output window. Set this variable to zero, to not open
" the Grep output window by default. You can open it manually by using
" the :cwindow command.
if !exists("Grep_OpenQuickfixWindow")
let Grep_OpenQuickfixWindow = 1
endif
" Default grep file list
if !exists("Grep_Default_Filelist")
let Grep_Default_Filelist = '*'
endif
" Default grep options
if !exists("Grep_Default_Options")
let Grep_Default_Options = ''
endif
" Use the 'xargs' utility in combination with the 'find' utility. Set this
" to zero to not use the xargs utility.
if !exists("Grep_Find_Use_Xargs")
let Grep_Find_Use_Xargs = 1
endif
" The command-line arguments to supply to the xargs utility
if !exists('Grep_Xargs_Options')
let Grep_Xargs_Options = '--null'
endif
" The find utility is from the cygwin package or some other find utility.
if !exists("Grep_Cygwin_Find")
let Grep_Cygwin_Find = 0
endif
" NULL device name to supply to grep. We need this because, grep will not
" print the name of the file, if only one filename is supplied. We need the
" filename for Vim quickfix processing.
if !exists("Grep_Null_Device")
if has("win32") || has("win16") || has("win95")
let Grep_Null_Device = 'NUL'
else
let Grep_Null_Device = '/dev/null'
endif
endif
" Character to use to quote patterns and filenames before passing to grep.
if !exists("Grep_Shell_Quote_Char")
if has("win32") || has("win16") || has("win95")
let Grep_Shell_Quote_Char = ''
else
let Grep_Shell_Quote_Char = "'"
endif
endif
" Character to use to escape special characters before passing to grep.
if !exists("Grep_Shell_Escape_Char")
if has("win32") || has("win16") || has("win95")
let Grep_Shell_Escape_Char = ''
else
let Grep_Shell_Escape_Char = '\'
endif
endif
" The list of directories to skip while searching for a pattern. Set this
" variable to '', if you don't want to skip directories.
if !exists("Grep_Skip_Dirs")
let Grep_Skip_Dirs = 'RCS CVS SCCS'
endif
" The list of files to skip while searching for a pattern. Set this variable
" to '', if you don't want to skip any files.
if !exists("Grep_Skip_Files")
let Grep_Skip_Files = '*~ *,v s.*'
endif
" RunGrepCmd()
" Run the specified grep command using the supplied pattern
function! s:RunGrepCmd(cmd, pattern, action)
let cmd_output = system(a:cmd)
if cmd_output == ""
echohl WarningMsg |
\ echomsg "Error: Pattern " . a:pattern . " not found" |
\ echohl None
return
endif
let tmpfile = tempname()
let old_verbose = &verbose
set verbose&vim
exe "redir! > " . tmpfile
silent echon '[Search results for pattern: ' . a:pattern . "]\n"
silent echon cmd_output
redir END
let &verbose = old_verbose
let old_efm = &efm
set efm=%f:%\\s%#%l:%m
if v:version >= 700 && a:action == 'add'
execute "silent! caddfile " . tmpfile
else
if exists(":cgetfile")
execute "silent! cgetfile " . tmpfile
else
execute "silent! cfile " . tmpfile
endif
endif
let &efm = old_efm
" Open the grep output window
if g:Grep_OpenQuickfixWindow == 1
" Open the quickfix window below the current window
botright copen
endif
call delete(tmpfile)
endfunction
" RunGrepRecursive()
" Run specified grep command recursively
function! s:RunGrepRecursive(cmd_name, grep_cmd, action, ...)
if a:0 > 0 && (a:1 == "-?" || a:1 == "-h")
echo 'Usage: ' . a:cmd_name . " [<grep_options>] [<search_pattern> " .
\ "[<file_name(s)>]]"
return
endif
let grep_opt = ""
let pattern = ""
let filepattern = ""
let argcnt = 1
while argcnt <= a:0
if a:{argcnt} =~ '^-'
let grep_opt = grep_opt . " " . a:{argcnt}
elseif pattern == ""
let pattern = g:Grep_Shell_Quote_Char . a:{argcnt} .
\ g:Grep_Shell_Quote_Char
else
let filepattern = filepattern . " " . a:{argcnt}
endif
let argcnt= argcnt + 1
endwhile
if grep_opt == ""
let grep_opt = g:Grep_Default_Options
endif
if a:grep_cmd != 'agrep'
" Don't display messages about non-existent files
" Agrep doesn't support the -s option
let grep_opt = grep_opt . " -s"
endif
if a:grep_cmd == 'grep'
let grep_path = g:Grep_Path
let grep_expr_option = '--'
elseif a:grep_cmd == 'fgrep'
let grep_path = g:Fgrep_Path
let grep_expr_option = '-e'
elseif a:grep_cmd == 'egrep'
let grep_path = g:Egrep_Path
let grep_expr_option = '-e'
elseif a:grep_cmd == 'agrep'
let grep_path = g:Agrep_Path
let grep_expr_option = ''
else
return
endif
" No argument supplied. Get the identifier and file list from user
if pattern == ""
let pattern = input("Search for pattern: ", expand("<cword>"))
if pattern == ""
return
endif
let pattern = g:Grep_Shell_Quote_Char . pattern .
\ g:Grep_Shell_Quote_Char
endif
let cwd = getcwd()
if g:Grep_Cygwin_Find == 1
let cwd = substitute(cwd, "\\", "/", "g")
endif
if v:version >= 700
let startdir = input("Start searching from directory: ", cwd, "dir")
else
let startdir = input("Start searching from directory: ", cwd)
endif
if startdir == ""
return
endif
if filepattern == ""
let filepattern = input("Search in files matching pattern: ",
\ g:Grep_Default_Filelist)
if filepattern == ""
return
endif
endif
let txt = filepattern . ' '
let find_file_pattern = ''
while txt != ''
let one_pattern = strpart(txt, 0, stridx(txt, ' '))
if find_file_pattern != ''
let find_file_pattern = find_file_pattern . ' -o'
endif
let find_file_pattern = find_file_pattern . ' -name ' .
\ g:Grep_Shell_Quote_Char . one_pattern . g:Grep_Shell_Quote_Char
let txt = strpart(txt, stridx(txt, ' ') + 1)
endwhile
let find_file_pattern = g:Grep_Shell_Escape_Char . '(' .
\ find_file_pattern . ' ' . g:Grep_Shell_Escape_Char . ')'
let txt = g:Grep_Skip_Dirs
let find_prune = ''
if txt != ''
let txt = txt . ' '
while txt != ''
let one_dir = strpart(txt, 0, stridx(txt, ' '))
if find_prune != ''
let find_prune = find_prune . ' -o'
endif
let find_prune = find_prune . ' -name ' . one_dir
let txt = strpart(txt, stridx(txt, ' ') + 1)
endwhile
let find_prune = '-type d ' . g:Grep_Shell_Escape_Char . '(' .
\ find_prune
let find_prune = find_prune . ' ' . g:Grep_Shell_Escape_Char . ')'
endif
let txt = g:Grep_Skip_Files
let find_skip_files = '-type f'
if txt != ''
let txt = txt . ' '
while txt != ''
let one_file = strpart(txt, 0, stridx(txt, ' '))
let find_skip_files = find_skip_files . ' ! -name ' .
\ g:Grep_Shell_Quote_Char . one_file .
\ g:Grep_Shell_Quote_Char
let txt = strpart(txt, stridx(txt, ' ') + 1)
endwhile
endif
if g:Grep_Find_Use_Xargs == 1
let cmd = g:Grep_Find_Path . " " . startdir
let cmd = cmd . " " . find_prune . " -prune -o"
let cmd = cmd . " " . find_skip_files
let cmd = cmd . " " . find_file_pattern
let cmd = cmd . " -print0 | "
let cmd = cmd . g:Grep_Xargs_Path . ' ' . g:Grep_Xargs_Options
let cmd = cmd . ' ' . grep_path . " " . grep_opt . " -n "
let cmd = cmd . grep_expr_option . " " . pattern
let cmd = cmd . ' ' . g:Grep_Null_Device
else
let cmd = g:Grep_Find_Path . " " . startdir
let cmd = cmd . " " . find_prune . " -prune -o"
let cmd = cmd . " " . find_skip_files
let cmd = cmd . " " . find_file_pattern
let cmd = cmd . " -exec " . grep_path . " " . grep_opt . " -n "
let cmd = cmd . grep_expr_option . " " . pattern
let cmd = cmd . " {} " . g:Grep_Null_Device . ' ' .
\ g:Grep_Shell_Escape_Char . ';'
endif
call s:RunGrepCmd(cmd, pattern, a:action)
endfunction
" RunGrepSpecial()
" Search for a pattern in all the opened buffers or filenames in the
" argument list
function! s:RunGrepSpecial(cmd_name, which, action, ...)
if a:0 > 0 && (a:1 == "-?" || a:1 == "-h")
echo 'Usage: ' . a:cmd_name . " [<grep_options>] [<search_pattern>]"
return
endif
" Search in all the Vim buffers
if a:which == 'buffer'
" Get a list of all the buffer names
let last_bufno = bufnr("$")
let i = 1
let filenames = ""
while i <= last_bufno
if bufexists(i) && buflisted(i)
let filenames = filenames . " " . bufname(i)
endif
let i = i + 1
endwhile
" No buffers
if filenames == ""
return
endif
elseif a:which == 'args'
" Search in all the filenames in the argument list
let arg_cnt = argc()
if arg_cnt == 0
echohl WarningMsg
echomsg "Error: Argument list is empty"
echohl None
return
endif
let i = 0
let filenames = ""
while i < arg_cnt
let filenames = filenames . " " . argv(i)
let i = i + 1
endwhile
" No arguments
if filenames == ""
echohl WarningMsg
echomsg "Error: Argument list is empty"
echohl None
return
endif
endif
let grep_opt = ""
let pattern = ""
" Get the list of optional grep command-line options (if present)
" supplied by the user. All the grep options will be preceded
" by a '-'
let argcnt= 1
while argcnt <= a:0 && a:{argcnt} =~ '^-'
let grep_opt = grep_opt . " " . a:{argcnt}
let argcnt = argcnt + 1
endwhile
" If the user didn't specify the option, then use the defaults
if grep_opt == ""
let grep_opt = g:Grep_Default_Options
endif
" Don't display messages about non-existent files
let grep_opt = grep_opt . " -s"
" The last argument specified by the user is the pattern
if argcnt == a:0
let pattern = a:{argcnt}
else
" No argument supplied. Get the identifier and file list from user
let pattern = input("Search for pattern: ", expand("<cword>"))
if pattern == ""
return
endif
endif
let pattern = g:Grep_Shell_Quote_Char . pattern . g:Grep_Shell_Quote_Char
" Add /dev/null to the list of filenames, so that grep print the
" filename and linenumber when grepping in a single file
let filenames = filenames . " " . g:Grep_Null_Device
let cmd = g:Grep_Path . " " . grep_opt . " -n -- "
let cmd = cmd . pattern . " " . filenames
call s:RunGrepCmd(cmd, pattern, a:action)
endfunction
" RunGrep()
" Run the specified grep command
function! s:RunGrep(cmd_name, grep_cmd, action, ...)
if a:0 > 0 && (a:1 == "-?" || a:1 == "-h")
echo 'Usage: ' . a:cmd_name . " [<grep_options>] [<search_pattern> " .
\ "[<file_name(s)>]]"
return
endif
let grep_opt = ""
let pattern = ""
let filenames = ""
" Parse the arguments
" grep command-line flags are specified using the "-flag" format
" the next argument is assumed to be the pattern
" and the next arguments are assumed to be filenames or file patterns
let argcnt = 1
while argcnt <= a:0
if a:{argcnt} =~ '^-'
let grep_opt = grep_opt . " " . a:{argcnt}
elseif pattern == ""
let pattern = g:Grep_Shell_Quote_Char . a:{argcnt} .
\ g:Grep_Shell_Quote_Char
else
let filenames= filenames . " " . a:{argcnt}
endif
let argcnt = argcnt + 1
endwhile
if grep_opt == ""
let grep_opt = g:Grep_Default_Options
endif
if a:grep_cmd != 'agrep'
" Don't display messages about non-existent files
" Agrep doesn't support the -s option
let grep_opt = grep_opt . " -s"
endif
if a:grep_cmd == 'grep'
let grep_path = g:Grep_Path
let grep_expr_option = '--'
elseif a:grep_cmd == 'fgrep'
let grep_path = g:Fgrep_Path
let grep_expr_option = '-e'
elseif a:grep_cmd == 'egrep'
let grep_path = g:Egrep_Path
let grep_expr_option = '-e'
elseif a:grep_cmd == 'agrep'
let grep_path = g:Agrep_Path
let grep_expr_option = ''
else
return
endif
" Get the identifier and file list from user
if pattern == ""
let pattern = input("Search for pattern: ", expand("<cword>"))
if pattern == ""
return
endif
let pattern = g:Grep_Shell_Quote_Char . pattern .
\ g:Grep_Shell_Quote_Char
endif
if filenames == ""
if v:version >= 700
let filenames = input("Search in files: ", g:Grep_Default_Filelist,
\ "file")
else
let filenames = input("Search in files: ", g:Grep_Default_Filelist)
endif
if filenames == ""
return
endif
endif
" Add /dev/null to the list of filenames, so that grep print the
" filename and linenumber when grepping in a single file
let filenames = filenames . " " . g:Grep_Null_Device
let cmd = grep_path . " " . grep_opt . " -n "
let cmd = cmd . grep_expr_option . " " . pattern
let cmd = cmd . " " . filenames
call s:RunGrepCmd(cmd, pattern, a:action)
endfunction
" Define the set of grep commands
command! -nargs=* -complete=file Grep
\ call s:RunGrep('Grep', 'grep', 'set', <f-args>)
command! -nargs=* -complete=file Rgrep
\ call s:RunGrepRecursive('Rgrep', 'grep', 'set', <f-args>)
command! -nargs=* GrepBuffer
\ call s:RunGrepSpecial('GrepBuffer', 'buffer', 'set', <f-args>)
command! -nargs=* Bgrep
\ call s:RunGrepSpecial('Bgrep', 'buffer', 'set', <f-args>)
command! -nargs=* GrepArgs
\ call s:RunGrepSpecial('GrepArgs', 'args', 'set', <f-args>)
command! -nargs=* -complete=file Fgrep
\ call s:RunGrep('Fgrep', 'fgrep', 'set', <f-args>)
command! -nargs=* -complete=file Rfgrep
\ call s:RunGrepRecursive('Rfgrep', 'fgrep', 'set', <f-args>)
command! -nargs=* -complete=file Egrep
\ call s:RunGrep('Egrep', 'egrep', 'set', <f-args>)
command! -nargs=* -complete=file Regrep
\ call s:RunGrepRecursive('Regrep', 'egrep', 'set', <f-args>)
command! -nargs=* -complete=file Agrep
\ call s:RunGrep('Agrep', 'agrep', 'set', <f-args>)
command! -nargs=* -complete=file Ragrep
\ call s:RunGrepRecursive('Ragrep', 'agrep', 'set', <f-args>)
if v:version >= 700
command! -nargs=* -complete=file GrepAdd
\ call s:RunGrep('GrepAdd', 'grep', 'add', <f-args>)
command! -nargs=* -complete=file RgrepAdd
\ call s:RunGrepRecursive('RgrepAdd', 'grep', 'add', <f-args>)
command! -nargs=* GrepBufferAdd
\ call s:RunGrepSpecial('GrepBufferAdd', 'buffer', 'add', <f-args>)
command! -nargs=* BgrepAdd
\ call s:RunGrepSpecial('BgrepAdd', 'buffer', 'add', <f-args>)
command! -nargs=* GrepArgsAdd
\ call s:RunGrepSpecial('GrepArgsAdd', 'args', 'add', <f-args>)
command! -nargs=* -complete=file FgrepAdd
\ call s:RunGrep('FgrepAdd', 'fgrep', 'add', <f-args>)
command! -nargs=* -complete=file RfgrepAdd
\ call s:RunGrepRecursive('RfgrepAdd', 'fgrep', 'add', <f-args>)
command! -nargs=* -complete=file EgrepAdd
\ call s:RunGrep('EgrepAdd', 'egrep', 'add', <f-args>)
command! -nargs=* -complete=file RegrepAdd
\ call s:RunGrepRecursive('RegrepAdd', 'egrep', 'add', <f-args>)
command! -nargs=* -complete=file AgrepAdd
\ call s:RunGrep('AgrepAdd', 'agrep', 'add', <f-args>)
command! -nargs=* -complete=file RagrepAdd
\ call s:RunGrepRecursive('RagrepAdd', 'agrep', 'add', <f-args>)
endif
" Add the Tools->Search Files menu
if has('gui_running')
anoremenu <silent> Tools.Search.Current\ Directory<Tab>:Grep
\ :Grep<CR>
anoremenu <silent> Tools.Search.Recursively<Tab>:Rgrep
\ :Rgrep<CR>
anoremenu <silent> Tools.Search.Buffer\ List<Tab>:Bgrep
\ :Bgrep<CR>
anoremenu <silent> Tools.Search.Argument\ List<Tab>:GrepArgs
\ :GrepArgs<CR>
endif
" restore 'cpo'
let &cpo = s:cpo_save
unlet s:cpo_save
-574
View File
@@ -1,574 +0,0 @@
# ============================================================================
# File: gundo.py
# Description: vim global plugin to visualize your undo tree
# Maintainer: Steve Losh <steve@stevelosh.com>
# License: GPLv2+ -- look it up.
# Notes: Much of this code was thiefed from Mercurial, and the rest was
# heavily inspired by scratch.vim and histwin.vim.
#
# ============================================================================
import difflib
import itertools
import sys
import time
import vim
# Mercurial's graphlog code --------------------------------------------------------
def asciiedges(seen, rev, parents):
"""adds edge info to changelog DAG walk suitable for ascii()"""
if rev not in seen:
seen.append(rev)
nodeidx = seen.index(rev)
knownparents = []
newparents = []
for parent in parents:
if parent in seen:
knownparents.append(parent)
else:
newparents.append(parent)
ncols = len(seen)
seen[nodeidx:nodeidx + 1] = newparents
edges = [(nodeidx, seen.index(p)) for p in knownparents]
if len(newparents) > 0:
edges.append((nodeidx, nodeidx))
if len(newparents) > 1:
edges.append((nodeidx, nodeidx + 1))
nmorecols = len(seen) - ncols
return nodeidx, edges, ncols, nmorecols
def get_nodeline_edges_tail(
node_index, p_node_index, n_columns, n_columns_diff, p_diff, fix_tail):
if fix_tail and n_columns_diff == p_diff and n_columns_diff != 0:
# Still going in the same non-vertical direction.
if n_columns_diff == -1:
start = max(node_index + 1, p_node_index)
tail = ["|", " "] * (start - node_index - 1)
tail.extend(["/", " "] * (n_columns - start))
return tail
else:
return ["\\", " "] * (n_columns - node_index - 1)
else:
return ["|", " "] * (n_columns - node_index - 1)
def draw_edges(edges, nodeline, interline):
for (start, end) in edges:
if start == end + 1:
interline[2 * end + 1] = "/"
elif start == end - 1:
interline[2 * start + 1] = "\\"
elif start == end:
interline[2 * start] = "|"
else:
nodeline[2 * end] = "+"
if start > end:
(start, end) = (end, start)
for i in range(2 * start + 1, 2 * end):
if nodeline[i] != "+":
nodeline[i] = "-"
def fix_long_right_edges(edges):
for (i, (start, end)) in enumerate(edges):
if end > start:
edges[i] = (start, end + 1)
def ascii(buf, state, type, char, text, coldata):
"""prints an ASCII graph of the DAG
takes the following arguments (one call per node in the graph):
- Somewhere to keep the needed state in (init to asciistate())
- Column of the current node in the set of ongoing edges.
- Type indicator of node data == ASCIIDATA.
- Payload: (char, lines):
- Character to use as node's symbol.
- List of lines to display as the node's text.
- Edges; a list of (col, next_col) indicating the edges between
the current node and its parents.
- Number of columns (ongoing edges) in the current revision.
- The difference between the number of columns (ongoing edges)
in the next revision and the number of columns (ongoing edges)
in the current revision. That is: -1 means one column removed;
0 means no columns added or removed; 1 means one column added.
"""
idx, edges, ncols, coldiff = coldata
assert -2 < coldiff < 2
if coldiff == -1:
# Transform
#
# | | | | | |
# o | | into o---+
# |X / |/ /
# | | | |
fix_long_right_edges(edges)
# add_padding_line says whether to rewrite
#
# | | | | | | | |
# | o---+ into | o---+
# | / / | | | # <--- padding line
# o | | | / /
# o | |
add_padding_line = (len(text) > 2 and coldiff == -1 and
[x for (x, y) in edges if x + 1 < y])
# fix_nodeline_tail says whether to rewrite
#
# | | o | | | | o | |
# | | |/ / | | |/ /
# | o | | into | o / / # <--- fixed nodeline tail
# | |/ / | |/ /
# o | | o | |
fix_nodeline_tail = len(text) <= 2 and not add_padding_line
# nodeline is the line containing the node character (typically o)
nodeline = ["|", " "] * idx
nodeline.extend([char, " "])
nodeline.extend(
get_nodeline_edges_tail(idx, state[1], ncols, coldiff,
state[0], fix_nodeline_tail))
# shift_interline is the line containing the non-vertical
# edges between this entry and the next
shift_interline = ["|", " "] * idx
if coldiff == -1:
n_spaces = 1
edge_ch = "/"
elif coldiff == 0:
n_spaces = 2
edge_ch = "|"
else:
n_spaces = 3
edge_ch = "\\"
shift_interline.extend(n_spaces * [" "])
shift_interline.extend([edge_ch, " "] * (ncols - idx - 1))
# draw edges from the current node to its parents
draw_edges(edges, nodeline, shift_interline)
# lines is the list of all graph lines to print
lines = [nodeline]
if add_padding_line:
lines.append(get_padding_line(idx, ncols, edges))
lines.append(shift_interline)
# make sure that there are as many graph lines as there are
# log strings
while len(text) < len(lines):
text.append("")
if len(lines) < len(text):
extra_interline = ["|", " "] * (ncols + coldiff)
while len(lines) < len(text):
lines.append(extra_interline)
# print lines
indentation_level = max(ncols, ncols + coldiff)
for (line, logstr) in zip(lines, text):
ln = "%-*s %s" % (2 * indentation_level, "".join(line), logstr)
buf.write(ln.rstrip() + '\n')
# ... and start over
state[0] = coldiff
state[1] = idx
def generate(dag, edgefn, current):
seen, state = [], [0, 0]
buf = Buffer()
for node, parents in list(dag):
if node.time:
age_label = age(int(node.time))
else:
age_label = 'Original'
line = '[%s] %s' % (node.n, age_label)
if node.n == current:
char = '@'
else:
char = 'o'
ascii(buf, state, 'C', char, [line], edgefn(seen, node, parents))
return buf.b
# Mercurial age function -----------------------------------------------------------
agescales = [("year", 3600 * 24 * 365),
("month", 3600 * 24 * 30),
("week", 3600 * 24 * 7),
("day", 3600 * 24),
("hour", 3600),
("minute", 60),
("second", 1)]
def age(ts):
'''turn a timestamp into an age string.'''
def plural(t, c):
if c == 1:
return t
return t + "s"
def fmt(t, c):
return "%d %s" % (c, plural(t, c))
now = time.time()
then = ts
if then > now:
return 'in the future'
delta = max(1, int(now - then))
if delta > agescales[0][1] * 2:
return time.strftime('%Y-%m-%d', time.gmtime(float(ts)))
for t, s in agescales:
n = delta // s
if n >= 2 or s == 1:
return '%s ago' % fmt(t, n)
# Python Vim utility functions -----------------------------------------------------
normal = lambda s: vim.command('normal %s' % s)
MISSING_BUFFER = "Cannot find Gundo's target buffer (%s)"
MISSING_WINDOW = "Cannot find window (%s) for Gundo's target buffer (%s)"
def _check_sanity():
'''Check to make sure we're not crazy.
Does the following things:
* Make sure the target buffer still exists.
'''
b = int(vim.eval('g:gundo_target_n'))
if not vim.eval('bufloaded(%d)' % b):
vim.command('echo "%s"' % (MISSING_BUFFER % b))
return False
w = int(vim.eval('bufwinnr(%d)' % b))
if w == -1:
vim.command('echo "%s"' % (MISSING_WINDOW % (w, b)))
return False
return True
def _goto_window_for_buffer(b):
w = int(vim.eval('bufwinnr(%d)' % int(b)))
vim.command('%dwincmd w' % w)
def _goto_window_for_buffer_name(bn):
b = vim.eval('bufnr("%s")' % bn)
return _goto_window_for_buffer(b)
def _undo_to(n):
n = int(n)
if n == 0:
vim.command('silent earlier %s' % (int(vim.eval('&undolevels')) + 1))
else:
vim.command('silent undo %d' % n)
INLINE_HELP = '''\
" Gundo for %s (%d)
" j/k - move between undo states
" p - preview diff of selected and current states
" <cr> - revert to selected state
'''
# Python undo tree data structures and functions -----------------------------------
class Buffer(object):
def __init__(self):
self.b = ''
def write(self, s):
self.b += s
class Node(object):
def __init__(self, n, parent, time, curhead):
self.n = int(n)
self.parent = parent
self.children = []
self.curhead = curhead
self.time = time
def _make_nodes(alts, nodes, parent=None):
p = parent
for alt in alts:
curhead = 'curhead' in alt
node = Node(n=alt['seq'], parent=p, time=alt['time'], curhead=curhead)
nodes.append(node)
if alt.get('alt'):
_make_nodes(alt['alt'], nodes, p)
p = node
def make_nodes():
ut = vim.eval('undotree()')
entries = ut['entries']
root = Node(0, None, False, 0)
nodes = []
_make_nodes(entries, nodes, root)
nodes.append(root)
nmap = dict((node.n, node) for node in nodes)
return nodes, nmap
def changenr(nodes):
_curhead_l = list(itertools.dropwhile(lambda n: not n.curhead, nodes))
if _curhead_l:
current = _curhead_l[0].parent.n
else:
current = int(vim.eval('changenr()'))
return current
# Gundo rendering ------------------------------------------------------------------
# Rendering utility functions
def _fmt_time(t):
return time.strftime('%Y-%m-%d %I:%M:%S %p', time.localtime(float(t)))
def _output_preview_text(lines):
_goto_window_for_buffer_name('__Gundo_Preview__')
vim.command('setlocal modifiable')
vim.current.buffer[:] = lines
vim.command('setlocal nomodifiable')
def _generate_preview_diff(current, node_before, node_after):
_goto_window_for_buffer(vim.eval('g:gundo_target_n'))
if not node_after.n: # we're at the original file
before_lines = []
_undo_to(0)
after_lines = vim.current.buffer[:]
before_name = 'n/a'
before_time = ''
after_name = 'Original'
after_time = ''
elif not node_before.n: # we're at a pseudo-root state
_undo_to(0)
before_lines = vim.current.buffer[:]
_undo_to(node_after.n)
after_lines = vim.current.buffer[:]
before_name = 'Original'
before_time = ''
after_name = node_after.n
after_time = _fmt_time(node_after.time)
else:
_undo_to(node_before.n)
before_lines = vim.current.buffer[:]
_undo_to(node_after.n)
after_lines = vim.current.buffer[:]
before_name = node_before.n
before_time = _fmt_time(node_before.time)
after_name = node_after.n
after_time = _fmt_time(node_after.time)
_undo_to(current)
return list(difflib.unified_diff(before_lines, after_lines,
before_name, after_name,
before_time, after_time))
def _generate_change_preview_diff(current, node_before, node_after):
_goto_window_for_buffer(vim.eval('g:gundo_target_n'))
_undo_to(node_before.n)
before_lines = vim.current.buffer[:]
_undo_to(node_after.n)
after_lines = vim.current.buffer[:]
before_name = node_before.n or 'Original'
before_time = node_before.time and _fmt_time(node_before.time) or ''
after_name = node_after.n or 'Original'
after_time = node_after.time and _fmt_time(node_after.time) or ''
_undo_to(current)
return list(difflib.unified_diff(before_lines, after_lines,
before_name, after_name,
before_time, after_time))
def GundoRenderGraph():
if not _check_sanity():
return
nodes, nmap = make_nodes()
for node in nodes:
node.children = [n for n in nodes if n.parent == node]
def walk_nodes(nodes):
for node in nodes:
if node.parent:
yield (node, [node.parent])
else:
yield (node, [])
dag = sorted(nodes, key=lambda n: int(n.n), reverse=True)
current = changenr(nodes)
result = generate(walk_nodes(dag), asciiedges, current).rstrip().splitlines()
result = [' ' + l for l in result]
target = (vim.eval('g:gundo_target_f'), int(vim.eval('g:gundo_target_n')))
if int(vim.eval('g:gundo_help')):
header = (INLINE_HELP % target).splitlines()
else:
header = []
vim.command('call s:GundoOpenGraph()')
vim.command('setlocal modifiable')
vim.current.buffer[:] = (header + result)
vim.command('setlocal nomodifiable')
i = 1
for line in result:
try:
line.split('[')[0].index('@')
i += 1
break
except ValueError:
pass
i += 1
vim.command('%d' % (i+len(header)-1))
def GundoRenderPreview():
if not _check_sanity():
return
target_state = vim.eval('s:GundoGetTargetState()')
# Check that there's an undo state. There may not be if we're talking about
# a buffer with no changes yet.
if target_state == None:
_goto_window_for_buffer_name('__Gundo__')
return
else:
target_state = int(target_state)
_goto_window_for_buffer(vim.eval('g:gundo_target_n'))
nodes, nmap = make_nodes()
current = changenr(nodes)
node_after = nmap[target_state]
node_before = node_after.parent
vim.command('call s:GundoOpenPreview()')
_output_preview_text(_generate_preview_diff(current, node_before, node_after))
_goto_window_for_buffer_name('__Gundo__')
def GundoRenderChangePreview():
if not _check_sanity():
return
target_state = vim.eval('s:GundoGetTargetState()')
# Check that there's an undo state. There may not be if we're talking about
# a buffer with no changes yet.
if target_state == None:
_goto_window_for_buffer_name('__Gundo__')
return
else:
target_state = int(target_state)
_goto_window_for_buffer(vim.eval('g:gundo_target_n'))
nodes, nmap = make_nodes()
current = changenr(nodes)
node_after = nmap[target_state]
node_before = nmap[current]
vim.command('call s:GundoOpenPreview()')
_output_preview_text(_generate_change_preview_diff(current, node_before, node_after))
_goto_window_for_buffer_name('__Gundo__')
# Gundo undo/redo
def GundoRevert():
if not _check_sanity():
return
target_n = int(vim.eval('s:GundoGetTargetState()'))
back = vim.eval('g:gundo_target_n')
_goto_window_for_buffer(back)
_undo_to(target_n)
vim.command('GundoRenderGraph')
_goto_window_for_buffer(back)
if int(vim.eval('g:gundo_close_on_revert')):
vim.command('GundoToggle')
def GundoPlayTo():
if not _check_sanity():
return
target_n = int(vim.eval('s:GundoGetTargetState()'))
back = int(vim.eval('g:gundo_target_n'))
vim.command('echo "%s"' % back)
_goto_window_for_buffer(back)
normal('zR')
nodes, nmap = make_nodes()
start = nmap[changenr(nodes)]
end = nmap[target_n]
def _walk_branch(origin, dest):
rev = origin.n < dest.n
nodes = []
if origin.n > dest.n:
current, final = origin, dest
else:
current, final = dest, origin
while current.n >= final.n:
if current.n == final.n:
break
nodes.append(current)
current = current.parent
else:
return None
nodes.append(current)
return reversed(nodes) if rev else nodes
branch = _walk_branch(start, end)
if not branch:
vim.command('unsilent echo "No path to that node from here!"')
return
for node in branch:
_undo_to(node.n)
vim.command('GundoRenderGraph')
normal('zz')
_goto_window_for_buffer(back)
vim.command('redraw')
vim.command('sleep 60m')
def initPythonModule():
if sys.version_info[:2] < (2, 4):
vim.command('let s:has_supported_python = 0')
-401
View File
@@ -1,401 +0,0 @@
" ============================================================================
" File: gundo.vim
" Description: vim global plugin to visualize your undo tree
" Maintainer: Steve Losh <steve@stevelosh.com>
" License: GPLv2+ -- look it up.
" Notes: Much of this code was thiefed from Mercurial, and the rest was
" heavily inspired by scratch.vim and histwin.vim.
"
" ============================================================================
"{{{ Init
if !exists('g:gundo_debug') && (exists('g:gundo_disable') || exists('loaded_gundo') || &cp)"{{{
finish
endif
let loaded_gundo = 1"}}}
if v:version < '703'"{{{
function! s:GundoDidNotLoad()
echohl WarningMsg|echomsg "Gundo unavailable: requires Vim 7.3+"|echohl None
endfunction
command! -nargs=0 GundoToggle call s:GundoDidNotLoad()
finish
endif"}}}
if has('python')"{{{
let s:has_supported_python = 1
else
let s:has_supported_python = 0
endif
if !s:has_supported_python
function! s:GundoDidNotLoad()
echohl WarningMsg|echomsg "Gundo requires Vim to be compiled with Python 2.4+"|echohl None
endfunction
command! -nargs=0 GundoToggle call s:GundoDidNotLoad()
finish
endif"}}}
let s:plugin_path = escape(expand('<sfile>:p:h'), '\')
if !exists('g:gundo_width')"{{{
let g:gundo_width = 45
endif"}}}
if !exists('g:gundo_preview_height')"{{{
let g:gundo_preview_height = 15
endif"}}}
if !exists('g:gundo_preview_bottom')"{{{
let g:gundo_preview_bottom = 0
endif"}}}
if !exists('g:gundo_right')"{{{
let g:gundo_right = 0
endif"}}}
if !exists('g:gundo_help')"{{{
let g:gundo_help = 1
endif"}}}
if !exists("g:gundo_map_move_older")"{{{
let g:gundo_map_move_older = 'j'
endif"}}}
if !exists("g:gundo_map_move_newer")"{{{
let g:gundo_map_move_newer = 'k'
endif"}}}
if !exists("g:gundo_close_on_revert")"{{{
let g:gundo_close_on_revert = 0
endif"}}}
"}}}
"{{{ Gundo utility functions
function! s:GundoGetTargetState()"{{{
let target_line = matchstr(getline("."), '\v\[[0-9]+\]')
return matchstr(target_line, '\v[0-9]+')
endfunction"}}}
function! s:GundoGoToWindowForBufferName(name)"{{{
if bufwinnr(bufnr(a:name)) != -1
exe bufwinnr(bufnr(a:name)) . "wincmd w"
return 1
else
return 0
endif
endfunction"}}}
function! s:GundoIsVisible()"{{{
if bufwinnr(bufnr("__Gundo__")) != -1 || bufwinnr(bufnr("__Gundo_Preview__")) != -1
return 1
else
return 0
endif
endfunction"}}}
function! s:GundoInlineHelpLength()"{{{
if g:gundo_help
return 6
else
return 0
endif
endfunction"}}}
"}}}
"{{{ Gundo buffer settings
function! s:GundoMapGraph()"{{{
exec 'nnoremap <script> <silent> <buffer> ' . g:gundo_map_move_older . " :call <sid>GundoMove(1)<CR>"
exec 'nnoremap <script> <silent> <buffer> ' . g:gundo_map_move_newer . " :call <sid>GundoMove(-1)<CR>"
nnoremap <script> <silent> <buffer> <CR> :call <sid>GundoRevert()<CR>
nnoremap <script> <silent> <buffer> o :call <sid>GundoRevert()<CR>
nnoremap <script> <silent> <buffer> <down> :call <sid>GundoMove(1)<CR>
nnoremap <script> <silent> <buffer> <up> :call <sid>GundoMove(-1)<CR>
nnoremap <script> <silent> <buffer> gg gg:call <sid>GundoMove(1)<CR>
nnoremap <script> <silent> <buffer> P :call <sid>GundoPlayTo()<CR>
nnoremap <script> <silent> <buffer> p :call <sid>GundoRenderChangePreview()<CR>
nnoremap <script> <silent> <buffer> q :call <sid>GundoClose()<CR>
cabbrev <script> <silent> <buffer> q call <sid>GundoClose()
cabbrev <script> <silent> <buffer> quit call <sid>GundoClose()
nnoremap <script> <silent> <buffer> <2-LeftMouse> :call <sid>GundoMouseDoubleClick()<CR>
endfunction"}}}
function! s:GundoMapPreview()"{{{
nnoremap <script> <silent> <buffer> q :call <sid>GundoClose()<CR>
cabbrev <script> <silent> <buffer> q call <sid>GundoClose()
cabbrev <script> <silent> <buffer> quit call <sid>GundoClose()
endfunction"}}}
function! s:GundoSettingsGraph()"{{{
setlocal buftype=nofile
setlocal bufhidden=hide
setlocal noswapfile
setlocal nobuflisted
setlocal nomodifiable
setlocal filetype=gundo
setlocal nolist
setlocal nonumber
setlocal norelativenumber
setlocal nowrap
call s:GundoSyntaxGraph()
call s:GundoMapGraph()
endfunction"}}}
function! s:GundoSettingsPreview()"{{{
setlocal buftype=nofile
setlocal bufhidden=hide
setlocal noswapfile
setlocal nobuflisted
setlocal nomodifiable
setlocal filetype=diff
setlocal nonumber
setlocal norelativenumber
setlocal nowrap
setlocal foldlevel=20
setlocal foldmethod=diff
call s:GundoMapPreview()
endfunction"}}}
function! s:GundoSyntaxGraph()"{{{
let b:current_syntax = 'gundo'
syn match GundoCurrentLocation '@'
syn match GundoHelp '\v^".*$'
syn match GundoNumberField '\v\[[0-9]+\]'
syn match GundoNumber '\v[0-9]+' contained containedin=GundoNumberField
hi def link GundoCurrentLocation Keyword
hi def link GundoHelp Comment
hi def link GundoNumberField Comment
hi def link GundoNumber Identifier
endfunction"}}}
"}}}
"{{{ Gundo buffer/window management
function! s:GundoResizeBuffers(backto)"{{{
call s:GundoGoToWindowForBufferName('__Gundo__')
exe "vertical resize " . g:gundo_width
call s:GundoGoToWindowForBufferName('__Gundo_Preview__')
exe "resize " . g:gundo_preview_height
exe a:backto . "wincmd w"
endfunction"}}}
function! s:GundoOpenGraph()"{{{
let existing_gundo_buffer = bufnr("__Gundo__")
if existing_gundo_buffer == -1
call s:GundoGoToWindowForBufferName('__Gundo_Preview__')
exe "new __Gundo__"
if g:gundo_preview_bottom
if g:gundo_right
wincmd L
else
wincmd H
endif
endif
call s:GundoResizeBuffers(winnr())
else
let existing_gundo_window = bufwinnr(existing_gundo_buffer)
if existing_gundo_window != -1
if winnr() != existing_gundo_window
exe existing_gundo_window . "wincmd w"
endif
else
call s:GundoGoToWindowForBufferName('__Gundo_Preview__')
if g:gundo_preview_bottom
if g:gundo_right
exe "botright vsplit +buffer" . existing_gundo_buffer
else
exe "topleft vsplit +buffer" . existing_gundo_buffer
endif
else
exe "split +buffer" . existing_gundo_buffer
endif
call s:GundoResizeBuffers(winnr())
endif
endif
endfunction"}}}
function! s:GundoOpenPreview()"{{{
let existing_preview_buffer = bufnr("__Gundo_Preview__")
if existing_preview_buffer == -1
if g:gundo_preview_bottom
exe "botright new __Gundo_Preview__"
else
if g:gundo_right
exe "botright vnew __Gundo_Preview__"
else
exe "topleft vnew __Gundo_Preview__"
endif
endif
else
let existing_preview_window = bufwinnr(existing_preview_buffer)
if existing_preview_window != -1
if winnr() != existing_preview_window
exe existing_preview_window . "wincmd w"
endif
else
if g:gundo_preview_bottom
exe "botright split +buffer" . existing_preview_buffer
else
if g:gundo_right
exe "botright vsplit +buffer" . existing_preview_buffer
else
exe "topleft vsplit +buffer" . existing_preview_buffer
endif
endif
endif
endif
endfunction"}}}
function! s:GundoClose()"{{{
if s:GundoGoToWindowForBufferName('__Gundo__')
quit
endif
if s:GundoGoToWindowForBufferName('__Gundo_Preview__')
quit
endif
exe bufwinnr(g:gundo_target_n) . "wincmd w"
endfunction"}}}
function! s:GundoOpen()"{{{
if !exists('g:gundo_py_loaded')
exe 'pyfile ' . s:plugin_path . '/gundo.py'
python initPythonModule()
if !s:has_supported_python
function! s:GundoDidNotLoad()
echohl WarningMsg|echomsg "Gundo unavailable: requires Vim 7.3+"|echohl None
endfunction
command! -nargs=0 GundoToggle call s:GundoDidNotLoad()
call s:GundoDidNotLoad()
return
endif"
let g:gundo_py_loaded = 1
endif
" Save `splitbelow` value and set it to default to avoid problems with
" positioning new windows.
let saved_splitbelow = &splitbelow
let &splitbelow = 0
call s:GundoOpenPreview()
exe bufwinnr(g:gundo_target_n) . "wincmd w"
call s:GundoRenderGraph()
call s:GundoRenderPreview()
" Restore `splitbelow` value.
let &splitbelow = saved_splitbelow
endfunction"}}}
function! s:GundoToggle()"{{{
if s:GundoIsVisible()
call s:GundoClose()
else
let g:gundo_target_n = bufnr('')
let g:gundo_target_f = @%
call s:GundoOpen()
endif
endfunction"}}}
"}}}
"{{{ Gundo mouse handling
function! s:GundoMouseDoubleClick()"{{{
let start_line = getline('.')
if stridx(start_line, '[') == -1
return
else
call s:GundoRevert()
endif
endfunction"}}}
"}}}
"{{{ Gundo movement
function! s:GundoMove(direction) range"{{{
let start_line = getline('.')
if v:count1 == 0
let move_count = 1
else
let move_count = v:count1
endif
let distance = 2 * move_count
" If we're in between two nodes we move by one less to get back on track.
if stridx(start_line, '[') == -1
let distance = distance - 1
endif
let target_n = line('.') + (distance * a:direction)
" Bound the movement to the graph.
if target_n <= s:GundoInlineHelpLength() - 1
call cursor(s:GundoInlineHelpLength(), 0)
else
call cursor(target_n, 0)
endif
let line = getline('.')
" Move to the node, whether it's an @ or an o
let idx1 = stridx(line, '@')
let idx2 = stridx(line, 'o')
if idx1 != -1
call cursor(0, idx1 + 1)
else
call cursor(0, idx2 + 1)
endif
call s:GundoRenderPreview()
endfunction"}}}
"}}}
"{{{ Gundo rendering
function! s:GundoRenderGraph()"{{{
python GundoRenderGraph()
endfunction"}}}
function! s:GundoRenderPreview()"{{{
python GundoRenderPreview()
endfunction"}}}
function! s:GundoRenderChangePreview()"{{{
python GundoRenderChangePreview()
endfunction"}}}
"}}}
"{{{ Gundo undo/redo
function! s:GundoRevert()"{{{
python GundoRevert()
endfunction"}}}
function! s:GundoPlayTo()"{{{
python GundoPlayTo()
endfunction"}}}
"}}}
"{{{ Misc
command! -nargs=0 GundoToggle call s:GundoToggle()
command! -nargs=0 GundoRenderGraph call s:GundoRenderGraph()
autocmd BufNewFile __Gundo__ call s:GundoSettingsGraph()
autocmd BufNewFile __Gundo_Preview__ call s:GundoSettingsPreview()
"}}}
-623
View File
@@ -1,623 +0,0 @@
if &cp || exists("loaded_jsbeautify")
finish
endif
let loaded_jsbeautify = 3
function! s:trim_output()
while len(s:output) > 0 && (s:output[len(s:output)-1] == " " || s:output[len(s:output)-1] == s:indent_string)
call remove(s:output, -1)
endwhile
endfunction
function! s:print_newline(ignore_repeated)
let s:if_line_flag = 0
call s:trim_output()
if len(s:output)==0
return
endif
if s:output[len(s:output)-1] != "\n" || !a:ignore_repeated
call add(s:output, "\n")
endif
let index = 0
while index < s:indent_level
call add(s:output, s:indent_string)
let index += 1
endwhile
endfunction
function! s:print_space()
let last_output = " "
if len(s:output) > 0
let last_output = s:output[len(s:output) - 1]
endif
if last_output != " " && last_output != "\n" && last_output != s:indent_string
call add(s:output, " ")
endif
endfunction
function! s:print_token()
call add(s:output, s:token_text)
endfunctio
function! s:indent()
let s:indent_level += 1
endfunction
function! s:unindent()
if s:indent_level
let s:indent_level -= 1
endif
endfunction
function! s:remove_indent()
if len(s:output)>0 && s:output[len(s:output) -1] == s:indent_string
call remove(s:output, -1)
endif
endfunction
function! s:set_mode(mode)
call add(s:modes, s:current_mode)
let s:current_mode = a:mode
endfunction
function! s:restore_mode()
if s:current_mode == "DO_BLOCK"
let s:do_block_just_closed = 1
else
let s:do_block_just_closed = 0
endif
let s:current_mode = remove(s:modes, -1)
endfunction
function! s:in_array(what, arr)
return index(a:arr, a:what) != -1
endfunction
function! s:get_next_token()
let n_newlines = 0
if s:parser_pos >= len(s:input)
return ["", "TK_EOF"]
endif
let c = s:input[s:parser_pos]
let s:parser_pos += 1
while s:in_array(c, s:whitespace)
if s:parser_pos >= len(s:input)
return ["", "TK_EOF"]
endif
if c == "\n"
let n_newlines += 1
endif
let c = s:input[s:parser_pos]
let s:parser_pos += 1
endwhile
let wanted_newline = 0
if s:opt_preserve_newlines
if n_newlines > 1
for i in [0, 1]
call s:print_newline(i==0)
endfor
endif
let wanted_newline = n_newlines == 1
endif
if s:in_array(c, s:wordchar)
if s:parser_pos < len(s:input)
while s:in_array(s:input[s:parser_pos], s:wordchar)
let c .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos == len(s:input)
break
endif
endwhile
endif
"if s:parser_pos != len(s:input) && c =~ /^[0-9]+[Ee]$/ && (s:input[s:parser_pos] == "-" || s:input[s:parser_pos] == "+")
"let sign = s:input[s:parser_pos]
"let s:parser_pos += 1
"let t = get_next_token(s:parser_pos)
"let c .= sign . t[0]
"return [c, "TK_WORD"]
" endif
if c == "in"
return [c, "TK_OPERATOR"]
endif
if wanted_newline && s:last_type != "TK_OPERATOR" && !s:if_line_flag
call s:print_newline(1)
endif
return [c, "TK_WORD"]
endif
if c == "(" || c == "["
return [c, "TK_START_EXPR"]
endif
if c == ")" || c == "]"
return [c, "TK_END_EXPR"]
endif
if c == "{"
return [c, "TK_START_BLOCK"]
endif
if c == "}"
return [c, "TK_END_BLOCK"]
endif
if c == ";"
return [c, "TK_SEMICOLON"]
endif
if c == "/"
let comment = ""
if s:input[s:parser_pos] == "*"
let s:parser_pos += 1
if s:parser_pos < len(s:input)
while !(s:input[s:parser_pos] == "*" && s:parser_pos + 1 < len(s:input) && s:input[s:parser_pos + 1] == "/" && s:parser_pos < len(s:input))
let comment .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
endif
let s:parser_pos += 2
return ['/*' . comment . '*/', 'TK_BLOCK_COMMENT']
endif
" peek for comment // ...
if s:input[s:parser_pos] == "/"
let comment = c
while s:input[s:parser_pos] != "\r" && s:input[s:parser_pos] != "\n"
let comment .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
let s:parser_pos += 1
if wanted_newline
call s:print_newline(1)
endif
return [comment, "TK_COMMENT"]
endif
endif
if c == "'" || c =='"' || (c == "/" && ((s:last_type == "TK_WORD" && s:last_text == "return") || (s:last_type == "TK_START_EXPR" || s:last_type == "TK_START_BLOCK" || s:last_type == "TK_END_BLOCK" || s:last_type == "TK_OPERATOR" || s:last_type == "TK_EOF" || s:last_type == "TK_SEMICOLON")))
let sep = c
let esc = 0
let resulting_string = c
if s:parser_pos < len(s:input)
while esc || s:input[s:parser_pos] != sep
let resulting_string .= s:input[s:parser_pos]
if !esc
let esc = s:input[s:parser_pos] == "\\"
else
let esc = 0
endif
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
return [resulting_string, "TK_STRING"]
endif
endwhile
endif
let s:parser_pos += 1
let resulting_string .= sep
if sep == "/"
while s:parser_pos < len(s:input) && s:in_array(s:input[s:parser_pos], s:wordchar)
let resulting_string .= s:input[s:parser_pos]
let s:parser_pos += 1
endwhile
endif
return [resulting_string, "TK_STRING"]
endif
if c == "#"
let sharp = "#"
if s:parser_pos < len(s:input) && s:in_array(s:input[s:parser_pos], s:digits)
let c = s:input[s:parser_pos]
let sharp .= c
let s:parser_pos += 1
while s:parser_pos < len(s:input) && c != "#" && c !="="
let c = s:input[s:parser_pos]
let sharp .= c
let s:parser_pos += 1
endwhile
if c == "#"
return [sharp, "TK_WORD"]
else
return [sharp, "TK_OPERATOR"]
endif
endif
endif
if c == "<" && s:input[s:parser_pos-1 : s:parser_pos+3] == "<!--"
let s:parser_pos += 3
return ["<!--", "TK_COMMENT"]
endif
if c == "-" && s:input[s:parser_pos-1 : s:parser_pos+2] == "-->"
let s:parser_pos += 2
if wanted_newline
call s:print_newline(1)
endif
return ["-->", "TK_COMMENT"]
endif
if s:in_array(c, s:punct)
while s:parser_pos < len(s:input) && s:in_array(c . s:input[s:parser_pos], s:punct)
let c .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
return [c, "TK_OPERATOR"]
endif
return [c, "TK_UNKNOWN"]
endif
endfunction
function! s:is_js()
return expand("%:e") == "js"
endfunction
"function! g:Jsbeautify(js_source_text, options)
function! g:Jsbeautify()
if !s:is_js()
echo "Not a JS file."
return
endif
"let a:options = {}
let s:opt_indent_size = 1
let s:opt_indent_char = "\t"
let s:opt_preserve_newlines = 1
let s:opt_indent_level = 0
let s:if_line_flag = 0
"--------------------------------
let s:indent_string = ""
while s:opt_indent_size > 0
let s:indent_string .= s:opt_indent_char
let s:opt_indent_size -= 1
endwhile
let s:indent_level = s:opt_indent_level
let lines = getline(1, "$")
let s:input = join(lines, "\n")
"let s:input = a:js_source_text
let s:last_word = "" "last 'TK_WORD' passed
let s:last_type = "TK_START_EXPR" "last token type
let s:last_text = "" "last token text
let s:output = []
let s:do_block_just_closed = 0
let s:var_line = 0
let s:var_line_tainted = 0
let s:whitespace = ["\n", "\r", "\t", " "]
let s:wordchar = split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$", '\zs')
let s:digits = split("0123456789", '\zs')
"<!-- is a special case (ok, it"s a minor hack actually)
let s:punct = split("+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::", " ")
let s:line_starters = split("continue,try,throw,return,var,if,switch,case,default,for,while,break", ",")
let s:current_mode = "BLOCK"
let s:modes = [s:current_mode]
let s:parser_pos = 0
let s:in_case = 0
while 1
let t = s:get_next_token()
let s:token_text = t[0]
let s:token_type = t[1]
if s:token_type == "TK_EOF"
break
endif
try
if s:token_type == "TK_START_EXPR"
let s:var_line = 0
call s:set_mode("EXPRESSION")
if s:last_text == ";"
call s:print_newline(1)
elseif s:last_type == "TK_END_EXPR" || s:last_type == "TK_START_EXPR"
" do nothing on (( and )( and ][ and ]( ..
elseif s:last_type != "TK_WORD" && s:last_type != "TK_OPERATOR"
call s:print_space()
elseif s:in_array(s:last_word, s:line_starters)
call s:print_space()
endif
call s:print_token()
elseif s:token_type == "TK_END_EXPR"
call s:print_token()
call s:restore_mode()
elseif s:token_type == "TK_START_BLOCK"
if s:last_word == "do"
call s:set_mode("DO_BLOCK")
else
call s:set_mode("BLOCK")
endif
if s:last_type != "TK_OPERATOR" && s:last_type != "TK_START_EXPR"
if s:last_type == "TK_START_BLOCK"
call s:print_newline(1)
else
call s:print_space()
endif
endif
call s:print_token()
call s:indent()
elseif s:token_type == "TK_END_BLOCK"
if s:last_type == "TK_START_BLOCK"
call s:remove_indent()
call s:unindent()
else
call s:unindent()
call s:print_newline(1)
endif
call s:print_token()
call s:restore_mode()
elseif s:token_type == "TK_WORD"
if s:do_block_just_closed
" do {} ## while ()
call s:print_space()
call s:print_token()
call s:print_space()
let s:do_block_just_closed = 0
throw "jump out"
endif
if s:token_text == "case" || s:token_text == "default"
if s:last_text == ":"
"switch cases following one another
call s:remove_indent()
else
" case statement starts in the same line where switch
call s:unindent()
call s:print_newline(1)
call s:indent()
endif
call s:print_token()
let s:in_case = 1
throw "jump out"
endif
let s:prefix = "NONE"
if s:last_type == "TK_END_BLOCK"
if !s:in_array(tolower(s:token_text), ["else", "catch", "finally"])
let s:prefix = "NEWLINE"
else
let s:prefix = "SPACE"
call s:print_space()
endif
elseif s:last_type == "TK_SEMICOLON" && (s:current_mode == "BLOCK" || s:current_mode == "DO_BLOCK")
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_SEMICOLON" && s:current_mode == "EXPRESSION"
let s:prefix = "SPACE"
elseif s:last_type == "TK_STRING"
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_WORD"
let s:prefix = "SPACE"
elseif s:last_type == "TK_START_BLOCK"
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_END_EXPR"
call s:print_space()
let s:prefix = "NEWLINE"
endif
if s:last_type != "TK_END_BLOCK" && s:in_array(tolower(s:token_text), ["else", "catch", "finally"])
call s:print_newline(1)
elseif s:in_array(s:token_text, s:line_starters) || s:prefix == "NEWLINE"
if s:last_text == "else"
call s:print_space()
elseif (s:last_type == "TK_START_EXPR" || s:last_text == "=" || s:last_text == ",") && s:token_text == "function"
" no need to force newline on "function":
" DONOTHINT
elseif s:last_type == "TK_WORD" && (s:last_text == "return" || s:last_text == "throw")
" no newline between "return nnn"
call s:print_space()
elseif s:last_type != "TK_END_EXPR"
if (s:last_type != "TK_START_EXPR" || s:token_text != "var") && s:last_text != ":"
" no need to force newline on "var": for (var
" x = 0...)
if s:token_text == "if" && s:last_type == "TK_WORD" && s:last_word == "else"
" no newline for } else if {
call s:print_space()
else
call s:print_newline(1)
endif
endif
else
if s:in_array(s:token_text, s:line_starters) && s:last_text != ")"
call s:print_newline(1)
endif
endif
elseif s:prefix == "SPACE"
call s:print_space()
endif
call s:print_token()
let s:last_word = s:token_text
if s:token_text == "var"
let s:var_line = 1
let s:var_line_tainted = 0
endif
if s:token_text == "if" || s:token_text == "else"
let s:if_line_flag = 1
endif
elseif s:token_type == "TK_SEMICOLON"
call s:print_token()
let s:var_line = 0
elseif s:token_type == "TK_STRING"
if s:last_type == "TK_START_BLOCK" || s:last_type == "TK_END_BLOCK" || s:last_type == "TK_SEMICOLON"
call s:print_newline(1)
elseif s:last_type == "TK_WORD"
call s:print_space()
endif
call s:print_token()
elseif s:token_type == "TK_OPERATOR"
let start_delim = 1
let end_delim = 1
if s:var_line && s:token_text != ","
let s:var_line_tainted = 1
if s:token_text == ":"
let s:var_line = 0
endif
endif
if s:var_line && s:token_text=="," && s:current_mode == "EXPRESSION"
" do not break on comma, for(var a = 1, b = 2)
let s:var_line_tainted = 0
endif
if s:token_text == ":" && s:in_case
call s:print_token()
call s:print_newline(1)
throw "jump out"
endif
if s:token_text == "::"
" no spaces around exotic namespacing syntax operator
call s:print_token()
throw "jump out"
endif
let s:in_case = 0
if s:token_text == ","
if s:var_line
if s:var_line_tainted
call s:print_token()
call s:print_newline(1)
let s:var_line_tainted = 0
else
call s:print_token()
call s:print_space()
endif
elseif s:last_type == "TK_END_BLOCK"
call s:print_token()
call s:print_newline(1)
else
if s:current_mode == "BLOCK"
call s:print_token()
call s:print_newline(1)
else
" EXPR od DO_BLOCK
call s:print_token()
call s:print_space()
endif
endif
throw "jump out"
elseif s:token_text == "--" || s:token_text == "++" " unary operators special case
if s:last_text == ";"
" space for (;; ++i)
let start_delim = 1
let end_delim = 0
else
let start_delim = 0
let end_delim = 0
endif
elseif s:token_text == "!" && s:last_type == "TK_START_EXPR"
" special case handling: if (!a)
let start_delim = 0
let end_delim = 0
elseif s:last_type == "TK_OPERATOR"
let s:start_delim = 0
let s:end_delim = 0
elseif s:last_type == "TK_END_EXPR"
let s:start_delim = 1
let s:end_delim = 1
elseif s:token_text == "."
" decimal digits or object.property
let start_delim = 0
let end_delim = 0
elseif s:token_text == ":"
" zz: xx
" can"t differentiate ternary op, so for now it"s a ? b:
" c;without space before colon
if s:last_text =~ '/^\d+$/'
" a little help for ternary a ? 1 : 0
let start_delim = 1
else
let start_delim = 0
endif
endif
if start_delim
call s:print_space()
endif
call s:print_token()
if end_delim
call s:print_space()
endif
throw "jump out"
elseif s:token_type == "TK_BLOCK_COMMENT"
call s:print_newline(1)
call s:print_token()
call s:print_newline(1)
elseif s:token_type == "TK_COMMENT"
"call s:print_newline(1)
call s:print_space()
call s:print_token()
call s:print_newline(1)
elseif s:token_type == "TK_UNKNOWN"
call s:print_token()
throw "jump out"
endif
catch /.*/
if v:exception != 'jump out'
echo "exception caught: " v:exception
endif
endtry
let s:last_type = s:token_type
let s:last_text = s:token_text
endwhile
let ret = join(s:output, "")
:g/.*/d
let @0 = ret
:put!0
endfunction
nnoremap <silent> <leader>ff :call g:Jsbeautify()<cr>
-108
View File
@@ -1,108 +0,0 @@
"=============================================================================
" Copyright (C) 2009-2010 Takeshi NISHIDA
"
" GetLatestVimScripts: 3252 1 :AutoInstall: L9
"=============================================================================
" LOAD GUARD {{{1
if !l9#guardScriptLoading(expand('<sfile>:p'), 702, 0, [])
finish
endif
" }}}1
"=============================================================================
" OPTIONS: {{{1
call l9#defineVariableDefault('g:l9_balloonly', 'balloonly.exe')
" }}}1
"=============================================================================
" ASSERTION: {{{1
" This command has effect only if $L9_DEBUG is non-zero.
" Used as follows:
" L9Assert a:i > 0
" This command can't interpret script-local variables directly.
" NG: L9Assert s:a == 1
" OK: execute 'L9Assert ' . s:a . ' == 1'
"
if $L9_DEBUG
command -nargs=* L9Assert call eval((<args>) ? 0 : s:handleFailedAssersion(<q-args>))
function s:handleFailedAssersion(expr)
echoerr '[L9Assert] Assersion failure: ' . a:expr
if input('[L9Assert] Continue? (Y/N) ', 'Y') !=? 'Y'
throw 'L9Assert ' . a:expr
endif
endfunction
else
command -nargs=* L9Assert :
endif
" }}}1
"=============================================================================
" TIMER: {{{1
" These commands have effect only if $L9_TIMER is non-zero.
" Used as follows:
" L9Timer foo
" ... (1)
" L9Timer bar
" ... (2)
" L9TimerStop
" ...
" L9TimerDump <- shows each elapsed time of (1) and (2)
"
if $L9_TIMER
command -nargs=1 L9Timer call s:timerBegin(<q-args>)
command -nargs=0 L9TimerStop call s:timerStop()
command -nargs=0 L9TimerDump call s:timerDump()
let s:timerData = []
let s:timerTagMaxLen = 0
function s:timerBegin(tag)
L9TimerStop
let s:timerCurrent = {'tag': strftime('%c ') . a:tag . ' ', 'time': reltime()}
let s:timerTagMaxLen = max([len(s:timerCurrent.tag), s:timerTagMaxLen])
endfunction
function s:timerStop()
if !exists('s:timerCurrent')
return
endif
let s:timerCurrent.time = reltimestr(reltime(s:timerCurrent.time))
call add(s:timerData, s:timerCurrent)
unlet s:timerCurrent
endfunction
function s:timerDump()
L9TimerStop
let lines = map(s:timerData, 'v:val.tag . repeat(" ", s:timerTagMaxLen - len(v:val.tag)) . v:val.time')
call l9#tempbuffer#openReadOnly('[l9-timer]', '', lines, 0, 0, 0, {})
let s:timerData = []
let s:timerTagMaxLen = 0
endfunction
else
command -nargs=1 L9Timer :
command -nargs=0 L9TimerStop :
command -nargs=0 L9TimerDump :
endif
" }}}1
"=============================================================================
" GREP BUFFER: {{{1
" Grep for current buffer by l9#grepBuffers()
" Used as :L9GrepBuffer/pattern
command -nargs=? L9GrepBuffer call l9#grepBuffers(<q-args>, [bufnr('%')])
" Grep for all buffers by l9#grepBuffers()
" Used as :L9GrepBufferAll/pattern
command -nargs=? L9GrepBufferAll call l9#grepBuffers(<q-args>, range(1, bufnr('$')))
" }}}1
"=============================================================================
" vim: set fdm=marker:
-85
View File
@@ -1,85 +0,0 @@
" loremipsum.vim
" @Author: Thomas 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: 2008-07-10.
" @Last Change: 2008-07-11.
" @Revision: 66
" GetLatestVimScripts: 2289 0 loremipsum.vim
if &cp || exists("loaded_loremipsum")
finish
endif
let loaded_loremipsum = 2
let s:save_cpo = &cpo
set cpo&vim
if !exists('g:loremipsum_paragraph_template')
" A dictionary of filetypes and paragraph templates (as format
" strings for |printf()|).
" :nodefault:
" :read: let g:loremipsum_paragraph_template = {} "{{{2
let g:loremipsum_paragraph_template = {
\ 'html': '<p>%s</p>',
\ 'php': '<p>%s</p>',
\ }
endif
if !exists('g:loremipsum_marker')
" A dictionary of filetypes and array containing the prefix and the
" postfix for the inserted text:
" [prefix, postfix, no_inline?]
" :read: let g:loremipsum_marker = {} "{{{2
let g:loremipsum_marker = {
\ 'html': ['<!--lorem-->', '<!--/lorem-->', 0],
\ 'php': ['<!--lorem-->', '<!--/lorem-->', 0],
\ 'tex': ['% lorem{{{', '% lorem}}}', 1],
\ 'viki': ['% lorem{{{', '% lorem}}}', 1],
\ }
endif
if !exists('g:loremipsum_words')
" Default length.
let g:loremipsum_words = 100 "{{{2
endif
if !exists('g:loremipsum_files')
" *b:loremipsum_file*
" If b:loremipsum_file exists, it will be used as source. Otherwise,
" g:loremipsum_files[&spelllang] will be checked. As a fallback,
" .../autoload/loremipsum.txt will be used.
let g:loremipsum_files = {} "{{{2
endif
" :display: :Loremipsum[!] [COUNT] [PARAGRAPH_TEMPLATE] [PREFIX POSTFIX]
" With [!], insert the text "inline", don't apply paragraph templates.
" If the PARAGRAPH_TEMPLATE is *, use the default template from
" |g:loremipsum_paragraph_template| (in case you want to change
" PREFIX and POSTFIX). If it is _, use no paragraph template.
" If PREFIX is _, don't use markers.
command! -bang -nargs=* Loremipsum call loremipsum#Insert("<bang>", <f-args>)
" Replace loremipsum text with something else. Or simply remove it.
" :display: :Loreplace [REPLACEMENT] [PREFIX] [POSTFIX]
command! -nargs=* Loreplace call loremipsum#Replace(<f-args>)
let &cpo = s:save_cpo
unlet s:save_cpo
finish
CHANGES:
0.1
- Initial release
0.2
- Loremipsum!: With !, insert inline (single paragraph)
- If the template argument is *, don't apply the default paragraph
template.
- Loreplace: Replace loremipsum text with something else (provided a
marker was defined for the current filetype)
- g:loremipsum_file, b:loremipsum_file
-289
View File
@@ -1,289 +0,0 @@
" Script Name: mark.vim
" Description: Highlight several words in different colors simultaneously.
"
" Copyright: (C) 2005-2008 by Yuheng Xie
" (C) 2008-2011 by Ingo Karkat
" The VIM LICENSE applies to this script; see ':help copyright'.
"
" Maintainer: Ingo Karkat <ingo@karkat.de>
" Orig Author: Yuheng Xie <elephant@linux.net.cn>
" Contributors:Luc Hermitte, Ingo Karkat
"
" Dependencies:
" - Requires Vim 7.1 with "matchadd()", or Vim 7.2 or higher.
" - mark.vim autoload script.
"
" Version: 2.5.0
" Changes:
" 06-May-2011, Ingo Karkat
" - By default, enable g:mwAutoSaveMarks, so that marks are always persisted,
" but disable g:mwAutoLoadMarks, so that persisted marks have to be explicitly
" loaded, if that is desired. I often wondered why I got unexpected mark
" highlightings in a new Vim session until I realized that I had used marks in
" a previous session and forgot to clear them.
"
" 21-Apr-2011, Ingo Karkat
" - Expose toggling of mark display (keeping the mark patterns) via new
" <Plug>MarkToggle mapping. Offer :MarkClear command as a replacement for the
" old argumentless :Mark command, which now just disables, but not clears all
" marks.
" - Implement lazy-loading of disabled persistent marks via g:mwDoDeferredLoad
" flag passing to autoload/mark.vim.
"
" 19-Apr-2011, Ingo Karkat
" - ENH: Add explicit mark persistence via :MarkLoad and :MarkSave commands and
" automatic persistence via the g:mwAutoLoadMarks and g:mwAutoSaveMarks
" configuration flags.
"
" 15-Apr-2011, Ingo Karkat
" - Avoid losing the mark highlightings on :syn on or :colorscheme commands.
" Thanks to Zhou YiChao for alerting me to this issue and suggesting a fix.
"
" 17-Nov-2009, Ingo Karkat
" - Replaced the (overly) generic mark#GetVisualSelectionEscaped() with
" mark#GetVisualSelectionAsRegexp() and
" mark#GetVisualSelectionAsLiteralPattern().
"
" 04-Jul-2009, Ingo Karkat
" - A [count] before any mapping either caused "No range allowed" error or just
" repeated the :call [count] times, resulting in the current search pattern
" echoed [count] times and a hit-enter prompt. Now suppressing [count] via
" <C-u> and handling it inside the implementation.
" - Now passing isBackward (0/1) instead of optional 'b' flag into functions.
" Also passing empty regexp to mark#MarkRegex() to avoid any optional
" arguments.
"
" 02-Jul-2009, Ingo Karkat
" - Split off functions into autoload script.
" - Removed g:force_reload_mark.
" - Initialization of global variables and autocommands is now done lazily on
" the first use, not during loading of the plugin. This reduces Vim startup
" time and footprint as long as the functionality isn't yet used.
"
" 6-Jun-2009, Ingo Karkat
" 1. Somehow s:WrapMessage() needs a redraw before the :echo to avoid that a
" later Vim redraw clears the wrap message. This happened when there's no
" statusline and thus :echo'ing into the ruler.
" 2. Removed line-continuations and ':set cpo=...'. Upper-cased <SID> and <CR>.
" 3. Added default highlighting for the special search type.
"
" 2-Jun-2009, Ingo Karkat
" 1. Replaced highlighting via :syntax with matchadd() / matchdelete(). This
" requires Vim 7.2 / 7.1 with patches. This method is faster, there are no
" more clashes with syntax highlighting (:match always has preference), and
" the background highlighting does not disappear under 'cursorline'.
" 2. Factored :windo application out into s:MarkScope().
" 3. Using winrestcmd() to fix effects of :windo: By entering a window, its
" height is potentially increased from 0 to 1.
" 4. Handling multiple tabs by calling s:UpdateScope() on the TabEnter event.
"
" 1-Jun-2009, Ingo Karkat
" 1. Now using Vim List for g:mwWord and thus requiring Vim 7. g:mwCycle is now
" zero-based, but the syntax groups "MarkWordx" are still one-based.
" 2. Added missing setter for re-inclusion guard.
" 3. Factored :syntax operations out of s:DoMark() and s:UpdateMark() so that
" they can all be done in a single :windo.
" 4. Normal mode <Plug>MarkSet now has the same semantics as its visual mode
" cousin: If the cursor is on an existing mark, the mark is removed.
" Beforehand, one could only remove a visually selected mark via again
" selecting it. Now, one simply can invoke the mapping when on such a mark.
" 5. Highlighting can now actually be overridden in the vimrc (anywhere
" _before_ sourcing this script) by using ':hi def'.
"
" 31-May-2009, Ingo Karkat
" 1. Refactored s:Search() to optionally take advantage of SearchSpecial.vim
" autoload functionality for echoing of search pattern, wrap and error
" messages.
" 2. Now prepending search type ("any-mark", "same-mark", "new-mark") for
" better identification.
" 3. Retired the algorithm in s:PrevWord in favor of simply using <cword>,
" which makes mark.vim work like the * command. At the end of a line,
" non-keyword characters may now be marked; the previous algorithm prefered
" any preceding word.
" 4. BF: If 'iskeyword' contains characters that have a special meaning in a
" regex (e.g. [.*]), these are now escaped properly.
"
" 01-Sep-2008, Ingo Karkat: bugfixes and enhancements
" 1. Added <Plug>MarkAllClear (without a default mapping), which clears all
" marks, even when the cursor is on a mark.
" 2. Added <Plug>... mappings for hard-coded \*, \#, \/, \?, * and #, to allow
" re-mapping and disabling. Beforehand, there were some <Plug>... mappings
" and hard-coded ones; now, everything can be customized.
" 3. Bugfix: Using :autocmd without <bang> to avoid removing _all_ autocmds for
" the BufWinEnter event. (Using a custom :augroup would be even better.)
" 4. Bugfix: Explicitly defining s:current_mark_position; some execution paths
" left it undefined, causing errors.
" 5. Refactoring: Instead of calling s:InitMarkVariables() at the beginning of
" several functions, just calling it once when sourcing the script.
" 6. Refactoring: Moved multiple 'let lastwinnr = winnr()' to a single one at the
" top of DoMark().
" 7. ENH: Make the match according to the 'ignorecase' setting, like the star
" command.
" 8. The jumps to the next/prev occurrence now print 'search hit BOTTOM,
" continuing at TOP" and "Pattern not found:..." messages, like the * and
" n/N Vim search commands.
" 9. Jumps now open folds if the occurrence is inside a closed fold, just like n/N
" do.
"
" 10th Mar 2006, Yuheng Xie: jump to ANY mark
" (*) added \* \# \/ \? for the ability of jumping to ANY mark, even when the
" cursor is not currently over any mark
"
" 20th Sep 2005, Yuheng Xie: minor modifications
" (*) merged MarkRegexVisual into MarkRegex
" (*) added GetVisualSelectionEscaped for multi-lines visual selection and
" visual selection contains ^, $, etc.
" (*) changed the name ThisMark to CurrentMark
" (*) added SearchCurrentMark and re-used raw map (instead of Vim function) to
" implement * and #
"
" 14th Sep 2005, Luc Hermitte: modifications done on v1.1.4
" (*) anti-reinclusion guards. They do not guard colors definitions in case
" this script must be reloaded after .gvimrc
" (*) Protection against disabled |line-continuation|s.
" (*) Script-local functions
" (*) Default keybindings
" (*) \r for visual mode
" (*) uses <Leader> instead of "\"
" (*) do not mess with global variable g:w
" (*) regex simplified -> double quotes changed into simple quotes.
" (*) strpart(str, idx, 1) -> str[idx]
" (*) command :Mark
" -> e.g. :Mark Mark.\{-}\ze(
" Avoid installing twice or when in unsupported Vim version.
if exists('g:loaded_mark') || (v:version == 701 && ! exists('*matchadd')) || (v:version < 702)
finish
endif
let g:loaded_mark = 1
"- configuration --------------------------------------------------------------
if ! exists('g:mwHistAdd')
let g:mwHistAdd = '/@'
endif
if ! exists('g:mwAutoLoadMarks')
let g:mwAutoLoadMarks = 0
endif
if ! exists('g:mwAutoSaveMarks')
let g:mwAutoSaveMarks = 1
endif
"- default highlightings ------------------------------------------------------
function! s:DefaultHighlightings()
" You may define your own colors in your vimrc file, in the form as below:
highlight def MarkWord1 ctermbg=Cyan ctermfg=Black guibg=#8CCBEA guifg=Black
highlight def MarkWord2 ctermbg=Green ctermfg=Black guibg=#A4E57E guifg=Black
highlight def MarkWord3 ctermbg=Yellow ctermfg=Black guibg=#FFDB72 guifg=Black
highlight def MarkWord4 ctermbg=Red ctermfg=Black guibg=#FF7272 guifg=Black
highlight def MarkWord5 ctermbg=Magenta ctermfg=Black guibg=#FFB3FF guifg=Black
highlight def MarkWord6 ctermbg=Blue ctermfg=Black guibg=#9999FF guifg=Black
endfunction
call s:DefaultHighlightings()
autocmd ColorScheme * call <SID>DefaultHighlightings()
" Default highlighting for the special search type.
" You can override this by defining / linking the 'SearchSpecialSearchType'
" highlight group before this script is sourced.
highlight def link SearchSpecialSearchType MoreMsg
"- mappings -------------------------------------------------------------------
nnoremap <silent> <Plug>MarkSet :<C-u>call mark#MarkCurrentWord()<CR>
vnoremap <silent> <Plug>MarkSet <C-\><C-n>:call mark#DoMark(mark#GetVisualSelectionAsLiteralPattern())<CR>
nnoremap <silent> <Plug>MarkRegex :<C-u>call mark#MarkRegex('')<CR>
vnoremap <silent> <Plug>MarkRegex <C-\><C-n>:call mark#MarkRegex(mark#GetVisualSelectionAsRegexp())<CR>
nnoremap <silent> <Plug>MarkClear :<C-u>call mark#DoMark(mark#CurrentMark()[0])<CR>
nnoremap <silent> <Plug>MarkAllClear :<C-u>call mark#ClearAll()<CR>
nnoremap <silent> <Plug>MarkToggle :<C-u>call mark#Toggle()<CR>
nnoremap <silent> <Plug>MarkSearchCurrentNext :<C-u>call mark#SearchCurrentMark(0)<CR>
nnoremap <silent> <Plug>MarkSearchCurrentPrev :<C-u>call mark#SearchCurrentMark(1)<CR>
nnoremap <silent> <Plug>MarkSearchAnyNext :<C-u>call mark#SearchAnyMark(0)<CR>
nnoremap <silent> <Plug>MarkSearchAnyPrev :<C-u>call mark#SearchAnyMark(1)<CR>
nnoremap <silent> <Plug>MarkSearchNext :<C-u>if !mark#SearchNext(0)<Bar>execute 'normal! *zv'<Bar>endif<CR>
nnoremap <silent> <Plug>MarkSearchPrev :<C-u>if !mark#SearchNext(1)<Bar>execute 'normal! #zv'<Bar>endif<CR>
" When typed, [*#nN] open the fold at the search result, but inside a mapping or
" :normal this must be done explicitly via 'zv'.
if !hasmapto('<Plug>MarkSet', 'n')
nmap <unique> <silent> <Leader>m <Plug>MarkSet
endif
if !hasmapto('<Plug>MarkSet', 'v')
vmap <unique> <silent> <Leader>m <Plug>MarkSet
endif
if !hasmapto('<Plug>MarkRegex', 'n')
nmap <unique> <silent> <Leader>r <Plug>MarkRegex
endif
if !hasmapto('<Plug>MarkRegex', 'v')
vmap <unique> <silent> <Leader>r <Plug>MarkRegex
endif
if !hasmapto('<Plug>MarkClear', 'n')
nmap <unique> <silent> <Leader>n <Plug>MarkClear
endif
" No default mapping for <Plug>MarkAllClear.
" No default mapping for <Plug>MarkToggle.
if !hasmapto('<Plug>MarkSearchCurrentNext', 'n')
nmap <unique> <silent> <Leader>* <Plug>MarkSearchCurrentNext
endif
if !hasmapto('<Plug>MarkSearchCurrentPrev', 'n')
nmap <unique> <silent> <Leader># <Plug>MarkSearchCurrentPrev
endif
if !hasmapto('<Plug>MarkSearchAnyNext', 'n')
nmap <unique> <silent> <Leader>/ <Plug>MarkSearchAnyNext
endif
if !hasmapto('<Plug>MarkSearchAnyPrev', 'n')
nmap <unique> <silent> <Leader>? <Plug>MarkSearchAnyPrev
endif
if !hasmapto('<Plug>MarkSearchNext', 'n')
nmap <unique> <silent> * <Plug>MarkSearchNext
endif
if !hasmapto('<Plug>MarkSearchPrev', 'n')
nmap <unique> <silent> # <Plug>MarkSearchPrev
endif
"- commands -------------------------------------------------------------------
command! -nargs=? Mark call mark#DoMark(<f-args>)
command! -bar MarkClear call mark#ClearAll()
command! -bar MarkLoad call mark#LoadCommand(1)
command! -bar MarkSave call mark#SaveCommand()
"- marks persistence ----------------------------------------------------------
if g:mwAutoLoadMarks
" As the viminfo is only processed after sourcing of the runtime files, the
" persistent global variables are not yet available here. Defer this until Vim
" startup has completed.
function! s:AutoLoadMarks()
if g:mwAutoLoadMarks && exists('g:MARK_MARKS') && g:MARK_MARKS !=# '[]'
if ! exists('g:MARK_ENABLED') || g:MARK_ENABLED
" There are persistent marks and they haven't been disabled; we need to
" show them right now.
call mark#LoadCommand(0)
else
" Though there are persistent marks, they have been disabled. We avoid
" sourcing the autoload script and its invasive autocmds right now;
" maybe the marks are never turned on. We just inform the autoload
" script that it should do this once it is sourced on-demand by a
" mark mapping or command.
let g:mwDoDeferredLoad = 1
endif
endif
endfunction
augroup MarkInitialization
autocmd!
" Note: Avoid triggering the autoload unless there actually are persistent
" marks. For that, we need to check that g:MARK_MARKS doesn't contain the
" empty list representation, and also :execute the :call.
autocmd VimEnter * call <SID>AutoLoadMarks()
augroup END
endif
" vim: ts=2 sw=2
-86
View File
@@ -1,86 +0,0 @@
"=============================================================================
" File: occur.vim
" Author: FURUSAWA, Noriyoshi (noriyosi xxx gmail dot com) xxx=@,dot=.
" Last Change: 2008/7/13
" Version: 0.03
"=============================================================================
if exists('loaded_occur') || &cp
finish
endif
let loaded_occur=1
if v:version < 700
echo "Sorry, occur ONLY runs with Vim 7.0 and greater."
finish
endif
if !exists("g:occur_no_quickfix_map")
let g:occur_no_quickfix_map = 0
endif
" Key bind
nnoremap <silent> <unique> <Leader>oc :Occur<CR>
" gryf: Changed followin mapping due to confilct with showmarks plugin
nnoremap <silent> <unique> <Leader>om :Moccur<CR>
" gryf: Changed followin mapping due to confilct with marks plugin
nnoremap <silent> <unique> <Leader>8 *<C-o>:Moccur<CR>
" Create commands
command! Occur silent call s:SetupAndGo('s:Occur')
command! Moccur silent call s:SetupAndGo('s:Moccur')
command! StarOccur exec "normal! *<C-o>" <Bar> Moccur
function! s:Occur()
let expr = 'caddexpr expand("%") . ":" . line(".") . ":" . getline(".")'
exec 'silent keepjumps g/' . @/ . '/' . expr
endfunction
function! s:Moccur()
" Create the buffer list
redir => command_out
ls
redir END
let buffers = []
for line in split(command_out, '\n')
call add(buffers, split(line, ' ')[0])
endfor
" Search the pattern in all buffers
for buf_number in buffers
exec 'keepjumps buffer ' . buf_number
call s:Occur()
endfor
endfunction
function! s:SetupAndGo(func)
let org_efm = &errorformat
let &errorformat = '%f:%l:%m'
" Clear the results window
cexpr "================= occur result ================="
cclose
" Log the current cursor position
normal! H
" Do Occur
call function(a:func)()
" Open the results window (and restore cursor position)
keepjumps cfirst 1
exec "normal! \<C-o>"
copen
" Map the key sequence on the QuickFix
if !g:occur_no_quickfix_map
nnoremap <buffer> <silent> <Space> <C-w><C-_>
nnoremap <buffer> <silent> x 10<C-w>_<CR>zxzz:copen<CR>
nnoremap <buffer> <silent> <CR> <CR>zxzz:cclose<CR>
nnoremap <buffer> <silent> q :cclose<CR>
endif
let &errorformat = org_efm
endfunction
-72
View File
@@ -1,72 +0,0 @@
" repeat.vim - Let the repeat command repeat plugin maps
" Maintainer: Tim Pope
" Version: 1.0
" Installation:
" Place in either ~/.vim/plugin/repeat.vim (to load at start up) or
" ~/.vim/autoload/repeat.vim (to load automatically as needed).
"
" Developers:
" Basic usage is as follows:
"
" silent! call repeat#set("\<Plug>MappingToRepeatCommand",3)
"
" The first argument is the mapping that will be invoked when the |.| key is
" pressed. Typically, it will be the same as the mapping the user invoked.
" This sequence will be stuffed into the input queue literally. Thus you must
" encode special keys by prefixing them with a backslash inside double quotes.
"
" The second argument is the default count. This is the number that will be
" prefixed to the mapping if no explicit numeric argument was given. The
" value of the v:count variable is usually correct and it will be used if the
" second parameter is omitted. If your mapping doesn't accept a numeric
" argument and you never want to receive one, pass a value of -1.
"
" Make sure to call the repeat#set function _after_ making changes to the
" file.
if exists("g:loaded_repeat") || &cp || v:version < 700
finish
endif
let g:loaded_repeat = 1
let g:repeat_tick = -1
function! repeat#set(sequence,...)
silent exe "norm! \"=''\<CR>p"
let g:repeat_sequence = a:sequence
let g:repeat_count = a:0 ? a:1 : v:count
let g:repeat_tick = b:changedtick
endfunction
function! s:repeat(count)
if g:repeat_tick == b:changedtick
let c = g:repeat_count
let s = g:repeat_sequence
let cnt = c == -1 ? "" : (a:count ? a:count : (c ? c : ''))
call feedkeys(cnt . s)
else
call feedkeys((a:count ? a:count : '') . '.', 'n')
endif
endfunction
function! s:wrap(command,count)
let preserve = (g:repeat_tick == b:changedtick)
exe 'norm! '.(a:count ? a:count : '').a:command
if preserve
let g:repeat_tick = b:changedtick
endif
endfunction
nnoremap <silent> . :<C-U>call <SID>repeat(v:count)<CR>
nnoremap <silent> u :<C-U>call <SID>wrap('u',v:count)<CR>
nnoremap <silent> U :<C-U>call <SID>wrap('U',v:count)<CR>
nnoremap <silent> <C-R> :<C-U>call <SID>wrap("\<Lt>C-R>",v:count)<CR>
augroup repeatPlugin
autocmd!
autocmd BufLeave,BufWritePre,BufReadPre * let g:repeat_tick = (g:repeat_tick == b:changedtick || g:repeat_tick == 0) ? 0 : -1
autocmd BufEnter,BufWritePost * if g:repeat_tick == 0|let g:repeat_tick = b:changedtick|endif
augroup END
" vim:set ft=vim et sw=4 sts=4:
-507
View File
@@ -1,507 +0,0 @@
" ==============================================================================
" Name: ShowMarks
" Description: Visually displays the location of marks.
" Authors: Anthony Kruize <trandor@labyrinth.net.au>
" Michael Geddes <michaelrgeddes@optushome.com.au>
" Version: 2.2
" Modified: 17 August 2004
" License: Released into the public domain.
" ChangeLog: See :help showmarks-changelog
"
" Usage: Copy this file into the plugins directory so it will be
" automatically sourced.
"
" Default keymappings are:
" <Leader>mt - Toggles ShowMarks on and off.
" <Leader>mo - Turns ShowMarks on, and displays marks.
" <Leader>mh - Clears a mark.
" <Leader>ma - Clears all marks.
" <Leader>mm - Places the next available mark.
"
" Hiding a mark doesn't actually remove it, it simply moves it
" to line 1 and hides it visually.
"
" Configuration: ***********************************************************
" * PLEASE read the included help file(showmarks.txt) for a *
" * more thorough explanation of how to use ShowMarks. *
" ***********************************************************
" The following options can be used to customize the behavior
" of ShowMarks. Simply include them in your vimrc file with
" the desired settings.
"
" showmarks_enable (Default: 1)
" Defines whether ShowMarks is enabled by default.
" Example: let g:showmarks_enable=0
" showmarks_include (Default: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.'`^<>[]{}()\"")
" Defines all marks, in precedence order (only the highest
" precence will show on lines having more than one mark).
" Can be buffer-specific (set b:showmarks_include)
" showmarks_ignore_type (Default: "hq")
" Defines the buffer types to be ignored.
" Valid types are:
" h - Help p - preview
" q - quickfix r - readonly
" m - non-modifiable
" showmarks_textlower (Default: ">")
" Defines how the mark is to be displayed.
" A maximum of two characters can be displayed. To include
" the mark in the text use a tab(\t) character. A single
" character will display as the mark with the character
" suffixed (same as "\t<character>")
" Examples:
" To display the mark with a > suffixed:
" let g:showmarks_textlower="\t>"
" or
" let g:showmarks_textlower=">"
" To display the mark with a ( prefixed:
" let g:showmarks_textlower="(\t"
" To display two > characters:
" let g:showmarks_textlower=">>"
" showmarks_textupper (Default: ">")
" Same as above but for the marks A-Z.
" Example: let g:showmarks_textupper="**"
" showmarks_textother (Default: ">")
" Same as above but for all other marks.
" Example: let g:showmarks_textother="--"
" showmarks_hlline_lower (Default: 0)
" showmarks_hlline_upper (Default: 0)
" showmarks_hlline_other (Default: 0)
" Defines whether the entire line for a particular mark
" should be highlighted.
" Example: let g:showmarks_hlline_lower=1
"
" Setting Highlighting Colours
" ShowMarks uses the following highlighting groups:
" ShowMarksHLl - For marks a-z
" ShowMarksHLu - For marks A-Z
" ShowMarksHLo - For all other marks
" ShowMarksHLm - For multiple marks on the same line.
" (Highest precendece mark is shown)
"
" By default they are set to a bold blue on light blue.
" Defining a highlight for each of these groups will
" override the default highlighting.
" See the VIM help for more information about highlighting.
" ==============================================================================
" Check if we should continue loading
if exists( "loaded_showmarks" )
finish
endif
let loaded_showmarks = 1
" Bail if Vim isn't compiled with signs support.
if has( "signs" ) == 0
echohl ErrorMsg
echo "ShowMarks requires Vim to have +signs support."
echohl None
finish
endif
" Options: Set up some nice defaults
if !exists('g:showmarks_enable' ) | let g:showmarks_enable = 1 | endif
if !exists('g:showmarks_textlower' ) | let g:showmarks_textlower = ">" | endif
if !exists('g:showmarks_textupper' ) | let g:showmarks_textupper = ">" | endif
if !exists('g:showmarks_textother' ) | let g:showmarks_textother = ">" | endif
if !exists('g:showmarks_ignore_type' ) | let g:showmarks_ignore_type = "hq" | endif
if !exists('g:showmarks_ignore_name' ) | let g:showmarks_ignore_name = "" | endif
if !exists('g:showmarks_hlline_lower') | let g:showmarks_hlline_lower = "0" | endif
if !exists('g:showmarks_hlline_upper') | let g:showmarks_hlline_upper = "0" | endif
if !exists('g:showmarks_hlline_other') | let g:showmarks_hlline_other = "0" | endif
" This is the default, and used in ShowMarksSetup to set up info for any
" possible mark (not just those specified in the possibly user-supplied list
" of marks to show -- it can be changed on-the-fly).
let s:all_marks = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.'`^<>[]{}()\""
" Commands
com! -nargs=0 ShowMarksToggle :call <sid>ShowMarksToggle()
com! -nargs=0 ShowMarksOn :call <sid>ShowMarksOn()
com! -nargs=0 ShowMarksClearMark :call <sid>ShowMarksClearMark()
com! -nargs=0 ShowMarksClearAll :call <sid>ShowMarksClearAll()
com! -nargs=0 ShowMarksPlaceMark :call <sid>ShowMarksPlaceMark()
" Mappings (NOTE: Leave the '|'s immediately following the '<cr>' so the mapping does not contain any trailing spaces!)
if !hasmapto( '<Plug>ShowmarksShowMarksToggle' ) | map <silent> <unique> <leader>mt :ShowMarksToggle<cr>| endif
if !hasmapto( '<Plug>ShowmarksShowMarksOn' ) | map <silent> <unique> <leader>mo :ShowMarksOn<cr>| endif
if !hasmapto( '<Plug>ShowmarksClearMark' ) | map <silent> <unique> <leader>mh :ShowMarksClearMark<cr>| endif
if !hasmapto( '<Plug>ShowmarksClearAll' ) | map <silent> <unique> <leader>ma :ShowMarksClearAll<cr>| endif
if !hasmapto( '<Plug>ShowmarksPlaceMark' ) | map <silent> <unique> <leader>mm :ShowMarksPlaceMark<cr>| endif
noremap <unique> <script> \sm m
noremap <silent> m :exe 'norm \sm'.nr2char(getchar())<bar>call <sid>ShowMarks()<CR>
" AutoCommands: Only if ShowMarks is enabled
if g:showmarks_enable == 1
aug ShowMarks
au!
autocmd CursorHold * call s:ShowMarks()
aug END
endif
" Highlighting: Setup some nice colours to show the mark positions.
hi default ShowMarksHLl ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold
hi default ShowMarksHLu ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold
hi default ShowMarksHLo ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold
hi default ShowMarksHLm ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold
" Function: IncludeMarks()
" Description: This function returns the list of marks (in priority order) to
" show in this buffer. Each buffer, if not already set, inherits the global
" setting; if the global include marks have not been set; that is set to the
" default value.
fun! s:IncludeMarks()
if exists('b:showmarks_include') && exists('b:showmarks_previous_include') && b:showmarks_include != b:showmarks_previous_include
" The user changed the marks to include; hide all marks; change the
" included mark list, then show all marks. Prevent infinite
" recursion during this switch.
if exists('s:use_previous_include')
" Recursive call from ShowMarksHideAll()
return b:showmarks_previous_include
elseif exists('s:use_new_include')
" Recursive call from ShowMarks()
return b:showmarks_include
else
let s:use_previous_include = 1
call <sid>ShowMarksHideAll()
unlet s:use_previous_include
let s:use_new_include = 1
call <sid>ShowMarks()
unlet s:use_new_include
endif
endif
if !exists('g:showmarks_include')
let g:showmarks_include = s:all_marks
endif
if !exists('b:showmarks_include')
let b:showmarks_include = g:showmarks_include
endif
" Save this include setting so we can detect if it was changed.
let b:showmarks_previous_include = b:showmarks_include
return b:showmarks_include
endf
" Function: NameOfMark()
" Paramaters: mark - Specifies the mark to find the name of.
" Description: Convert marks that cannot be used as part of a variable name to
" something that can be. i.e. We cannot use [ as a variable-name suffix (as
" in 'placed_['; this function will return something like 63, so the variable
" will be something like 'placed_63').
" 10 is added to the mark's index to avoid colliding with the numeric marks
" 0-9 (since a non-word mark could be listed in showmarks_include in the
" first 10 characters if the user overrides the default).
" Returns: The name of the requested mark.
fun! s:NameOfMark(mark)
let name = a:mark
if a:mark =~# '\W'
let name = stridx(s:all_marks, a:mark) + 10
endif
return name
endf
" Function: VerifyText()
" Paramaters: which - Specifies the variable to verify.
" Description: Verify the validity of a showmarks_text{upper,lower,other} setup variable.
" Default to ">" if it is found to be invalid.
fun! s:VerifyText(which)
if strlen(g:showmarks_text{a:which}) == 0 || strlen(g:showmarks_text{a:which}) > 2
echohl ErrorMsg
echo "ShowMarks: text".a:which." must contain only 1 or 2 characters."
echohl None
let g:showmarks_text{a:which}=">"
endif
endf
" Function: ShowMarksSetup()
" Description: This function sets up the sign definitions for each mark.
" It uses the showmarks_textlower, showmarks_textupper and showmarks_textother
" variables to determine how to draw the mark.
fun! s:ShowMarksSetup()
" Make sure the textlower, textupper, and textother options are valid.
call s:VerifyText('lower')
call s:VerifyText('upper')
call s:VerifyText('other')
let n = 0
let s:maxmarks = strlen(s:all_marks)
while n < s:maxmarks
let c = strpart(s:all_marks, n, 1)
let nm = s:NameOfMark(c)
let text = '>'.c
let lhltext = ''
if c =~# '[a-z]'
if strlen(g:showmarks_textlower) == 1
let text=c.g:showmarks_textlower
elseif strlen(g:showmarks_textlower) == 2
let t1 = strpart(g:showmarks_textlower,0,1)
let t2 = strpart(g:showmarks_textlower,1,1)
if t1 == "\t"
let text=c.t2
elseif t2 == "\t"
let text=t1.c
else
let text=g:showmarks_textlower
endif
endif
let s:ShowMarksDLink{nm} = 'ShowMarksHLl'
if g:showmarks_hlline_lower == 1
let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm
endif
elseif c =~# '[A-Z]'
if strlen(g:showmarks_textupper) == 1
let text=c.g:showmarks_textupper
elseif strlen(g:showmarks_textupper) == 2
let t1 = strpart(g:showmarks_textupper,0,1)
let t2 = strpart(g:showmarks_textupper,1,1)
if t1 == "\t"
let text=c.t2
elseif t2 == "\t"
let text=t1.c
else
let text=g:showmarks_textupper
endif
endif
let s:ShowMarksDLink{nm} = 'ShowMarksHLu'
if g:showmarks_hlline_upper == 1
let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm
endif
else " Other signs, like ', ., etc.
if strlen(g:showmarks_textother) == 1
let text=c.g:showmarks_textother
elseif strlen(g:showmarks_textother) == 2
let t1 = strpart(g:showmarks_textother,0,1)
let t2 = strpart(g:showmarks_textother,1,1)
if t1 == "\t"
let text=c.t2
elseif t2 == "\t"
let text=t1.c
else
let text=g:showmarks_textother
endif
endif
let s:ShowMarksDLink{nm} = 'ShowMarksHLo'
if g:showmarks_hlline_other == 1
let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm
endif
endif
" Define the sign with a unique highlight which will be linked when placed.
exe 'sign define ShowMark'.nm.' '.lhltext.' text='.text.' texthl='.s:ShowMarksDLink{nm}.nm
let b:ShowMarksLink{nm} = ''
let n = n + 1
endw
endf
" Set things up
call s:ShowMarksSetup()
" Function: ShowMarksOn
" Description: Enable showmarks, and show them now.
fun! s:ShowMarksOn()
if g:showmarks_enable == 0
call <sid>ShowMarksToggle()
else
call <sid>ShowMarks()
endif
endf
" Function: ShowMarksToggle()
" Description: This function toggles whether marks are displayed or not.
fun! s:ShowMarksToggle()
if g:showmarks_enable == 0
let g:showmarks_enable = 1
call <sid>ShowMarks()
aug ShowMarks
au!
autocmd CursorHold * call s:ShowMarks()
aug END
else
let g:showmarks_enable = 0
call <sid>ShowMarksHideAll()
aug ShowMarks
au!
autocmd BufEnter * call s:ShowMarksHideAll()
aug END
endif
endf
" Function: ShowMarks()
" Description: This function runs through all the marks and displays or
" removes signs as appropriate. It is called on the CursorHold autocommand.
" We use the marked_{ln} variables (containing a timestamp) to track what marks
" we've shown (placed) in this call to ShowMarks; to only actually place the
" first mark on any particular line -- this forces only the first mark
" (according to the order of showmarks_include) to be shown (i.e., letters
" take precedence over marks like paragraph and sentence.)
fun! s:ShowMarks()
if g:showmarks_enable == 0
return
endif
if ((match(g:showmarks_ignore_type, "[Hh]") > -1) && (&buftype == "help" ))
\ || ((match(g:showmarks_ignore_type, "[Qq]") > -1) && (&buftype == "quickfix"))
\ || ((match(g:showmarks_ignore_type, "[Pp]") > -1) && (&pvw == 1 ))
\ || ((match(g:showmarks_ignore_type, "[Rr]") > -1) && (&readonly == 1 ))
\ || ((match(g:showmarks_ignore_type, "[Mm]") > -1) && (&modifiable == 0 ))
return
endif
let n = 0
let s:maxmarks = strlen(s:IncludeMarks())
while n < s:maxmarks
let c = strpart(s:IncludeMarks(), n, 1)
let nm = s:NameOfMark(c)
let id = n + (s:maxmarks * winbufnr(0))
let ln = line("'".c)
if ln == 0 && (exists('b:placed_'.nm) && b:placed_{nm} != ln)
exe 'sign unplace '.id.' buffer='.winbufnr(0)
elseif ln > 1 || c !~ '[a-zA-Z]'
" Have we already placed a mark here in this call to ShowMarks?
if exists('mark_at'.ln)
" Already placed a mark, set the highlight to multiple
if c =~# '[a-zA-Z]' && b:ShowMarksLink{mark_at{ln}} != 'ShowMarksHLm'
let b:ShowMarksLink{mark_at{ln}} = 'ShowMarksHLm'
exe 'hi link '.s:ShowMarksDLink{mark_at{ln}}.mark_at{ln}.' '.b:ShowMarksLink{mark_at{ln}}
endif
else
if !exists('b:ShowMarksLink'.nm) || b:ShowMarksLink{nm} != s:ShowMarksDLink{nm}
let b:ShowMarksLink{nm} = s:ShowMarksDLink{nm}
exe 'hi link '.s:ShowMarksDLink{nm}.nm.' '.b:ShowMarksLink{nm}
endif
let mark_at{ln} = nm
if !exists('b:placed_'.nm) || b:placed_{nm} != ln
exe 'sign unplace '.id.' buffer='.winbufnr(0)
exe 'sign place '.id.' name=ShowMark'.nm.' line='.ln.' buffer='.winbufnr(0)
let b:placed_{nm} = ln
endif
endif
endif
let n = n + 1
endw
endf
" Function: ShowMarksClearMark()
" Description: This function hides the mark at the current line.
" It simply moves the mark to line 1 and removes the sign.
" Only marks a-z and A-Z are supported.
fun! s:ShowMarksClearMark()
let ln = line(".")
let n = 0
let s:maxmarks = strlen(s:IncludeMarks())
while n < s:maxmarks
let c = strpart(s:IncludeMarks(), n, 1)
if c =~# '[a-zA-Z]' && ln == line("'".c)
let nm = s:NameOfMark(c)
let id = n + (s:maxmarks * winbufnr(0))
exe 'sign unplace '.id.' buffer='.winbufnr(0)
exe '1 mark '.c
let b:placed_{nm} = 1
endif
let n = n + 1
endw
endf
" Function: ShowMarksClearAll()
" Description: This function clears all marks in the buffer.
" It simply moves the marks to line 1 and removes the signs.
" Only marks a-z and A-Z are supported.
fun! s:ShowMarksClearAll()
let n = 0
let s:maxmarks = strlen(s:IncludeMarks())
while n < s:maxmarks
let c = strpart(s:IncludeMarks(), n, 1)
if c =~# '[a-zA-Z]'
let nm = s:NameOfMark(c)
let id = n + (s:maxmarks * winbufnr(0))
exe 'sign unplace '.id.' buffer='.winbufnr(0)
exe '1 mark '.c
let b:placed_{nm} = 1
endif
let n = n + 1
endw
endf
" Function: ShowMarksHideAll()
" Description: This function hides all marks in the buffer.
" It simply removes the signs.
fun! s:ShowMarksHideAll()
let n = 0
let s:maxmarks = strlen(s:IncludeMarks())
while n < s:maxmarks
let c = strpart(s:IncludeMarks(), n, 1)
let nm = s:NameOfMark(c)
if exists('b:placed_'.nm)
let id = n + (s:maxmarks * winbufnr(0))
exe 'sign unplace '.id.' buffer='.winbufnr(0)
unlet b:placed_{nm}
endif
let n = n + 1
endw
endf
" Function: ShowMarksPlaceMark()
" Description: This function will place the next unplaced mark (in priority
" order) to the current location. The idea here is to automate the placement
" of marks so the user doesn't have to remember which marks are placed or not.
" Hidden marks are considered to be unplaced.
" Only marks a-z are supported.
fun! s:ShowMarksPlaceMark()
" Find the first, next, and last [a-z] mark in showmarks_include (i.e.
" priority order), so we know where to "wrap".
let first_alpha_mark = -1
let last_alpha_mark = -1
let next_mark = -1
if !exists('b:previous_auto_mark')
let b:previous_auto_mark = -1
endif
" Find the next unused [a-z] mark (in priority order); if they're all
" used, find the next one after the previously auto-assigned mark.
let n = 0
let s:maxmarks = strlen(s:IncludeMarks())
while n < s:maxmarks
let c = strpart(s:IncludeMarks(), n, 1)
if c =~# '[a-z]'
if line("'".c) <= 1
" Found an unused [a-z] mark; we're done.
let next_mark = n
break
endif
if first_alpha_mark < 0
let first_alpha_mark = n
endif
let last_alpha_mark = n
if n > b:previous_auto_mark && next_mark == -1
let next_mark = n
endif
endif
let n = n + 1
endw
if next_mark == -1 && (b:previous_auto_mark == -1 || b:previous_auto_mark == last_alpha_mark)
" Didn't find an unused mark, and haven't placed any auto-chosen marks yet,
" or the previously placed auto-chosen mark was the last alpha mark --
" use the first alpha mark this time.
let next_mark = first_alpha_mark
endif
if (next_mark == -1)
echohl WarningMsg
echo 'No marks in [a-z] included! (No "next mark" to choose from)'
echohl None
return
endif
let c = strpart(s:IncludeMarks(), next_mark, 1)
let b:previous_auto_mark = next_mark
exe 'mark '.c
call <sid>ShowMarks()
endf
" -----------------------------------------------------------------------------
" vim:ts=4:sw=4:noet
-247
View File
@@ -1,247 +0,0 @@
" File: snipMate.vim
" Author: Michael Sanders
" Last Updated: July 13, 2009
" Version: 0.83
" Description: snipMate.vim implements some of TextMate's snippets features in
" Vim. A snippet is a piece of often-typed text that you can
" insert into your document using a trigger word followed by a "<tab>".
"
" For more help see snipMate.txt; you can do this by using:
" :helptags ~/.vim/doc
" :h snipMate.txt
if exists('loaded_snips') || &cp || version < 700
finish
endif
let loaded_snips = 1
if !exists('snips_author') | let snips_author = 'Me' | endif
au BufRead,BufNewFile *.snippets\= set ft=snippet
au FileType snippet setl noet fdm=indent
let s:snippets = {} | let s:multi_snips = {}
if !exists('snippets_dir')
let snippets_dir = substitute(globpath(&rtp, 'snippets/'), "\n", ',', 'g')
endif
fun! MakeSnip(scope, trigger, content, ...)
let multisnip = a:0 && a:1 != ''
let var = multisnip ? 's:multi_snips' : 's:snippets'
if !has_key({var}, a:scope) | let {var}[a:scope] = {} | endif
if !has_key({var}[a:scope], a:trigger)
let {var}[a:scope][a:trigger] = multisnip ? [[a:1, a:content]] : a:content
elseif multisnip | let {var}[a:scope][a:trigger] += [[a:1, a:content]]
else
echom 'Warning in snipMate.vim: Snippet '.a:trigger.' is already defined.'
\ .' See :h multi_snip for help on snippets with multiple matches.'
endif
endf
fun! ExtractSnips(dir, ft)
for path in split(globpath(a:dir, '*'), "\n")
if isdirectory(path)
let pathname = fnamemodify(path, ':t')
for snipFile in split(globpath(path, '*.snippet'), "\n")
call s:ProcessFile(snipFile, a:ft, pathname)
endfor
elseif fnamemodify(path, ':e') == 'snippet'
call s:ProcessFile(path, a:ft)
endif
endfor
endf
" Processes a single-snippet file; optionally add the name of the parent
" directory for a snippet with multiple matches.
fun s:ProcessFile(file, ft, ...)
let keyword = fnamemodify(a:file, ':t:r')
if keyword == '' | return | endif
try
let text = join(readfile(a:file), "\n")
catch /E484/
echom "Error in snipMate.vim: couldn't read file: ".a:file
endtry
return a:0 ? MakeSnip(a:ft, a:1, text, keyword)
\ : MakeSnip(a:ft, keyword, text)
endf
fun! ExtractSnipsFile(file, ft)
if !filereadable(a:file) | return | endif
let text = readfile(a:file)
let inSnip = 0
for line in text + ["\n"]
if inSnip && (line[0] == "\t" || line == '')
let content .= strpart(line, 1)."\n"
continue
elseif inSnip
call MakeSnip(a:ft, trigger, content[:-2], name)
let inSnip = 0
endif
if line[:6] == 'snippet'
let inSnip = 1
let trigger = strpart(line, 8)
let name = ''
let space = stridx(trigger, ' ') + 1
if space " Process multi snip
let name = strpart(trigger, space)
let trigger = strpart(trigger, 0, space - 1)
endif
let content = ''
endif
endfor
endf
fun! ResetSnippets()
let s:snippets = {} | let s:multi_snips = {} | let g:did_ft = {}
endf
let g:did_ft = {}
fun! GetSnippets(dir, filetypes)
for ft in split(a:filetypes, '\.')
if has_key(g:did_ft, ft) | continue | endif
call s:DefineSnips(a:dir, ft, ft)
if ft == 'objc' || ft == 'cpp' || ft == 'cs'
call s:DefineSnips(a:dir, 'c', ft)
elseif ft == 'xhtml'
call s:DefineSnips(a:dir, 'html', 'xhtml')
endif
let g:did_ft[ft] = 1
endfor
endf
" Define "aliasft" snippets for the filetype "realft".
fun s:DefineSnips(dir, aliasft, realft)
for path in split(globpath(a:dir, a:aliasft.'/')."\n".
\ globpath(a:dir, a:aliasft.'-*/'), "\n")
call ExtractSnips(path, a:realft)
endfor
for path in split(globpath(a:dir, a:aliasft.'.snippets')."\n".
\ globpath(a:dir, a:aliasft.'-*.snippets'), "\n")
call ExtractSnipsFile(path, a:realft)
endfor
endf
fun! TriggerSnippet()
if exists('g:SuperTabMappingForward')
if g:SuperTabMappingForward == "<tab>"
let SuperTabKey = "\<c-n>"
elseif g:SuperTabMappingBackward == "<tab>"
let SuperTabKey = "\<c-p>"
endif
endif
if pumvisible() " Update snippet if completion is used, or deal with supertab
if exists('SuperTabKey')
call feedkeys(SuperTabKey) | return ''
endif
call feedkeys("\<esc>a", 'n') " Close completion menu
call feedkeys("\<tab>") | return ''
endif
if exists('g:snipPos') | return snipMate#jumpTabStop(0) | endif
let word = matchstr(getline('.'), '\S\+\%'.col('.').'c')
for scope in [bufnr('%')] + split(&ft, '\.') + ['_']
let [trigger, snippet] = s:GetSnippet(word, scope)
" If word is a trigger for a snippet, delete the trigger & expand
" the snippet.
if snippet != ''
let col = col('.') - len(trigger)
sil exe 's/\V'.escape(trigger, '/.').'\%#//'
return snipMate#expandSnip(snippet, col)
endif
endfor
if exists('SuperTabKey')
call feedkeys(SuperTabKey)
return ''
endif
return "\<tab>"
endf
fun! BackwardsSnippet()
if exists('g:snipPos') | return snipMate#jumpTabStop(1) | endif
if exists('g:SuperTabMappingForward')
if g:SuperTabMappingBackward == "<s-tab>"
let SuperTabKey = "\<c-p>"
elseif g:SuperTabMappingForward == "<s-tab>"
let SuperTabKey = "\<c-n>"
endif
endif
if exists('SuperTabKey')
call feedkeys(SuperTabKey)
return ''
endif
return "\<s-tab>"
endf
" Check if word under cursor is snippet trigger; if it isn't, try checking if
" the text after non-word characters is (e.g. check for "foo" in "bar.foo")
fun s:GetSnippet(word, scope)
let word = a:word | let snippet = ''
while snippet == ''
if exists('s:snippets["'.a:scope.'"]["'.escape(word, '\"').'"]')
let snippet = s:snippets[a:scope][word]
elseif exists('s:multi_snips["'.a:scope.'"]["'.escape(word, '\"').'"]')
let snippet = s:ChooseSnippet(a:scope, word)
if snippet == '' | break | endif
else
if match(word, '\W') == -1 | break | endif
let word = substitute(word, '.\{-}\W', '', '')
endif
endw
if word == '' && a:word != '.' && stridx(a:word, '.') != -1
let [word, snippet] = s:GetSnippet('.', a:scope)
endif
return [word, snippet]
endf
fun s:ChooseSnippet(scope, trigger)
let snippet = []
let i = 1
for snip in s:multi_snips[a:scope][a:trigger]
let snippet += [i.'. '.snip[0]]
let i += 1
endfor
if i == 2 | return s:multi_snips[a:scope][a:trigger][0][1] | endif
let num = inputlist(snippet) - 1
return num == -1 ? '' : s:multi_snips[a:scope][a:trigger][num][1]
endf
fun! ShowAvailableSnips()
let line = getline('.')
let col = col('.')
let word = matchstr(getline('.'), '\S\+\%'.col.'c')
let words = [word]
if stridx(word, '.')
let words += split(word, '\.', 1)
endif
let matchlen = 0
let matches = []
for scope in [bufnr('%')] + split(&ft, '\.') + ['_']
let triggers = has_key(s:snippets, scope) ? keys(s:snippets[scope]) : []
if has_key(s:multi_snips, scope)
let triggers += keys(s:multi_snips[scope])
endif
for trigger in triggers
for word in words
if word == ''
let matches += [trigger] " Show all matches if word is empty
elseif trigger =~ '^'.word
let matches += [trigger]
let len = len(word)
if len > matchlen | let matchlen = len | endif
endif
endfor
endfor
endfor
" This is to avoid a bug with Vim when using complete(col - matchlen, matches)
" (Issue#46 on the Google Code snipMate issue tracker).
call setline(line('.'), substitute(line, repeat('.', matchlen).'\%'.col.'c', '', ''))
call complete(col, matches)
return ''
endf
" vim:noet:sw=4:ts=4:ft=vim
-625
View File
@@ -1,625 +0,0 @@
" surround.vim - Surroundings
" Author: Tim Pope <vimNOSPAM@tpope.org>
" Version: 1.90
" GetLatestVimScripts: 1697 1 :AutoInstall: surround.vim
"
" See surround.txt for help. This can be accessed by doing
"
" :helptags ~/.vim/doc
" :help surround
"
" Licensed under the same terms as Vim itself.
" ============================================================================
" Exit quickly when:
" - this plugin was already loaded or disabled
" - when 'compatible' is set
if (exists("g:loaded_surround") && g:loaded_surround) || &cp
finish
endif
let g:loaded_surround = 1
let s:cpo_save = &cpo
set cpo&vim
" Input functions {{{1
function! s:getchar()
let c = getchar()
if c =~ '^\d\+$'
let c = nr2char(c)
endif
return c
endfunction
function! s:inputtarget()
let c = s:getchar()
while c =~ '^\d\+$'
let c = c . s:getchar()
endwhile
if c == " "
let c = c . s:getchar()
endif
if c =~ "\<Esc>\|\<C-C>\|\0"
return ""
else
return c
endif
endfunction
function! s:inputreplacement()
"echo '-- SURROUND --'
let c = s:getchar()
if c == " "
let c = c . s:getchar()
endif
if c =~ "\<Esc>" || c =~ "\<C-C>"
return ""
else
return c
endif
endfunction
function! s:beep()
exe "norm! \<Esc>"
return ""
endfunction
function! s:redraw()
redraw
return ""
endfunction
" }}}1
" Wrapping functions {{{1
function! s:extractbefore(str)
if a:str =~ '\r'
return matchstr(a:str,'.*\ze\r')
else
return matchstr(a:str,'.*\ze\n')
endif
endfunction
function! s:extractafter(str)
if a:str =~ '\r'
return matchstr(a:str,'\r\zs.*')
else
return matchstr(a:str,'\n\zs.*')
endif
endfunction
function! s:repeat(str,count)
let cnt = a:count
let str = ""
while cnt > 0
let str = str . a:str
let cnt = cnt - 1
endwhile
return str
endfunction
function! s:fixindent(str,spc)
let str = substitute(a:str,'\t',s:repeat(' ',&sw),'g')
let spc = substitute(a:spc,'\t',s:repeat(' ',&sw),'g')
let str = substitute(str,'\(\n\|\%^\).\@=','\1'.spc,'g')
if ! &et
let str = substitute(str,'\s\{'.&ts.'\}',"\t",'g')
endif
return str
endfunction
function! s:process(string)
let i = 0
while i < 7
let i = i + 1
let repl_{i} = ''
let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i))
if m != ''
let m = substitute(strpart(m,1),'\r.*','','')
let repl_{i} = input(substitute(m,':\s*$','','').': ')
endif
endwhile
let s = ""
let i = 0
while i < strlen(a:string)
let char = strpart(a:string,i,1)
if char2nr(char) < 8
let next = stridx(a:string,char,i+1)
if next == -1
let s = s . char
else
let insertion = repl_{char2nr(char)}
let subs = strpart(a:string,i+1,next-i-1)
let subs = matchstr(subs,'\r.*')
while subs =~ '^\r.*\r'
let sub = matchstr(subs,"^\r\\zs[^\r]*\r[^\r]*")
let subs = strpart(subs,strlen(sub)+1)
let r = stridx(sub,"\r")
let insertion = substitute(insertion,strpart(sub,0,r),strpart(sub,r+1),'')
endwhile
let s = s . insertion
let i = next
endif
else
let s = s . char
endif
let i = i + 1
endwhile
return s
endfunction
function! s:wrap(string,char,type,...)
let keeper = a:string
let newchar = a:char
let type = a:type
let linemode = type ==# 'V' ? 1 : 0
let special = a:0 ? a:1 : 0
let before = ""
let after = ""
if type ==# "V"
let initspaces = matchstr(keeper,'\%^\s*')
else
let initspaces = matchstr(getline('.'),'\%^\s*')
endif
" Duplicate b's are just placeholders (removed)
let pairs = "b()B{}r[]a<>"
let extraspace = ""
if newchar =~ '^ '
let newchar = strpart(newchar,1)
let extraspace = ' '
endif
let idx = stridx(pairs,newchar)
if newchar == ' '
let before = ''
let after = ''
elseif exists("b:surround_".char2nr(newchar))
let all = s:process(b:surround_{char2nr(newchar)})
let before = s:extractbefore(all)
let after = s:extractafter(all)
elseif exists("g:surround_".char2nr(newchar))
let all = s:process(g:surround_{char2nr(newchar)})
let before = s:extractbefore(all)
let after = s:extractafter(all)
elseif newchar ==# "p"
let before = "\n"
let after = "\n\n"
elseif newchar =~# "[tT\<C-T><,]"
let dounmapp = 0
let dounmapb = 0
if !maparg(">","c")
let dounmapb= 1
" Hide from AsNeeded
exe "cn"."oremap > <CR>"
endif
let default = ""
if newchar ==# "T"
if !exists("s:lastdel")
let s:lastdel = ""
endif
let default = matchstr(s:lastdel,'<\zs.\{-\}\ze>')
endif
let tag = input("<",default)
echo "<".substitute(tag,'>*$','>','')
if dounmapb
silent! cunmap >
endif
if tag != ""
let tag = substitute(tag,'>*$','','')
let before = '<'.tag.'>'
if tag =~ '/$'
let after = ''
else
let after = '</'.substitute(tag,' .*','','').'>'
endif
if newchar == "\<C-T>" || newchar == ","
if type ==# "v" || type ==# "V"
let before = before . "\n\t"
endif
if type ==# "v"
let after = "\n". after
endif
endif
endif
elseif newchar ==# 'l' || newchar == '\'
" LaTeX
let env = input('\begin{')
let env = '{' . env
let env = env . s:closematch(env)
echo '\begin'.env
if env != ""
let before = '\begin'.env
let after = '\end'.matchstr(env,'[^}]*').'}'
endif
"if type ==# 'v' || type ==# 'V'
"let before = before ."\n\t"
"endif
"if type ==# 'v'
"let after = "\n".initspaces.after
"endif
elseif newchar ==# 'f' || newchar ==# 'F'
let fnc = input('function: ')
if fnc != ""
let before = substitute(fnc,'($','','').'('
let after = ')'
if newchar ==# 'F'
let before = before . ' '
let after = ' ' . after
endif
endif
elseif idx >= 0
let spc = (idx % 3) == 1 ? " " : ""
let idx = idx / 3 * 3
let before = strpart(pairs,idx+1,1) . spc
let after = spc . strpart(pairs,idx+2,1)
elseif newchar == "\<C-[>" || newchar == "\<C-]>"
let before = "{\n\t"
let after = "\n}"
elseif newchar !~ '\a'
let before = newchar
let after = newchar
else
let before = ''
let after = ''
endif
"let before = substitute(before,'\n','\n'.initspaces,'g')
let after = substitute(after ,'\n','\n'.initspaces,'g')
"let after = substitute(after,"\n\\s*\<C-U>\\s*",'\n','g')
if type ==# 'V' || (special && type ==# "v")
let before = substitute(before,' \+$','','')
let after = substitute(after ,'^ \+','','')
if after !~ '^\n'
let after = initspaces.after
endif
if keeper !~ '\n$' && after !~ '^\n'
let keeper = keeper . "\n"
elseif keeper =~ '\n$' && after =~ '^\n'
let after = strpart(after,1)
endif
if before !~ '\n\s*$'
let before = before . "\n"
if special
let before = before . "\t"
endif
endif
endif
if type ==# 'V'
let before = initspaces.before
endif
if before =~ '\n\s*\%$'
if type ==# 'v'
let keeper = initspaces.keeper
endif
let padding = matchstr(before,'\n\zs\s\+\%$')
let before = substitute(before,'\n\s\+\%$','\n','')
let keeper = s:fixindent(keeper,padding)
endif
if type ==# 'V'
let keeper = before.keeper.after
elseif type =~ "^\<C-V>"
" Really we should be iterating over the buffer
let repl = substitute(before,'[\\~]','\\&','g').'\1'.substitute(after,'[\\~]','\\&','g')
let repl = substitute(repl,'\n',' ','g')
let keeper = substitute(keeper."\n",'\(.\{-\}\)\(\n\)',repl.'\n','g')
let keeper = substitute(keeper,'\n\%$','','')
else
let keeper = before.extraspace.keeper.extraspace.after
endif
return keeper
endfunction
function! s:wrapreg(reg,char,...)
let orig = getreg(a:reg)
let type = substitute(getregtype(a:reg),'\d\+$','','')
let special = a:0 ? a:1 : 0
let new = s:wrap(orig,a:char,type,special)
call setreg(a:reg,new,type)
endfunction
" }}}1
function! s:insert(...) " {{{1
" Optional argument causes the result to appear on 3 lines, not 1
"call inputsave()
let linemode = a:0 ? a:1 : 0
let char = s:inputreplacement()
while char == "\<CR>" || char == "\<C-S>"
" TODO: use total count for additional blank lines
let linemode = linemode + 1
let char = s:inputreplacement()
endwhile
"call inputrestore()
if char == ""
return ""
endif
"call inputsave()
let cb_save = &clipboard
set clipboard-=unnamed
let reg_save = @@
call setreg('"',"\r",'v')
call s:wrapreg('"',char,linemode)
" If line mode is used and the surrounding consists solely of a suffix,
" remove the initial newline. This fits a use case of mine but is a
" little inconsistent. Is there anyone that would prefer the simpler
" behavior of just inserting the newline?
if linemode && match(getreg('"'),'^\n\s*\zs.*') == 0
call setreg('"',matchstr(getreg('"'),'^\n\s*\zs.*'),getregtype('"'))
endif
" This can be used to append a placeholder to the end
if exists("g:surround_insert_tail")
call setreg('"',g:surround_insert_tail,"a".getregtype('"'))
endif
"if linemode
"call setreg('"',substitute(getreg('"'),'^\s\+','',''),'c')
"endif
if col('.') >= col('$')
norm! ""p
else
norm! ""P
endif
if linemode
call s:reindent()
endif
norm! `]
call search('\r','bW')
let @@ = reg_save
let &clipboard = cb_save
return "\<Del>"
endfunction " }}}1
function! s:reindent() " {{{1
if exists("b:surround_indent") ? b:surround_indent : (exists("g:surround_indent") && g:surround_indent)
silent norm! '[=']
endif
endfunction " }}}1
function! s:dosurround(...) " {{{1
let scount = v:count1
let char = (a:0 ? a:1 : s:inputtarget())
let spc = ""
if char =~ '^\d\+'
let scount = scount * matchstr(char,'^\d\+')
let char = substitute(char,'^\d\+','','')
endif
if char =~ '^ '
let char = strpart(char,1)
let spc = 1
endif
if char == 'a'
let char = '>'
endif
if char == 'r'
let char = ']'
endif
let newchar = ""
if a:0 > 1
let newchar = a:2
if newchar == "\<Esc>" || newchar == "\<C-C>" || newchar == ""
return s:beep()
endif
endif
let cb_save = &clipboard
set clipboard-=unnamed
let append = ""
let original = getreg('"')
let otype = getregtype('"')
call setreg('"',"")
let strcount = (scount == 1 ? "" : scount)
if char == '/'
exe 'norm! '.strcount.'[/d'.strcount.']/'
else
exe 'norm! d'.strcount.'i'.char
endif
let keeper = getreg('"')
let okeeper = keeper " for reindent below
if keeper == ""
call setreg('"',original,otype)
let &clipboard = cb_save
return ""
endif
let oldline = getline('.')
let oldlnum = line('.')
if char ==# "p"
call setreg('"','','V')
elseif char ==# "s" || char ==# "w" || char ==# "W"
" Do nothing
call setreg('"','')
elseif char =~ "[\"'`]"
exe "norm! i \<Esc>d2i".char
call setreg('"',substitute(getreg('"'),' ','',''))
elseif char == '/'
norm! "_x
call setreg('"','/**/',"c")
let keeper = substitute(substitute(keeper,'^/\*\s\=','',''),'\s\=\*$','','')
else
" One character backwards
call search('.','bW')
exe "norm! da".char
endif
let removed = getreg('"')
let rem2 = substitute(removed,'\n.*','','')
let oldhead = strpart(oldline,0,strlen(oldline)-strlen(rem2))
let oldtail = strpart(oldline, strlen(oldline)-strlen(rem2))
let regtype = getregtype('"')
if char =~# '[\[({<T]' || spc
let keeper = substitute(keeper,'^\s\+','','')
let keeper = substitute(keeper,'\s\+$','','')
endif
if col("']") == col("$") && col('.') + 1 == col('$')
if oldhead =~# '^\s*$' && a:0 < 2
let keeper = substitute(keeper,'\%^\n'.oldhead.'\(\s*.\{-\}\)\n\s*\%$','\1','')
endif
let pcmd = "p"
else
let pcmd = "P"
endif
if line('.') < oldlnum && regtype ==# "V"
let pcmd = "p"
endif
call setreg('"',keeper,regtype)
if newchar != ""
call s:wrapreg('"',newchar)
endif
silent exe 'norm! ""'.pcmd.'`['
if removed =~ '\n' || okeeper =~ '\n' || getreg('"') =~ '\n'
call s:reindent()
endif
if getline('.') =~ '^\s\+$' && keeper =~ '^\s*\n'
silent norm! cc
endif
call setreg('"',removed,regtype)
let s:lastdel = removed
let &clipboard = cb_save
if newchar == ""
silent! call repeat#set("\<Plug>Dsurround".char,scount)
else
silent! call repeat#set("\<Plug>Csurround".char.newchar,scount)
endif
endfunction " }}}1
function! s:changesurround() " {{{1
let a = s:inputtarget()
if a == ""
return s:beep()
endif
let b = s:inputreplacement()
if b == ""
return s:beep()
endif
call s:dosurround(a,b)
endfunction " }}}1
function! s:opfunc(type,...) " {{{1
let char = s:inputreplacement()
if char == ""
return s:beep()
endif
let reg = '"'
let sel_save = &selection
let &selection = "inclusive"
let cb_save = &clipboard
set clipboard-=unnamed
let reg_save = getreg(reg)
let reg_type = getregtype(reg)
"call setreg(reg,"\n","c")
let type = a:type
if a:type == "char"
silent exe 'norm! v`[o`]"'.reg.'y'
let type = 'v'
elseif a:type == "line"
silent exe 'norm! `[V`]"'.reg.'y'
let type = 'V'
elseif a:type ==# "v" || a:type ==# "V" || a:type ==# "\<C-V>"
let ve = &virtualedit
if !(a:0 && a:1)
set virtualedit=
endif
silent exe 'norm! gv"'.reg.'y'
let &virtualedit = ve
elseif a:type =~ '^\d\+$'
let type = 'v'
silent exe 'norm! ^v'.a:type.'$h"'.reg.'y'
if mode() ==# 'v'
norm! v
return s:beep()
endif
else
let &selection = sel_save
let &clipboard = cb_save
return s:beep()
endif
let keeper = getreg(reg)
if type ==# "v" && a:type !=# "v"
let append = matchstr(keeper,'\_s\@<!\s*$')
let keeper = substitute(keeper,'\_s\@<!\s*$','','')
endif
call setreg(reg,keeper,type)
call s:wrapreg(reg,char,a:0 && a:1)
if type ==# "v" && a:type !=# "v" && append != ""
call setreg(reg,append,"ac")
endif
silent exe 'norm! gv'.(reg == '"' ? '' : '"' . reg).'p`['
if type ==# 'V' || (getreg(reg) =~ '\n' && type ==# 'v')
call s:reindent()
endif
call setreg(reg,reg_save,reg_type)
let &selection = sel_save
let &clipboard = cb_save
if a:type =~ '^\d\+$'
silent! call repeat#set("\<Plug>Y".(a:0 && a:1 ? "S" : "s")."surround".char,a:type)
endif
endfunction
function! s:opfunc2(arg)
call s:opfunc(a:arg,1)
endfunction " }}}1
function! s:closematch(str) " {{{1
" Close an open (, {, [, or < on the command line.
let tail = matchstr(a:str,'.[^\[\](){}<>]*$')
if tail =~ '^\[.\+'
return "]"
elseif tail =~ '^(.\+'
return ")"
elseif tail =~ '^{.\+'
return "}"
elseif tail =~ '^<.+'
return ">"
else
return ""
endif
endfunction " }}}1
nnoremap <silent> <Plug>Dsurround :<C-U>call <SID>dosurround(<SID>inputtarget())<CR>
nnoremap <silent> <Plug>Csurround :<C-U>call <SID>changesurround()<CR>
nnoremap <silent> <Plug>Yssurround :<C-U>call <SID>opfunc(v:count1)<CR>
nnoremap <silent> <Plug>YSsurround :<C-U>call <SID>opfunc2(v:count1)<CR>
" <C-U> discards the numerical argument but there's not much we can do with it
nnoremap <silent> <Plug>Ysurround :<C-U>set opfunc=<SID>opfunc<CR>g@
nnoremap <silent> <Plug>YSurround :<C-U>set opfunc=<SID>opfunc2<CR>g@
vnoremap <silent> <Plug>Vsurround :<C-U>call <SID>opfunc(visualmode())<CR>
vnoremap <silent> <Plug>VSurround :<C-U>call <SID>opfunc(visualmode(),visualmode() ==# 'V' ? 1 : 0)<CR>
vnoremap <silent> <Plug>VgSurround :<C-U>call <SID>opfunc(visualmode(),visualmode() ==# 'V' ? 0 : 1)<CR>
inoremap <silent> <Plug>Isurround <C-R>=<SID>insert()<CR>
inoremap <silent> <Plug>ISurround <C-R>=<SID>insert(1)<CR>
if !exists("g:surround_no_mappings") || ! g:surround_no_mappings
nmap ds <Plug>Dsurround
nmap cs <Plug>Csurround
nmap ys <Plug>Ysurround
nmap yS <Plug>YSurround
nmap yss <Plug>Yssurround
nmap ySs <Plug>YSsurround
nmap ySS <Plug>YSsurround
if !hasmapto("<Plug>Vsurround","v") && !hasmapto("<Plug>VSurround","v")
if exists(":xmap")
xmap s <Plug>Vsurround
else
vmap s <Plug>Vsurround
endif
endif
if !hasmapto("<Plug>VSurround","v")
if exists(":xmap")
xmap S <Plug>VSurround
else
vmap S <Plug>VSurround
endif
endif
if exists(":xmap")
xmap gS <Plug>VgSurround
else
vmap gS <Plug>VgSurround
endif
if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i")
imap <C-S> <Plug>Isurround
endif
imap <C-G>s <Plug>Isurround
imap <C-G>S <Plug>ISurround
"Implemented internally instead
"imap <C-S><C-S> <Plug>ISurround
endif
let &cpo = s:cpo_save
" vim:set ft=vim sw=2 sts=2 et:
-118
View File
@@ -1,118 +0,0 @@
" ============================================================================
" File: tagbar.vim
" Description: List the current file's tags in a sidebar, ordered by class etc
" Author: Jan Larres <jan@majutsushi.net>
" Licence: Vim licence
" Website: http://majutsushi.github.com/tagbar/
" Version: 2.3
" Note: This plugin was heavily inspired by the 'Taglist' plugin by
" Yegappan Lakshmanan and uses a small amount of code from it.
"
" Original taglist copyright notice:
" Permission is hereby granted to use and distribute this code,
" with or without modifications, provided that this copyright
" notice is copied with it. Like anything else that's free,
" taglist.vim is provided *as is* and comes with no warranty of
" any kind, either expressed or implied. In no event will the
" copyright holder be liable for any damamges resulting from the
" use of this software.
" ============================================================================
scriptencoding utf-8
if &cp || exists('g:loaded_tagbar')
finish
endif
" Basic init {{{1
if v:version < 700
echohl WarningMsg
echomsg 'Tagbar: Vim version is too old, Tagbar requires at least 7.0'
echohl None
finish
endif
if v:version == 700 && !has('patch167')
echohl WarningMsg
echomsg 'Tagbar: Vim versions lower than 7.0.167 have a bug'
\ 'that prevents this version of Tagbar from working.'
\ 'Please use the alternate version posted on the website.'
echohl None
finish
endif
if !exists('g:tagbar_left')
let g:tagbar_left = 0
endif
if !exists('g:tagbar_width')
let g:tagbar_width = 40
endif
if !exists('g:tagbar_autoclose')
let g:tagbar_autoclose = 0
endif
if !exists('g:tagbar_autofocus')
let g:tagbar_autofocus = 0
endif
if !exists('g:tagbar_sort')
let g:tagbar_sort = 1
endif
if !exists('g:tagbar_compact')
let g:tagbar_compact = 0
endif
if !exists('g:tagbar_expand')
let g:tagbar_expand = 0
endif
if !exists('g:tagbar_singleclick')
let g:tagbar_singleclick = 0
endif
if !exists('g:tagbar_foldlevel')
let g:tagbar_foldlevel = 99
endif
if !exists('g:tagbar_iconchars')
if has('multi_byte') && has('unix') && &encoding == 'utf-8' &&
\ (empty(&termencoding) || &termencoding == 'utf-8')
let g:tagbar_iconchars = ['▶', '▼']
else
let g:tagbar_iconchars = ['+', '-']
endif
endif
if !exists('g:tagbar_autoshowtag')
let g:tagbar_autoshowtag = 0
endif
if !exists('g:tagbar_updateonsave_maxlines')
let g:tagbar_updateonsave_maxlines = 5000
endif
if !exists('g:tagbar_systemenc')
let g:tagbar_systemenc = &encoding
endif
augroup TagbarSession
autocmd!
autocmd SessionLoadPost * nested call tagbar#RestoreSession()
augroup END
" Commands {{{1
command! -nargs=0 TagbarToggle call tagbar#ToggleWindow()
command! -nargs=? TagbarOpen call tagbar#OpenWindow(<f-args>)
command! -nargs=0 TagbarOpenAutoClose call tagbar#OpenWindow('fc')
command! -nargs=0 TagbarClose call tagbar#CloseWindow()
command! -nargs=1 TagbarSetFoldlevel call tagbar#SetFoldLevel(<args>)
command! -nargs=0 TagbarShowTag call tagbar#OpenParents()
command! -nargs=? TagbarDebug call tagbar#StartDebug(<f-args>)
command! -nargs=0 TagbarDebugEnd call tagbar#StopDebug()
" Modeline {{{1
" vim: ts=8 sw=4 sts=4 et foldenable foldmethod=marker foldcolumn=1
-127
View File
@@ -1,127 +0,0 @@
" Author: Eric Van Dewoestine
"
" License: {{{
" Copyright (c) 2005 - 2010, Eric Van Dewoestine
" All rights reserved.
"
" Redistribution and use of this software in source and binary forms, with
" or without modification, are permitted provided that the following
" conditions are met:
"
" * Redistributions of source code must retain the above
" copyright notice, this list of conditions and the
" following disclaimer.
"
" * Redistributions in binary form must reproduce the above
" copyright notice, this list of conditions and the
" following disclaimer in the documentation and/or other
" materials provided with the distribution.
"
" * Neither the name of Eric Van Dewoestine nor the names of its
" contributors may be used to endorse or promote products derived from
" this software without specific prior written permission of
" Eric Van Dewoestine.
"
" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
" IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
" THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
" CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
" EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
" PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
" LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
" NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
" SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
" }}}
if exists('g:taglisttoo_loaded') ||
\ (exists('g:TaglistTooEnabled') && !g:TaglistTooEnabled) ||
\ !has('python')
finish
endif
let g:taglisttoo_loaded = 1
" try to disable taglist.vim
let g:loaded_taglist = 1
" Global Variables {{{
if !exists('g:Tlist_Ctags_Cmd')
if executable('exuberant-ctags')
let g:Tlist_Ctags_Cmd = 'exuberant-ctags'
elseif executable('ctags')
let g:Tlist_Ctags_Cmd = 'ctags'
elseif executable('ctags.exe')
let g:Tlist_Ctags_Cmd = 'ctags.exe'
elseif executable('tags')
let g:Tlist_Ctags_Cmd = 'tags'
endif
endif
" no ctags found, no need to continue.
if !exists('g:Tlist_Ctags_Cmd')
echohl WarningMsg | echom 'ctags not found' | echohl Normal
finish
endif
if !exists('g:Tlist_Auto_Open')
let g:Tlist_Auto_Open = 0
endif
if !exists("g:TaglistTooPosition")
if exists('Tlist_Use_Right_Window') && Tlist_Use_Right_Window
let g:TaglistTooPosition = 'right'
else
let g:TaglistTooPosition = 'left'
endif
endif
if !exists('g:TagList_title')
let g:TagList_title = "[TagList]"
endif
if !exists('g:Tlist_WinWidth')
let g:Tlist_WinWidth = 30
endif
if !exists('g:Tlist_Sort_Type')
let g:Tlist_Sort_Type = 'name'
endif
if !exists('g:TaglistTooTagEcho')
let g:TaglistTooTagEcho = 1
endif
if g:Tlist_Auto_Open && !exists('g:Tlist_Temp_Disable')
augroup taglisttoo_autoopen
autocmd!
autocmd VimEnter * nested call taglisttoo#taglist#AutoOpen()
augroup END
" Auto open on new tabs as well.
if v:version >= 700
autocmd taglisttoo_autoopen BufWinEnter *
\ if tabpagenr() > 1 &&
\ !exists('t:Tlist_Auto_Opened') &&
\ !exists('g:SessionLoad') |
\ call taglisttoo#taglist#AutoOpen() |
\ let t:Tlist_Auto_Opened = 1 |
\ endif
endif
endif
augroup taglisttoo_file_session
autocmd!
autocmd SessionLoadPost * call taglisttoo#taglist#Restore()
augroup END
" }}}
" Command Declarations {{{
if !exists(":TlistToo")
command TlistToo :call taglisttoo#taglist#Taglist()
endif
" }}}
" vim:ft=vim:fdm=marker
-264
View File
@@ -1,264 +0,0 @@
" vim600: set foldmethod=marker:
"
" BZR extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Options documentation: {{{2
"
" VCSCommandBZRExec
" This variable specifies the BZR executable. If not set, it defaults to
" 'bzr' executed from the user's executable path.
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandBZRExec', 'bzr'))
" BZR is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:bzrFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke bzr suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandBZRExec', 'bzr')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the BZR executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'BZR'
let fullCmd = s:Executable() . ' ' . a:cmd
return VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
else
throw 'BZR VCSCommand plugin called on non-BZR item.'
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:bzrFunctions.Identify(buffer) {{{2
function! s:bzrFunctions.Identify(buffer)
let fileName = resolve(bufname(a:buffer))
let l:save_bzr_log=$BZR_LOG
try
let $BZR_LOG=has("win32") || has("win95") || has("win64") || has("win16") ? "nul" : "/dev/null"
let statusText = s:VCSCommandUtility.system(s:Executable() . ' info -- "' . fileName . '"')
finally
let $BZR_LOG=l:save_bzr_log
endtry
if(v:shell_error)
return 0
else
return 1
endif
endfunction
" Function: s:bzrFunctions.Add() {{{2
function! s:bzrFunctions.Add(argList)
return s:DoCommand(join(['add'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:bzrFunctions.Annotate(argList) {{{2
function! s:bzrFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype ==? 'bzrannotate'
" Perform annotation of the version indicated by the current line.
let caption = matchstr(getline('.'),'\v^\s+\zs\d+')
let options = ' -r' . caption
else
let caption = ''
let options = ''
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let caption = a:argList[0]
let options = ' -r' . caption
else
let caption = join(a:argList, ' ')
let options = ' ' . caption
endif
let resultBuffer = s:DoCommand('blame' . options, 'annotate', caption, {})
if resultBuffer > 0
normal! 1G2dd
endif
return resultBuffer
endfunction
" Function: s:bzrFunctions.Commit(argList) {{{2
function! s:bzrFunctions.Commit(argList)
let resultBuffer = s:DoCommand('commit -F "' . a:argList[0] . '"', 'commit', '', {})
if resultBuffer == 0
echomsg 'No commit needed.'
endif
endfunction
" Function: s:bzrFunctions.Delete() {{{2
function! s:bzrFunctions.Delete(argList)
return s:DoCommand(join(['rm'] + a:argList, ' '), 'rm', join(a:argList, ' '), {})
endfunction
" Function: s:bzrFunctions.Diff(argList) {{{2
function! s:bzrFunctions.Diff(argList)
if len(a:argList) == 0
let revOptions = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let revOptions = ['-r' . join(a:argList, '..')]
let caption = '(' . a:argList[0] . ' : ' . get(a:argList, 1, 'current') . ')'
else
" Pass-through
let caption = join(a:argList, ' ')
let revOptions = a:argList
endif
return s:DoCommand(join(['diff'] + revOptions), 'diff', caption, {'allowNonZeroExit': 1})
endfunction
" Function: s:bzrFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin.
" Returns: List of results: [revision, repository]
function! s:bzrFunctions.GetBufferInfo()
let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
let fileName = resolve(bufname(originalBuffer))
let statusText = s:VCSCommandUtility.system(s:Executable() . ' status -S -- "' . fileName . '"')
let revision = s:VCSCommandUtility.system(s:Executable() . ' revno -- "' . fileName . '"')
if(v:shell_error)
return []
endif
" File not under BZR control.
if statusText =~ '^?'
return ['Unknown']
endif
let [flags, repository] = matchlist(statusText, '^\(.\{3}\)\s\+\(\S\+\)')[1:2]
if revision == ''
" Error
return ['Unknown']
elseif flags =~ '^A'
return ['New', 'New']
else
return [revision, repository]
endif
endfunction
" Function: s:bzrFunctions.Info(argList) {{{2
function! s:bzrFunctions.Info(argList)
return s:DoCommand(join(['version-info'] + a:argList, ' '), 'version-info', join(a:argList, ' '), {})
endfunction
" Function: s:bzrFunctions.Lock(argList) {{{2
function! s:bzrFunctions.Lock(argList)
echomsg 'bzr lock is not necessary'
endfunction
" Function: s:bzrFunctions.Log() {{{2
function! s:bzrFunctions.Log(argList)
if len(a:argList) == 0
let options = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let options = ['-r' . join(a:argList, ':')]
let caption = options[0]
else
" Pass-through
let options = a:argList
let caption = join(a:argList, ' ')
endif
let resultBuffer = s:DoCommand(join(['log', '-v'] + options), 'log', caption, {})
return resultBuffer
endfunction
" Function: s:bzrFunctions.Revert(argList) {{{2
function! s:bzrFunctions.Revert(argList)
return s:DoCommand('revert', 'revert', '', {})
endfunction
" Function: s:bzrFunctions.Review(argList) {{{2
function! s:bzrFunctions.Review(argList)
if len(a:argList) == 0
let versiontag = '(current)'
let versionOption = ''
else
let versiontag = a:argList[0]
let versionOption = ' -r ' . versiontag . ' '
endif
return s:DoCommand('cat' . versionOption, 'review', versiontag, {})
endfunction
" Function: s:bzrFunctions.Status(argList) {{{2
function! s:bzrFunctions.Status(argList)
let options = ['-S']
if len(a:argList) != 0
let options = a:argList
endif
return s:DoCommand(join(['status'] + options, ' '), 'status', join(options, ' '), {})
endfunction
" Function: s:bzrFunctions.Unlock(argList) {{{2
function! s:bzrFunctions.Unlock(argList)
echomsg 'bzr unlock is not necessary'
endfunction
" Function: s:bzrFunctions.Update(argList) {{{2
function! s:bzrFunctions.Update(argList)
return s:DoCommand('update', 'update', '', {})
endfunction
" Annotate setting {{{2
let s:bzrFunctions.AnnotateSplitRegex = '^[^|]\+ | '
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('BZR', expand('<sfile>'), s:bzrFunctions, [])
let &cpo = s:save_cpo
File diff suppressed because it is too large Load Diff
-453
View File
@@ -1,453 +0,0 @@
" vim600: set foldmethod=marker:
"
" CVS extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Command documentation {{{2
"
" The following commands only apply to files under CVS source control.
"
" CVSEdit Performs "cvs edit" on the current file.
"
" CVSEditors Performs "cvs editors" on the current file.
"
" CVSUnedit Performs "cvs unedit" on the current file.
"
" CVSWatch Takes an argument which must be one of [on|off|add|remove].
" Performs "cvs watch" with the given argument on the current
" file.
"
" CVSWatchers Performs "cvs watchers" on the current file.
"
" CVSWatchAdd Alias for "CVSWatch add"
"
" CVSWatchOn Alias for "CVSWatch on"
"
" CVSWatchOff Alias for "CVSWatch off"
"
" CVSWatchRemove Alias for "CVSWatch remove"
"
" Mapping documentation: {{{2
"
" By default, a mapping is defined for each command. User-provided mappings
" can be used instead by mapping to <Plug>CommandName, for instance:
"
" nnoremap ,ce <Plug>CVSEdit
"
" The default mappings are as follow:
"
" <Leader>ce CVSEdit
" <Leader>cE CVSEditors
" <Leader>ct CVSUnedit
" <Leader>cwv CVSWatchers
" <Leader>cwa CVSWatchAdd
" <Leader>cwn CVSWatchOn
" <Leader>cwf CVSWatchOff
" <Leader>cwr CVSWatchRemove
"
" Options documentation: {{{2
"
" VCSCommandCVSExec
" This variable specifies the CVS executable. If not set, it defaults to
" 'cvs' executed from the user's executable path.
"
" VCSCommandCVSDiffOpt
" This variable, if set, determines the options passed to the cvs diff
" command. If not set, it defaults to 'u'.
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandCVSExec', 'cvs'))
" CVS is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:cvsFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke cvs suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandCVSExec', 'cvs')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText, options) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the CVS executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'CVS'
let fullCmd = s:Executable() . ' ' . a:cmd
let ret = VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
if ret > 0
if getline(line('$')) =~ '^cvs \w\+: closing down connection'
$d
1
endif
endif
return ret
else
throw 'CVS VCSCommand plugin called on non-CVS item.'
endif
endfunction
" Function: s:GetRevision() {{{2
" Function for retrieving the current buffer's revision number.
" Returns: Revision number or an empty string if an error occurs.
function! s:GetRevision()
if !exists('b:VCSCommandBufferInfo')
let b:VCSCommandBufferInfo = s:cvsFunctions.GetBufferInfo()
endif
if len(b:VCSCommandBufferInfo) > 0
return b:VCSCommandBufferInfo[0]
else
return ''
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:cvsFunctions.Identify(buffer) {{{2
function! s:cvsFunctions.Identify(buffer)
let fileName = resolve(bufname(a:buffer))
if isdirectory(fileName)
let directoryName = fileName
else
let directoryName = fnamemodify(fileName, ':h')
endif
if strlen(directoryName) > 0
let CVSRoot = directoryName . '/CVS/Root'
else
let CVSRoot = 'CVS/Root'
endif
if filereadable(CVSRoot)
return 1
else
return 0
endif
endfunction
" Function: s:cvsFunctions.Add(argList) {{{2
function! s:cvsFunctions.Add(argList)
return s:DoCommand(join(['add'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:cvsFunctions.Annotate(argList) {{{2
function! s:cvsFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype ==? 'cvsannotate'
" This is a CVSAnnotate buffer. Perform annotation of the version
" indicated by the current line.
let caption = matchstr(getline('.'),'\v^[0-9.]+')
if VCSCommandGetOption('VCSCommandCVSAnnotateParent', 0) != 0
if caption != '1.1'
let revmaj = matchstr(caption,'\v[0-9.]+\ze\.[0-9]+')
let revmin = matchstr(caption,'\v[0-9.]+\.\zs[0-9]+') - 1
if revmin == 0
" Jump to ancestor branch
let caption = matchstr(revmaj,'\v[0-9.]+\ze\.[0-9]+')
else
let caption = revmaj . "." . revmin
endif
endif
endif
let options = ['-r' . caption]
else
" CVS defaults to pulling HEAD, regardless of current branch.
" Therefore, always pass desired revision.
let caption = ''
let options = ['-r' . s:GetRevision()]
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let caption = a:argList[0]
let options = ['-r' . caption]
else
let caption = join(a:argList)
let options = a:argList
endif
let resultBuffer = s:DoCommand(join(['-q', 'annotate'] + options), 'annotate', caption, {})
if resultBuffer > 0
" Remove header lines from standard error
silent v/^\d\+\%(\.\d\+\)\+/d
endif
return resultBuffer
endfunction
" Function: s:cvsFunctions.Commit(argList) {{{2
function! s:cvsFunctions.Commit(argList)
let resultBuffer = s:DoCommand('commit -F "' . a:argList[0] . '"', 'commit', '', {})
if resultBuffer == 0
echomsg 'No commit needed.'
endif
return resultBuffer
endfunction
" Function: s:cvsFunctions.Delete() {{{2
" By default, use the -f option to remove the file first. If options are
" passed in, use those instead.
function! s:cvsFunctions.Delete(argList)
let options = ['-f']
let caption = ''
if len(a:argList) > 0
let options = a:argList
let caption = join(a:argList, ' ')
endif
return s:DoCommand(join(['remove'] + options, ' '), 'delete', caption, {})
endfunction
" Function: s:cvsFunctions.Diff(argList) {{{2
function! s:cvsFunctions.Diff(argList)
if len(a:argList) == 0
let revOptions = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let revOptions = ['-r' . join(a:argList, ' -r')]
let caption = '(' . a:argList[0] . ' : ' . get(a:argList, 1, 'current') . ')'
else
" Pass-through
let caption = join(a:argList, ' ')
let revOptions = a:argList
endif
let cvsDiffOpt = VCSCommandGetOption('VCSCommandCVSDiffOpt', 'u')
if cvsDiffOpt == ''
let diffOptions = []
else
let diffOptions = ['-' . cvsDiffOpt]
endif
return s:DoCommand(join(['diff'] + diffOptions + revOptions), 'diff', caption, {'allowNonZeroExit': 1})
endfunction
" Function: s:cvsFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin. This CVS extension adds branch name to the return
" list as well.
" Returns: List of results: [revision, repository, branch]
function! s:cvsFunctions.GetBufferInfo()
let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
let fileName = bufname(originalBuffer)
if isdirectory(fileName)
let tag = ''
if filereadable(fileName . '/CVS/Tag')
let tagFile = readfile(fileName . '/CVS/Tag')
if len(tagFile) == 1
let tag = substitute(tagFile[0], '^T', '', '')
endif
endif
return [tag]
endif
let realFileName = fnamemodify(resolve(fileName), ':t')
if !filereadable(fileName)
return ['Unknown']
endif
let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
try
let statusText=s:VCSCommandUtility.system(s:Executable() . ' status -- "' . realFileName . '"')
if(v:shell_error)
return []
endif
let revision=substitute(statusText, '^\_.*Working revision:\s*\(\d\+\%(\.\d\+\)\+\|New file!\)\_.*$', '\1', '')
" We can still be in a CVS-controlled directory without this being a CVS
" file
if match(revision, '^New file!$') >= 0
let revision='New'
elseif match(revision, '^\d\+\.\d\+\%(\.\d\+\.\d\+\)*$') <0
return ['Unknown']
endif
let branch=substitute(statusText, '^\_.*Sticky Tag:\s\+\(\d\+\%(\.\d\+\)\+\|\a[A-Za-z0-9-_]*\|(none)\).*$', '\1', '')
let repository=substitute(statusText, '^\_.*Repository revision:\s*\(\d\+\%(\.\d\+\)\+\|New file!\|No revision control file\)\_.*$', '\1', '')
let repository=substitute(repository, '^New file!\|No revision control file$', 'New', '')
return [revision, repository, branch]
finally
call VCSCommandChdir(oldCwd)
endtry
endfunction
" Function: s:cvsFunctions.Log() {{{2
function! s:cvsFunctions.Log(argList)
if len(a:argList) == 0
let options = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let options = ['-r' . join(a:argList, ':')]
let caption = options[0]
else
" Pass-through
let options = a:argList
let caption = join(a:argList, ' ')
endif
return s:DoCommand(join(['log'] + options), 'log', caption, {})
endfunction
" Function: s:cvsFunctions.Revert(argList) {{{2
function! s:cvsFunctions.Revert(argList)
return s:DoCommand('update -C', 'revert', '', {})
endfunction
" Function: s:cvsFunctions.Review(argList) {{{2
function! s:cvsFunctions.Review(argList)
if len(a:argList) == 0
let versiontag = '(current)'
let versionOption = ''
else
let versiontag = a:argList[0]
let versionOption = ' -r ' . versiontag . ' '
endif
return s:DoCommand('-q update -p' . versionOption, 'review', versiontag, {})
endfunction
" Function: s:cvsFunctions.Status(argList) {{{2
function! s:cvsFunctions.Status(argList)
return s:DoCommand(join(['status'] + a:argList, ' '), 'status', join(a:argList, ' '), {})
endfunction
" Function: s:cvsFunctions.Update(argList) {{{2
function! s:cvsFunctions.Update(argList)
return s:DoCommand('update', 'update', '', {})
endfunction
" Section: CVS-specific functions {{{1
" Function: s:CVSEdit() {{{2
function! s:CVSEdit()
return s:DoCommand('edit', 'cvsedit', '', {})
endfunction
" Function: s:CVSEditors() {{{2
function! s:CVSEditors()
return s:DoCommand('editors', 'cvseditors', '', {})
endfunction
" Function: s:CVSUnedit() {{{2
function! s:CVSUnedit()
return s:DoCommand('unedit', 'cvsunedit', '', {})
endfunction
" Function: s:CVSWatch(onoff) {{{2
function! s:CVSWatch(onoff)
if a:onoff !~ '^\c\%(on\|off\|add\|remove\)$'
echoerr 'Argument to CVSWatch must be one of [on|off|add|remove]'
return -1
end
return s:DoCommand('watch ' . tolower(a:onoff), 'cvswatch', '', {})
endfunction
" Function: s:CVSWatchers() {{{2
function! s:CVSWatchers()
return s:DoCommand('watchers', 'cvswatchers', '', {})
endfunction
" Annotate setting {{{2
let s:cvsFunctions.AnnotateSplitRegex = '): '
" Section: Command definitions {{{1
" Section: Primary commands {{{2
com! CVSEdit call s:CVSEdit()
com! CVSEditors call s:CVSEditors()
com! CVSUnedit call s:CVSUnedit()
com! -nargs=1 CVSWatch call s:CVSWatch(<f-args>)
com! CVSWatchAdd call s:CVSWatch('add')
com! CVSWatchOn call s:CVSWatch('on')
com! CVSWatchOff call s:CVSWatch('off')
com! CVSWatchRemove call s:CVSWatch('remove')
com! CVSWatchers call s:CVSWatchers()
" Section: Plugin command mappings {{{1
let s:cvsExtensionMappings = {}
if !exists("no_plugin_maps")
let mappingInfo = [
\['CVSEdit', 'CVSEdit', 'e'],
\['CVSEditors', 'CVSEditors', 'E'],
\['CVSUnedit', 'CVSUnedit', 't'],
\['CVSWatchers', 'CVSWatchers', 'wv'],
\['CVSWatchAdd', 'CVSWatch add', 'wa'],
\['CVSWatchOff', 'CVSWatch off', 'wf'],
\['CVSWatchOn', 'CVSWatch on', 'wn'],
\['CVSWatchRemove', 'CVSWatch remove', 'wr']
\]
for [pluginName, commandText, shortCut] in mappingInfo
execute 'nnoremap <silent> <Plug>' . pluginName . ' :' . commandText . '<CR>'
if !hasmapto('<Plug>' . pluginName)
let s:cvsExtensionMappings[shortCut] = commandText
endif
endfor
endif
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('CVS', expand('<sfile>'), s:cvsFunctions, s:cvsExtensionMappings)
" Section: Menu items {{{1
for [s:shortcut, s:command] in [
\['CVS.&Edit', '<Plug>CVSEdit'],
\['CVS.Ed&itors', '<Plug>CVSEditors'],
\['CVS.Unedi&t', '<Plug>CVSUnedit'],
\['CVS.&Watchers', '<Plug>CVSWatchers'],
\['CVS.WatchAdd', '<Plug>CVSWatchAdd'],
\['CVS.WatchOn', '<Plug>CVSWatchOn'],
\['CVS.WatchOff', '<Plug>CVSWatchOff'],
\['CVS.WatchRemove', '<Plug>CVSWatchRemove']
\]
call s:VCSCommandUtility.addMenuItem(s:shortcut, s:command)
endfor
unlet s:shortcut s:command
let &cpo = s:save_cpo
-249
View File
@@ -1,249 +0,0 @@
" vim600: set foldmethod=marker:
"
" git extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Options documentation: {{{2
"
" VCSCommandGitExec
" This variable specifies the git executable. If not set, it defaults to
" 'git' executed from the user's executable path.
"
" VCSCommandGitDiffOpt
" This variable, if set, determines the default options passed to the
" VCSDiff command. If any options (starting with '-') are passed to the
" command, this variable is not used.
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandGitExec', 'git'))
" git is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:gitFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke git suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandGitExec', 'git')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText, options) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the git executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'git'
let fullCmd = s:Executable() . ' ' . a:cmd
return VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
else
throw 'git VCSCommand plugin called on non-git item.'
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:gitFunctions.Identify(buffer) {{{2
" This function only returns an inexact match due to the detection method used
" by git, which simply traverses the directory structure upward.
function! s:gitFunctions.Identify(buffer)
let oldCwd = VCSCommandChangeToCurrentFileDir(resolve(bufname(a:buffer)))
try
call s:VCSCommandUtility.system(s:Executable() . ' rev-parse --is-inside-work-tree')
if(v:shell_error)
return 0
else
return g:VCSCOMMAND_IDENTIFY_INEXACT
endif
finally
call VCSCommandChdir(oldCwd)
endtry
endfunction
" Function: s:gitFunctions.Add(argList) {{{2
function! s:gitFunctions.Add(argList)
return s:DoCommand(join(['add'] + ['-v'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:gitFunctions.Annotate(argList) {{{2
function! s:gitFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype == 'gitannotate'
" Perform annotation of the version indicated by the current line.
let options = matchstr(getline('.'),'^\x\+')
else
let options = ''
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let options = a:argList[0]
else
let options = join(a:argList, ' ')
endif
return s:DoCommand('blame ' . options, 'annotate', options, {})
endfunction
" Function: s:gitFunctions.Commit(argList) {{{2
function! s:gitFunctions.Commit(argList)
try
return s:DoCommand('commit -F "' . a:argList[0] . '"', 'commit', '', {})
catch /\m^Version control command failed.*nothing\%( added\)\? to commit/
echomsg 'No commit needed.'
endtry
endfunction
" Function: s:gitFunctions.Delete() {{{2
" All options are passed through.
function! s:gitFunctions.Delete(argList)
let options = a:argList
let caption = join(a:argList, ' ')
return s:DoCommand(join(['rm'] + options, ' '), 'delete', caption, {})
endfunction
" Function: s:gitFunctions.Diff(argList) {{{2
" Pass-through call to git-diff. If no options (starting with '-') are found,
" then the options in the 'VCSCommandGitDiffOpt' variable are added.
function! s:gitFunctions.Diff(argList)
let gitDiffOpt = VCSCommandGetOption('VCSCommandGitDiffOpt', '')
if gitDiffOpt == ''
let diffOptions = []
else
let diffOptions = [gitDiffOpt]
for arg in a:argList
if arg =~ '^-'
let diffOptions = []
break
endif
endfor
endif
return s:DoCommand(join(['diff'] + diffOptions + a:argList), 'diff', join(a:argList), {})
endfunction
" Function: s:gitFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin. This CVS extension adds branch name to the return
" list as well.
" Returns: List of results: [revision, repository, branch]
function! s:gitFunctions.GetBufferInfo()
let oldCwd = VCSCommandChangeToCurrentFileDir(resolve(bufname('%')))
try
let branch = substitute(s:VCSCommandUtility.system(s:Executable() . ' symbolic-ref -q HEAD'), '\n$', '', '')
if v:shell_error
let branch = 'DETACHED'
else
let branch = substitute(branch, '^refs/heads/', '', '')
endif
let info = [branch]
for method in split(VCSCommandGetOption('VCSCommandGitDescribeArgList', (',tags,all,always')), ',', 1)
if method != ''
let method = ' --' . method
endif
let tag = substitute(s:VCSCommandUtility.system(s:Executable() . ' describe' . method), '\n$', '', '')
if !v:shell_error
call add(info, tag)
break
endif
endfor
return info
finally
call VCSCommandChdir(oldCwd)
endtry
endfunction
" Function: s:gitFunctions.Log() {{{2
function! s:gitFunctions.Log(argList)
return s:DoCommand(join(['log'] + a:argList), 'log', join(a:argList, ' '), {})
endfunction
" Function: s:gitFunctions.Revert(argList) {{{2
function! s:gitFunctions.Revert(argList)
return s:DoCommand('checkout', 'revert', '', {})
endfunction
" Function: s:gitFunctions.Review(argList) {{{2
function! s:gitFunctions.Review(argList)
if len(a:argList) == 0
let revision = 'HEAD'
else
let revision = a:argList[0]
endif
let oldCwd = VCSCommandChangeToCurrentFileDir(resolve(bufname(VCSCommandGetOriginalBuffer('%'))))
try
let prefix = s:VCSCommandUtility.system(s:Executable() . ' rev-parse --show-prefix')
finally
call VCSCommandChdir(oldCwd)
endtry
let prefix = substitute(prefix, '\n$', '', '')
let blob = '"' . revision . ':' . prefix . '<VCSCOMMANDFILE>"'
return s:DoCommand('show ' . blob, 'review', revision, {})
endfunction
" Function: s:gitFunctions.Status(argList) {{{2
function! s:gitFunctions.Status(argList)
return s:DoCommand(join(['status'] + a:argList), 'status', join(a:argList), {'allowNonZeroExit': 1})
endfunction
" Function: s:gitFunctions.Update(argList) {{{2
function! s:gitFunctions.Update(argList)
throw "This command is not implemented for git because file-by-file update doesn't make much sense in that context. If you have an idea for what it should do, please let me know."
endfunction
" Annotate setting {{{2
let s:gitFunctions.AnnotateSplitRegex = ') '
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('git', expand('<sfile>'), s:gitFunctions, [])
let &cpo = s:save_cpo
-275
View File
@@ -1,275 +0,0 @@
" vim600: set foldmethod=marker:
"
" Mercurial extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Options documentation: {{{2
"
" VCSCommandHGExec
" This variable specifies the mercurial executable. If not set, it defaults
" to 'hg' executed from the user's executable path.
"
" VCSCommandHGDiffExt
" This variable, if set, sets the external diff program used by Subversion.
"
" VCSCommandHGDiffOpt
" This variable, if set, determines the options passed to the hg diff
" command (such as 'u', 'w', or 'b').
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandHGExec', 'hg'))
" HG is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:hgFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke hg suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandHGExec', 'hg')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText, options) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the HG executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'HG'
let fullCmd = s:Executable() . ' ' . a:cmd
return VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
else
throw 'HG VCSCommand plugin called on non-HG item.'
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:hgFunctions.Identify(buffer) {{{2
function! s:hgFunctions.Identify(buffer)
let oldCwd = VCSCommandChangeToCurrentFileDir(resolve(bufname(a:buffer)))
try
call s:VCSCommandUtility.system(s:Executable() . ' root')
if(v:shell_error)
return 0
else
return g:VCSCOMMAND_IDENTIFY_INEXACT
endif
finally
call VCSCommandChdir(oldCwd)
endtry
endfunction
" Function: s:hgFunctions.Add() {{{2
function! s:hgFunctions.Add(argList)
return s:DoCommand(join(['add -v'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:hgFunctions.Annotate(argList) {{{2
function! s:hgFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype ==? 'hgannotate'
" Perform annotation of the version indicated by the current line.
let caption = matchstr(getline('.'),'\v^\s*\w+\s+\zs\d+')
let options = ' -un -r' . caption
else
let caption = ''
let options = ' -un'
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let caption = a:argList[0]
let options = ' -un -r' . caption
else
let caption = join(a:argList, ' ')
let options = ' ' . caption
endif
return s:DoCommand('blame' . options, 'annotate', caption, {})
endfunction
" Function: s:hgFunctions.Commit(argList) {{{2
function! s:hgFunctions.Commit(argList)
try
return s:DoCommand('commit -v -l "' . a:argList[0] . '"', 'commit', '', {})
catch /Version control command failed.*nothing changed/
echomsg 'No commit needed.'
endtry
endfunction
" Function: s:hgFunctions.Delete() {{{2
function! s:hgFunctions.Delete(argList)
return s:DoCommand(join(['remove'] + a:argList, ' '), 'remove', join(a:argList, ' '), {})
endfunction
" Function: s:hgFunctions.Diff(argList) {{{2
function! s:hgFunctions.Diff(argList)
if len(a:argList) == 0
let revOptions = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let revOptions = ['-r' . join(a:argList, ':')]
let caption = '(' . a:argList[0] . ' : ' . get(a:argList, 1, 'current') . ')'
else
" Pass-through
let caption = join(a:argList, ' ')
let revOptions = a:argList
endif
let hgDiffExt = VCSCommandGetOption('VCSCommandHGDiffExt', '')
if hgDiffExt == ''
let diffExt = []
else
let diffExt = ['--diff-cmd ' . hgDiffExt]
endif
let hgDiffOpt = VCSCommandGetOption('VCSCommandHGDiffOpt', '')
if hgDiffOpt == ''
let diffOptions = []
else
let diffOptions = ['-x -' . hgDiffOpt]
endif
return s:DoCommand(join(['diff'] + diffExt + diffOptions + revOptions), 'diff', caption, {})
endfunction
" Function: s:hgFunctions.Info(argList) {{{2
function! s:hgFunctions.Info(argList)
return s:DoCommand(join(['log --limit 1'] + a:argList, ' '), 'log', join(a:argList, ' '), {})
endfunction
" Function: s:hgFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin.
" Returns: List of results: [revision, repository, branch]
function! s:hgFunctions.GetBufferInfo()
let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
let fileName = bufname(originalBuffer)
let statusText = s:VCSCommandUtility.system(s:Executable() . ' status -- "' . fileName . '"')
if(v:shell_error)
return []
endif
" File not under HG control.
if statusText =~ '^?'
return ['Unknown']
endif
let parentsText = s:VCSCommandUtility.system(s:Executable() . ' parents -- "' . fileName . '"')
let revision = matchlist(parentsText, '^changeset:\s\+\(\S\+\)\n')[1]
let logText = s:VCSCommandUtility.system(s:Executable() . ' log -- "' . fileName . '"')
let repository = matchlist(logText, '^changeset:\s\+\(\S\+\)\n')[1]
if revision == ''
" Error
return ['Unknown']
elseif statusText =~ '^A'
return ['New', 'New']
else
return [revision, repository]
endif
endfunction
" Function: s:hgFunctions.Log(argList) {{{2
function! s:hgFunctions.Log(argList)
if len(a:argList) == 0
let options = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let options = ['-r' . join(a:argList, ':')]
let caption = options[0]
else
" Pass-through
let options = a:argList
let caption = join(a:argList, ' ')
endif
let resultBuffer = s:DoCommand(join(['log', '-v'] + options), 'log', caption, {})
return resultBuffer
endfunction
" Function: s:hgFunctions.Revert(argList) {{{2
function! s:hgFunctions.Revert(argList)
return s:DoCommand('revert', 'revert', '', {})
endfunction
" Function: s:hgFunctions.Review(argList) {{{2
function! s:hgFunctions.Review(argList)
if len(a:argList) == 0
let versiontag = '(current)'
let versionOption = ''
else
let versiontag = a:argList[0]
let versionOption = ' -r ' . versiontag . ' '
endif
return s:DoCommand('cat' . versionOption, 'review', versiontag, {})
endfunction
" Function: s:hgFunctions.Status(argList) {{{2
function! s:hgFunctions.Status(argList)
let options = ['-A', '-v']
if len(a:argList) != 0
let options = a:argList
endif
return s:DoCommand(join(['status'] + options, ' '), 'status', join(options, ' '), {})
endfunction
" Function: s:hgFunctions.Update(argList) {{{2
function! s:hgFunctions.Update(argList)
return s:DoCommand('update', 'update', '', {})
endfunction
" Annotate setting {{{2
let s:hgFunctions.AnnotateSplitRegex = '\d\+: '
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('HG', expand('<sfile>'), s:hgFunctions, [])
let &cpo = s:save_cpo
-259
View File
@@ -1,259 +0,0 @@
" vim600: set foldmethod=marker:
"
" SVK extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Options documentation: {{{2
"
" VCSCommandSVKExec
" This variable specifies the SVK executable. If not set, it defaults to
" 'svk' executed from the user's executable path.
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandSVKExec', 'svk'))
" SVK is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:svkFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke SVK suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandSVKExec', 'svk')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText, options) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the SVK executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'SVK'
let fullCmd = s:Executable() . ' ' . a:cmd
return VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
else
throw 'SVK VCSCommand plugin called on non-SVK item.'
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:svkFunctions.Identify(buffer) {{{2
function! s:svkFunctions.Identify(buffer)
let fileName = resolve(bufname(a:buffer))
if isdirectory(fileName)
let directoryName = fileName
else
let directoryName = fnamemodify(fileName, ':p:h')
endif
let statusText = s:VCSCommandUtility.system(s:Executable() . ' info -- "' . directoryName . '"', "no")
if(v:shell_error)
return 0
else
return 1
endif
endfunction
" Function: s:svkFunctions.Add() {{{2
function! s:svkFunctions.Add(argList)
return s:DoCommand(join(['add'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:svkFunctions.Annotate(argList) {{{2
function! s:svkFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype ==? 'svkannotate'
" Perform annotation of the version indicated by the current line.
let caption = matchstr(getline('.'),'\v^\s+\zs\d+')
let options = ' -r' . caption
else
let caption = ''
let options = ''
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let caption = a:argList[0]
let options = ' -r' . caption
else
let caption = join(a:argList, ' ')
let options = ' ' . caption
endif
let resultBuffer = s:DoCommand('blame' . options, 'annotate', caption, {})
if resultBuffer > 0
normal! 1G2dd
endif
return resultBuffer
endfunction
" Function: s:svkFunctions.Commit(argList) {{{2
function! s:svkFunctions.Commit(argList)
let resultBuffer = s:DoCommand('commit -F "' . a:argList[0] . '"', 'commit', '', {})
if resultBuffer == 0
echomsg 'No commit needed.'
endif
endfunction
" Function: s:svkFunctions.Delete() {{{2
function! s:svkFunctions.Delete(argList)
return s:DoCommand(join(['delete'] + a:argList, ' '), 'delete', join(a:argList, ' '), {})
endfunction
" Function: s:svkFunctions.Diff(argList) {{{2
function! s:svkFunctions.Diff(argList)
if len(a:argList) == 0
let revOptions = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let revOptions = ['-r' . join(a:argList, ':')]
let caption = '(' . a:argList[0] . ' : ' . get(a:argList, 1, 'current') . ')'
else
" Pass-through
let caption = join(a:argList, ' ')
let revOptions = a:argList
endif
return s:DoCommand(join(['diff'] + revOptions), 'diff', caption, {})
endfunction
" Function: s:svkFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin.
" Returns: List of results: [revision, repository]
function! s:svkFunctions.GetBufferInfo()
let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
let fileName = resolve(bufname(originalBuffer))
let statusText = s:VCSCommandUtility.system(s:Executable() . ' status -v -- "' . fileName . '"')
if(v:shell_error)
return []
endif
" File not under SVK control.
if statusText =~ '^?'
return ['Unknown']
endif
let [flags, revision, repository] = matchlist(statusText, '^\(.\{3}\)\s\+\(\S\+\)\s\+\(\S\+\)\s\+\(\S\+\)\s')[1:3]
if revision == ''
" Error
return ['Unknown']
elseif flags =~ '^A'
return ['New', 'New']
else
return [revision, repository]
endif
endfunction
" Function: s:svkFunctions.Info(argList) {{{2
function! s:svkFunctions.Info(argList)
return s:DoCommand(join(['info'] + a:argList, ' '), 'info', join(a:argList, ' '), {})
endfunction
" Function: s:svkFunctions.Lock(argList) {{{2
function! s:svkFunctions.Lock(argList)
return s:DoCommand(join(['lock'] + a:argList, ' '), 'lock', join(a:argList, ' '), {})
endfunction
" Function: s:svkFunctions.Log() {{{2
function! s:svkFunctions.Log(argList)
if len(a:argList) == 0
let options = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let options = ['-r' . join(a:argList, ':')]
let caption = options[0]
else
" Pass-through
let options = a:argList
let caption = join(a:argList, ' ')
endif
let resultBuffer = s:DoCommand(join(['log', '-v'] + options), 'log', caption, {})
return resultBuffer
endfunction
" Function: s:svkFunctions.Revert(argList) {{{2
function! s:svkFunctions.Revert(argList)
return s:DoCommand('revert', 'revert', '', {})
endfunction
" Function: s:svkFunctions.Review(argList) {{{2
function! s:svkFunctions.Review(argList)
if len(a:argList) == 0
let versiontag = '(current)'
let versionOption = ''
else
let versiontag = a:argList[0]
let versionOption = ' -r ' . versiontag . ' '
endif
return s:DoCommand('cat' . versionOption, 'review', versiontag, {})
endfunction
" Function: s:svkFunctions.Status(argList) {{{2
function! s:svkFunctions.Status(argList)
let options = ['-v']
if len(a:argList) != 0
let options = a:argList
endif
return s:DoCommand(join(['status'] + options, ' '), 'status', join(options, ' '), {})
endfunction
" Function: s:svkFunctions.Unlock(argList) {{{2
function! s:svkFunctions.Unlock(argList)
return s:DoCommand(join(['unlock'] + a:argList, ' '), 'unlock', join(a:argList, ' '), {})
endfunction
" Function: s:svkFunctions.Update(argList) {{{2
function! s:svkFunctions.Update(argList)
return s:DoCommand('update', 'update', '', {})
endfunction
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('SVK', expand('<sfile>'), s:svkFunctions, [])
let &cpo = s:save_cpo
-281
View File
@@ -1,281 +0,0 @@
" vim600: set foldmethod=marker:
"
" SVN extension for VCSCommand.
"
" Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
" License:
" Copyright (c) Bob Hiestand
"
" Permission is hereby granted, free of charge, to any person obtaining a copy
" of this software and associated documentation files (the "Software"), to
" deal in the Software without restriction, including without limitation the
" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
" sell copies of the Software, and to permit persons to whom the Software is
" furnished to do so, subject to the following conditions:
"
" The above copyright notice and this permission notice shall be included in
" all copies or substantial portions of the Software.
"
" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
" IN THE SOFTWARE.
"
" Section: Documentation {{{1
"
" Options documentation: {{{2
"
" VCSCommandSVNExec
" This variable specifies the SVN executable. If not set, it defaults to
" 'svn' executed from the user's executable path.
"
" VCSCommandSVNDiffExt
" This variable, if set, sets the external diff program used by Subversion.
"
" VCSCommandSVNDiffOpt
" This variable, if set, determines the options passed to the svn diff
" command (such as 'u', 'w', or 'b').
" Section: Plugin header {{{1
if exists('VCSCommandDisableAll')
finish
endif
if v:version < 700
echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
finish
endif
if !exists('g:loaded_VCSCommand')
runtime plugin/vcscommand.vim
endif
if !executable(VCSCommandGetOption('VCSCommandSVNExec', 'svn'))
" SVN is not installed
finish
endif
let s:save_cpo=&cpo
set cpo&vim
" Section: Variable initialization {{{1
let s:svnFunctions = {}
" Section: Utility functions {{{1
" Function: s:Executable() {{{2
" Returns the executable used to invoke git suitable for use in a shell
" command.
function! s:Executable()
return VCSCommandGetOption('VCSCommandSVNExec', 'svn')
endfunction
" Function: s:DoCommand(cmd, cmdName, statusText, options) {{{2
" Wrapper to VCSCommandDoCommand to add the name of the SVN executable to the
" command argument.
function! s:DoCommand(cmd, cmdName, statusText, options)
if VCSCommandGetVCSType(expand('%')) == 'SVN'
let fullCmd = s:Executable() . ' ' . a:cmd
return VCSCommandDoCommand(fullCmd, a:cmdName, a:statusText, a:options)
else
throw 'SVN VCSCommand plugin called on non-SVN item.'
endif
endfunction
" Section: VCS function implementations {{{1
" Function: s:svnFunctions.Identify(buffer) {{{2
function! s:svnFunctions.Identify(buffer)
let oldCwd = VCSCommandChangeToCurrentFileDir(resolve(bufname(a:buffer)))
try
call s:VCSCommandUtility.system(s:Executable() . ' info .')
if(v:shell_error)
return 0
else
return g:VCSCOMMAND_IDENTIFY_EXACT
endif
finally
call VCSCommandChdir(oldCwd)
endtry
endfunction
" Function: s:svnFunctions.Add() {{{2
function! s:svnFunctions.Add(argList)
return s:DoCommand(join(['add'] + a:argList, ' '), 'add', join(a:argList, ' '), {})
endfunction
" Function: s:svnFunctions.Annotate(argList) {{{2
function! s:svnFunctions.Annotate(argList)
if len(a:argList) == 0
if &filetype ==? 'svnannotate'
" Perform annotation of the version indicated by the current line.
let caption = matchstr(getline('.'),'\v^\s+\zs\d+')
let options = ' -r' . caption
else
let caption = ''
let options = ''
endif
elseif len(a:argList) == 1 && a:argList[0] !~ '^-'
let caption = a:argList[0]
let options = ' -r' . caption
else
let caption = join(a:argList, ' ')
let options = ' ' . caption
endif
return s:DoCommand('blame --non-interactive' . options, 'annotate', caption, {})
endfunction
" Function: s:svnFunctions.Commit(argList) {{{2
function! s:svnFunctions.Commit(argList)
let resultBuffer = s:DoCommand('commit --non-interactive -F "' . a:argList[0] . '"', 'commit', '', {})
if resultBuffer == 0
echomsg 'No commit needed.'
endif
endfunction
" Function: s:svnFunctions.Delete() {{{2
function! s:svnFunctions.Delete(argList)
return s:DoCommand(join(['delete --non-interactive'] + a:argList, ' '), 'delete', join(a:argList, ' '), {})
endfunction
" Function: s:svnFunctions.Diff(argList) {{{2
function! s:svnFunctions.Diff(argList)
if len(a:argList) == 0
let revOptions = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let revOptions = ['-r' . join(a:argList, ':')]
let caption = '(' . a:argList[0] . ' : ' . get(a:argList, 1, 'current') . ')'
else
" Pass-through
let caption = join(a:argList, ' ')
let revOptions = a:argList
endif
let svnDiffExt = VCSCommandGetOption('VCSCommandSVNDiffExt', '')
if svnDiffExt == ''
let diffExt = []
else
let diffExt = ['--diff-cmd ' . svnDiffExt]
endif
let svnDiffOpt = VCSCommandGetOption('VCSCommandSVNDiffOpt', '')
if svnDiffOpt == ''
let diffOptions = []
else
let diffOptions = ['-x -' . svnDiffOpt]
endif
return s:DoCommand(join(['diff --non-interactive'] + diffExt + diffOptions + revOptions), 'diff', caption, {})
endfunction
" Function: s:svnFunctions.GetBufferInfo() {{{2
" Provides version control details for the current file. Current version
" number and current repository version number are required to be returned by
" the vcscommand plugin.
" Returns: List of results: [revision, repository, branch]
function! s:svnFunctions.GetBufferInfo()
let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
let fileName = bufname(originalBuffer)
let statusText = s:VCSCommandUtility.system(s:Executable() . ' status --non-interactive -v -- "' . fileName . '"')
if(v:shell_error)
return []
endif
" File not under SVN control.
if statusText =~ '^?'
return ['Unknown']
endif
let [flags, revision, repository] = matchlist(statusText, '^\(.\{9}\)\s*\(\d\+\)\s\+\(\d\+\)')[1:3]
if revision == ''
" Error
return ['Unknown']
elseif flags =~ '^A'
return ['New', 'New']
elseif flags =~ '*'
return [revision, repository, '*']
else
return [revision, repository]
endif
endfunction
" Function: s:svnFunctions.Info(argList) {{{2
function! s:svnFunctions.Info(argList)
return s:DoCommand(join(['info --non-interactive'] + a:argList, ' '), 'info', join(a:argList, ' '), {})
endfunction
" Function: s:svnFunctions.Lock(argList) {{{2
function! s:svnFunctions.Lock(argList)
return s:DoCommand(join(['lock --non-interactive'] + a:argList, ' '), 'lock', join(a:argList, ' '), {})
endfunction
" Function: s:svnFunctions.Log(argList) {{{2
function! s:svnFunctions.Log(argList)
if len(a:argList) == 0
let options = []
let caption = ''
elseif len(a:argList) <= 2 && match(a:argList, '^-') == -1
let options = ['-r' . join(a:argList, ':')]
let caption = options[0]
else
" Pass-through
let options = a:argList
let caption = join(a:argList, ' ')
endif
let resultBuffer = s:DoCommand(join(['log --non-interactive', '-v'] + options), 'log', caption, {})
return resultBuffer
endfunction
" Function: s:svnFunctions.Revert(argList) {{{2
function! s:svnFunctions.Revert(argList)
return s:DoCommand('revert', 'revert', '', {})
endfunction
" Function: s:svnFunctions.Review(argList) {{{2
function! s:svnFunctions.Review(argList)
if len(a:argList) == 0
let versiontag = '(current)'
let versionOption = ''
else
let versiontag = a:argList[0]
let versionOption = ' -r ' . versiontag . ' '
endif
return s:DoCommand('cat --non-interactive' . versionOption, 'review', versiontag, {})
endfunction
" Function: s:svnFunctions.Status(argList) {{{2
function! s:svnFunctions.Status(argList)
let options = ['-u', '-v']
if len(a:argList) != 0
let options = a:argList
endif
return s:DoCommand(join(['status --non-interactive'] + options, ' '), 'status', join(options, ' '), {})
endfunction
" Function: s:svnFunctions.Unlock(argList) {{{2
function! s:svnFunctions.Unlock(argList)
return s:DoCommand(join(['unlock --non-interactive'] + a:argList, ' '), 'unlock', join(a:argList, ' '), {})
endfunction
" Function: s:svnFunctions.Update(argList) {{{2
function! s:svnFunctions.Update(argList)
return s:DoCommand('update --non-interactive', 'update', '', {})
endfunction
" Annotate setting {{{2
let s:svnFunctions.AnnotateSplitRegex = '\s\+\S\+\s\+\S\+ '
" Section: Plugin Registration {{{1
let s:VCSCommandUtility = VCSCommandRegisterModule('SVN', expand('<sfile>'), s:svnFunctions, [])
let &cpo = s:save_cpo
-445
View File
@@ -1,445 +0,0 @@
" vim:tabstop=2:shiftwidth=2:expandtab:foldmethod=marker:textwidth=79
" Vimwiki plugin file
" Author: Maxim Kim <habamax@gmail.com>
" Home: http://code.google.com/p/vimwiki/
" GetLatestVimScripts: 2226 1 :AutoInstall: vimwiki
if exists("loaded_vimwiki") || &cp
finish
endif
let loaded_vimwiki = 1
let s:old_cpo = &cpo
set cpo&vim
" HELPER functions {{{
function! s:default(varname, value) "{{{
if !exists('g:vimwiki_'.a:varname)
let g:vimwiki_{a:varname} = a:value
endif
endfunction "}}}
" return longest common path prefix of 2 given paths.
" '~/home/usrname/wiki', '~/home/usrname/wiki/shmiki' => '~/home/usrname/wiki'
function! s:path_common_pfx(path1, path2) "{{{
let p1 = split(a:path1, '[/\\]', 1)
let p2 = split(a:path2, '[/\\]', 1)
let idx = 0
let minlen = min([len(p1), len(p2)])
while (idx < minlen) && (p1[idx] ==? p2[idx])
let idx = idx + 1
endwhile
if idx == 0
return ''
else
return join(p1[: idx-1], '/')
endif
endfunction "}}}
function! s:find_wiki(path) "{{{
let idx = 0
while idx < len(g:vimwiki_list)
let path = vimwiki#base#chomp_slash(expand(VimwikiGet('path', idx)))
let path = vimwiki#base#path_norm(path)
if s:path_common_pfx(path, a:path) == path
return idx
endif
let idx += 1
endwhile
return -1
endfunction "}}}
function! s:setup_buffer_leave()"{{{
if &filetype == 'vimwiki' && !exists("b:vimwiki_idx")
let b:vimwiki_idx = g:vimwiki_current_idx
endif
" Set up menu
if g:vimwiki_menu != ""
exe 'nmenu disable '.g:vimwiki_menu.'.Table'
endif
endfunction"}}}
function! s:setup_filetype() "{{{
" Find what wiki current buffer belongs to.
let path = expand('%:p:h')
let ext = '.'.expand('%:e')
let idx = s:find_wiki(path)
if idx == -1 && g:vimwiki_global_ext == 0
return
endif
set filetype=vimwiki
endfunction "}}}
function! s:setup_buffer_enter() "{{{
if exists("b:vimwiki_idx")
let g:vimwiki_current_idx = b:vimwiki_idx
else
" Find what wiki current buffer belongs to.
" If wiki does not exist in g:vimwiki_list -- add new wiki there with
" buffer's path and ext.
" Else set g:vimwiki_current_idx to that wiki index.
let path = expand('%:p:h')
let ext = '.'.expand('%:e')
let idx = s:find_wiki(path)
" The buffer's file is not in the path and user do not want his wiki
" extension to be global -- do not add new wiki.
if idx == -1 && g:vimwiki_global_ext == 0
return
endif
if idx == -1
call add(g:vimwiki_list, {'path': path, 'ext': ext, 'temp': 1})
let g:vimwiki_current_idx = len(g:vimwiki_list) - 1
else
let g:vimwiki_current_idx = idx
endif
let b:vimwiki_idx = g:vimwiki_current_idx
endif
" If you have
" au GUIEnter * VimwikiIndex
" Then change it to
" au GUIEnter * nested VimwikiIndex
if &filetype == ''
set filetype=vimwiki
endif
" Update existed/non-existed links highlighting.
call vimwiki#base#highlight_links()
" Settings foldmethod, foldexpr and foldtext are local to window. Thus in a
" new tab with the same buffer folding is reset to vim defaults. So we
" insist vimwiki folding here.
if g:vimwiki_folding == 1 && &fdm != 'expr'
setlocal fdm=expr
setlocal foldexpr=VimwikiFoldLevel(v:lnum)
setlocal foldtext=VimwikiFoldText()
endif
" And conceal level too.
if g:vimwiki_conceallevel && exists("+conceallevel")
let &conceallevel = g:vimwiki_conceallevel
endif
" Set up menu
if g:vimwiki_menu != ""
exe 'nmenu enable '.g:vimwiki_menu.'.Table'
endif
endfunction "}}}
" OPTION get/set functions {{{
" return value of option for current wiki or if second parameter exists for
" wiki with a given index.
function! VimwikiGet(option, ...) "{{{
if a:0 == 0
let idx = g:vimwiki_current_idx
else
let idx = a:1
endif
if !has_key(g:vimwiki_list[idx], a:option) &&
\ has_key(s:vimwiki_defaults, a:option)
if a:option == 'path_html'
let g:vimwiki_list[idx][a:option] =
\VimwikiGet('path', idx)[:-2].'_html/'
else
let g:vimwiki_list[idx][a:option] =
\s:vimwiki_defaults[a:option]
endif
endif
" if path's ending is not a / or \
" then add it
if a:option == 'path' || a:option == 'path_html'
let p = g:vimwiki_list[idx][a:option]
" resolve doesn't work quite right with symlinks ended with / or \
let p = substitute(p, '[/\\]\+$', '', '')
let p = resolve(expand(p))
let g:vimwiki_list[idx][a:option] = p.'/'
endif
return g:vimwiki_list[idx][a:option]
endfunction "}}}
" set option for current wiki or if third parameter exists for
" wiki with a given index.
function! VimwikiSet(option, value, ...) "{{{
if a:0 == 0
let idx = g:vimwiki_current_idx
else
let idx = a:1
endif
let g:vimwiki_list[idx][a:option] = a:value
endfunction "}}}
" }}}
" }}}
" CALLBACK function "{{{
" User can redefine it.
if !exists("*VimwikiWeblinkHandler") "{{{
function VimwikiWeblinkHandler(weblink)
for browser in g:vimwiki_browsers
if executable(browser)
if has("win32")
execute '!start "'.browser.'" "' . a:weblink . '"'
else
execute '!'.browser.' "' . a:weblink . '"'
endif
return
endif
endfor
endfunction
endif "}}}
" CALLBACK }}}
" DEFAULT wiki {{{
let s:vimwiki_defaults = {}
let s:vimwiki_defaults.path = '~/vimwiki/'
let s:vimwiki_defaults.path_html = '~/vimwiki_html/'
let s:vimwiki_defaults.css_name = 'style.css'
let s:vimwiki_defaults.index = 'index'
let s:vimwiki_defaults.ext = '.wiki'
let s:vimwiki_defaults.maxhi = 1
let s:vimwiki_defaults.syntax = 'default'
let s:vimwiki_defaults.template_path = '~/vimwiki/templates/'
let s:vimwiki_defaults.template_default = 'default'
let s:vimwiki_defaults.template_ext = '.html'
let s:vimwiki_defaults.nested_syntaxes = {}
let s:vimwiki_defaults.auto_export = 0
" is wiki temporary -- was added to g:vimwiki_list by opening arbitrary wiki
" file.
let s:vimwiki_defaults.temp = 0
" diary
let s:vimwiki_defaults.diary_rel_path = 'diary/'
let s:vimwiki_defaults.diary_index = 'diary'
let s:vimwiki_defaults.diary_header = 'Diary'
" Do not change this! Will wait till vim become more datetime awareable.
let s:vimwiki_defaults.diary_link_fmt = '%Y-%m-%d'
let s:vimwiki_defaults.diary_link_count = 4
"}}}
" DEFAULT options {{{
call s:default('list', [s:vimwiki_defaults])
if &encoding == 'utf-8'
call s:default('upper', 'A-Z\u0410-\u042f')
call s:default('lower', 'a-z\u0430-\u044f')
else
call s:default('upper', 'A-Z')
call s:default('lower', 'a-z')
endif
call s:default('other', '0-9')
call s:default('stripsym', '_')
call s:default('badsyms', '')
call s:default('auto_checkbox', 1)
call s:default('use_mouse', 0)
call s:default('folding', 0)
call s:default('fold_trailing_empty_lines', 0)
call s:default('fold_lists', 0)
call s:default('menu', 'Vimwiki')
call s:default('global_ext', 1)
call s:default('hl_headers', 0)
call s:default('hl_cb_checked', 0)
call s:default('camel_case', 1)
call s:default('list_ignore_newline', 1)
call s:default('listsyms', ' .oOX')
if has("win32")
call s:default('browsers',
\ [
\ expand('~').'\Local Settings\Application Data\Google\Chrome\Application\chrome.exe',
\ 'C:\Program Files\Opera\opera.exe',
\ 'C:\Program Files\Mozilla Firefox\firefox.exe',
\ 'C:\Program Files\Internet Explorer\iexplore.exe',
\ ])
else
call s:default('browsers',
\ [
\ 'chromium-browser',
\ 'opera',
\ 'firefox',
\ 'konqueror',
\ ])
endif
call s:default('use_calendar', 1)
call s:default('table_auto_fmt', 1)
call s:default('w32_dir_enc', '')
call s:default('CJK_length', 0)
call s:default('dir_link', '')
call s:default('file_exts', 'pdf,txt,doc,rtf,xls,php,zip,rar,7z,html,gz')
call s:default('valid_html_tags', 'b,i,s,u,sub,sup,kbd,br,hr,div,center,strong,em')
call s:default('user_htmls', '')
call s:default('html_header_numbering', 0)
call s:default('html_header_numbering_sym', '')
call s:default('conceallevel', 3)
call s:default('current_idx', 0)
let upp = g:vimwiki_upper
let low = g:vimwiki_lower
let oth = g:vimwiki_other
let nup = low.oth
let nlo = upp.oth
let any = upp.nup
let wword = '\C\<['.upp.']['.nlo.']*['.low.']['.nup.']*['.upp.']['.any.']*\>'
let g:vimwiki_rxWikiWord = '!\@<!'.wword
let g:vimwiki_rxNoWikiWord = '!'.wword
let g:vimwiki_rxWikiLink1 = '\[\[[^\]]\+\]\]'
let g:vimwiki_rxWikiLink2 = '\[\[[^\]]\+\]\[[^\]]\+\]\]'
if g:vimwiki_camel_case
let g:vimwiki_rxWikiLink = g:vimwiki_rxWikiWord.'\|'.
\ g:vimwiki_rxWikiLink1.'\|'.g:vimwiki_rxWikiLink2
else
let g:vimwiki_rxWikiLink = g:vimwiki_rxWikiLink1.'\|'.g:vimwiki_rxWikiLink2
endif
let g:vimwiki_rxWeblink = '\%("[^"(]\+\((\([^)]\+\))\)\?":\)\?'.
\'\%('.
\'\%('.
\'\%(https\?\|ftp\|gopher\|telnet\|file\|notes\|ms-help\):'.
\'\%(\%(//\)\|\%(\\\\\)\)'.
\'\)'.
\'\|\%(mailto:\)'.
\'\)'.
\'\+\S\+'.
\'[().,?\]]\@<!'
"}}}
" AUTOCOMMANDS for all known wiki extensions {{{
" Getting all extensions that different wikies could have
let extensions = {}
for wiki in g:vimwiki_list
if has_key(wiki, 'ext')
let extensions[wiki.ext] = 1
else
let extensions['.wiki'] = 1
endif
endfor
augroup filetypedetect
" clear FlexWiki's stuff
au! * *.wiki
augroup end
augroup vimwiki
autocmd!
for ext in keys(extensions)
exe 'autocmd BufWinEnter *'.ext.' call s:setup_buffer_enter()'
exe 'autocmd BufLeave,BufHidden *'.ext.' call s:setup_buffer_leave()'
exe 'autocmd BufNewFile,BufRead, *'.ext.' call s:setup_filetype()'
" ColorScheme could have or could have not a
" VimwikiHeader1..VimwikiHeader6 highlight groups. We need to refresh
" syntax after colorscheme change.
exe 'autocmd ColorScheme *'.ext.' syntax enable'.
\ ' | call vimwiki#base#highlight_links()'
" Format tables when exit from insert mode. Do not use textwidth to
" autowrap tables.
if g:vimwiki_table_auto_fmt
exe 'autocmd InsertLeave *'.ext.' call vimwiki#tbl#format(line("."))'
exe 'autocmd InsertEnter *'.ext.' call vimwiki#tbl#reset_tw(line("."))'
endif
endfor
augroup END
"}}}
" COMMANDS {{{
command! VimwikiUISelect call vimwiki#base#ui_select()
command! -count VimwikiIndex
\ call vimwiki#base#goto_index(v:count1)
command! -count VimwikiTabIndex tabedit <bar>
\ call vimwiki#base#goto_index(v:count1)
command! -count VimwikiDiaryIndex
\ call vimwiki#diary#goto_index(v:count1)
command! -count VimwikiMakeDiaryNote
\ call vimwiki#diary#make_note(v:count1)
command! -count VimwikiTabMakeDiaryNote tabedit <bar>
\ call vimwiki#diary#make_note(v:count1)
"}}}
" MAPPINGS {{{
if !hasmapto('<Plug>VimwikiIndex')
nmap <silent><unique> <Leader>ww <Plug>VimwikiIndex
endif
nnoremap <unique><script> <Plug>VimwikiIndex :VimwikiIndex<CR>
if !hasmapto('<Plug>VimwikiTabIndex')
nmap <silent><unique> <Leader>wt <Plug>VimwikiTabIndex
endif
nnoremap <unique><script> <Plug>VimwikiTabIndex :VimwikiTabIndex<CR>
if !hasmapto('<Plug>VimwikiUISelect')
nmap <silent><unique> <Leader>ws <Plug>VimwikiUISelect
endif
nnoremap <unique><script> <Plug>VimwikiUISelect :VimwikiUISelect<CR>
if !hasmapto('<Plug>VimwikiDiaryIndex')
nmap <silent><unique> <Leader>wi <Plug>VimwikiDiaryIndex
endif
nnoremap <unique><script> <Plug>VimwikiDiaryIndex :VimwikiDiaryIndex<CR>
if !hasmapto('<Plug>VimwikiMakeDiaryNote')
nmap <silent><unique> <Leader>w<Leader>w <Plug>VimwikiMakeDiaryNote
endif
nnoremap <unique><script> <Plug>VimwikiMakeDiaryNote :VimwikiMakeDiaryNote<CR>
if !hasmapto('<Plug>VimwikiTabMakeDiaryNote')
nmap <silent><unique> <Leader>w<Leader>t <Plug>VimwikiTabMakeDiaryNote
endif
nnoremap <unique><script> <Plug>VimwikiTabMakeDiaryNote
\ :VimwikiTabMakeDiaryNote<CR>
"}}}
" MENU {{{
function! s:build_menu(topmenu)
let idx = 0
while idx < len(g:vimwiki_list)
let norm_path = fnamemodify(VimwikiGet('path', idx), ':h:t')
let norm_path = escape(norm_path, '\ \.')
execute 'menu '.a:topmenu.'.Open\ index.'.norm_path.
\ ' :call vimwiki#base#goto_index('.(idx + 1).')<CR>'
execute 'menu '.a:topmenu.'.Open/Create\ diary\ note.'.norm_path.
\ ' :call vimwiki#diary#make_note('.(idx + 1).')<CR>'
let idx += 1
endwhile
endfunction
function! s:build_table_menu(topmenu)
exe 'menu '.a:topmenu.'.-Sep- :'
exe 'menu '.a:topmenu.'.Table.Create\ (enter\ cols\ rows) :VimwikiTable '
exe 'nmenu '.a:topmenu.'.Table.Format<tab>gqq gqq'
exe 'nmenu '.a:topmenu.'.Table.Move\ column\ left<tab><A-Left> :VimwikiTableMoveColumnLeft<CR>'
exe 'nmenu '.a:topmenu.'.Table.Move\ column\ right<tab><A-Right> :VimwikiTableMoveColumnRight<CR>'
exe 'nmenu disable '.a:topmenu.'.Table'
endfunction
if !empty(g:vimwiki_menu)
call s:build_menu(g:vimwiki_menu)
call s:build_table_menu(g:vimwiki_menu)
endif
" }}}
" CALENDAR Hook "{{{
if g:vimwiki_use_calendar
let g:calendar_action = 'vimwiki#diary#calendar_action'
let g:calendar_sign = 'vimwiki#diary#calendar_sign'
endif
"}}}
let &cpo = s:old_cpo
-68
View File
@@ -1,68 +0,0 @@
" Vim reStructured Text
" (c) Mikolaj Machowski 2006
" Author: Mikolaj Machowski ( mikmach AT wp DOT pl )
" Last Change: 4 Nov 2006
" Version: 1.4
" License:
" Copyright (C) 2006 Mikolaj Machowski <mikmach@wp.pl>
"
" This script is free software; you can redistribute it and/or
" modify it under the terms of the GNU Library General Public
" License as published by the Free Software Foundation; either
" version 2 of the License, or (at your option) any later version.
"
" This library is distributed in the hope that it will be useful,
" but WITHOUT ANY WARRANTY; without even the implied warranty of
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
" Library General Public License for more details.
"
" You should have received a copy of the GNU Library General Public License
" along with this library; see the file COPYING.LIB. If not, write to
" the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
" Boston, MA 02110-1301, USA.
"
" VST requires Vim7
if v:version < 700
finish
endif
" Command :Vst
command! -range=% -nargs=? -complete=custom,VST_Args Vst call vst#vst#VST_Export(<line1>, <line2>, <q-args>)
command! -range=% -nargs=? -complete=custom,VST_Args Vsti call vst#vst#VST_InstantWrapper(<line1>, <line2>, <q-args>)
command! -range=% -nargs=? -complete=custom,VST_Args Vstm call VST_Menus()
" VST_Args: Command line completion for :Vst command {{{
function! VST_Args(A, C, P)
let args = "html,tex,latex,pdf,toc,head,fold,link,slink,rep,srep,preproc,help,rest"
return substitute(args, ',', '\n', 'g')
endfunction
" }}}
" Menus {{{
function! VST_Menus()
if has("gui_running")
menu VreST.Export\ to\ HTML :Vst html<cr>
menu VreST.Export\ to\ LaTeX :Vst tex<cr>
menu VreST.Export\ to\ PDF :Vst pdf<cr>
menu VreST.Export\ to\ reST :Vst rest<cr>
menu VreST.Fold :Vst fold<cr>
menu VreST.Headers :Vst head<cr>
menu VreST.TOC :Vst toc<cr>
menu VreST.Help :Vst help<cr>
inoremenu VreST.Export\ to\ HTML <c-o>:Vst html<cr>
inoremenu VreST.Export\ to\ LaTeX <c-o>:Vst tex<cr>
inoremenu VreST.Export\ to\ PDF <c-o>:Vst pdf<cr>
inoremenu VreST.Export\ to\ reST <c-o>:Vst rest<cr>
inoremenu VreST.Fold <c-o>:Vst fold<cr>
inoremenu VreST.Headers <c-o>:Vst head<cr>
inoremenu VreST.TOC <c-o>:Vst toc<cr>
inoremenu VreST.Help <c-o>:Vst help<cr>
endif
endfunction
if exists("g:vst_showmenu") && g:vst_load_menus != 0
call VST_Menus()
endif
" }}}
" Load auxiliary mappings:
call vst#vst#VST_AuxiliaryMappings()
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4:nowrap
-99
View File
@@ -1,99 +0,0 @@
if &cp || exists("g:loaded_zoom")
finish
endif
let g:loaded_zoom = 1
let s:save_cpo = &cpo
set cpo&vim
" keep default value
let s:current_font = &guifont
" command
command! -narg=0 ZoomIn :call s:ZoomIn()
command! -narg=0 ZoomOut :call s:ZoomOut()
command! -narg=0 ZoomReset :call s:ZoomReset()
" map
"gryf: I like keypad mappings
nmap <kPlus> :ZoomIn<CR>
nmap <kMinus> :ZoomOut<CR>
nmap <kDivide> :ZoomReset<CR>
" guifont size + 1
function! s:ZoomIn()
" gryf: Let's check, what system we are dealing with
if has("win32")
let l:fsize = substitute(&guifont, '^.*:h\([^:]*\).*$', '\1', '')
let l:fsize += 1
let l:guifont = substitute(&guifont, ':h\([^:]*\)', ':h' . l:fsize, '')
let &guifont = l:guifont
elseif has('unix')
" gryf: might not work on os x though
let l:font = split(&guifont)
let l:font[-1] = l:font[-1] + 1
let &guifont = join(l:font, " ")
endif
endfunction
" guifont size - 1
function! s:ZoomOut()
" gryf: same as above
if has("win32")
let l:fsize = substitute(&guifont, '^.*:h\([^:]*\).*$', '\1', '')
let l:fsize -= 1
let l:guifont = substitute(&guifont, ':h\([^:]*\)', ':h' . l:fsize, '')
let &guifont = l:guifont
elseif has('unix')
let l:font = split(&guifont)
let l:font[-1] = l:font[-1] - 1
let &guifont = join(l:font, " ")
endif
endfunction
" reset guifont size
function! s:ZoomReset()
let &guifont = s:current_font
endfunction
let &cpo = s:save_cpo
finish
==============================================================================
zoom.vim : control gui font size with "+" or "-" keys.
------------------------------------------------------------------------------
$VIMRUNTIMEPATH/plugin/zoom.vim
==============================================================================
author : OMI TAKU
url : http://nanasi.jp/
email : mail@nanasi.jp
version : 2008/07/18 10:00:00
==============================================================================
Control Vim editor font size with key "+", or key "-".
Press "+" key, Vim editor gui font size will change bigger.
And, press "-" key, Vim editor gui font size will change smaller.
This plugin is for GUI only.
Normal Mode:
+ ... change font size bigger
- ... change font size smaller
Command-line Mode:
:ZoomIn ... change font size bigger
:ZoomOut ... change font size smaller
:ZoomReset ... reset font size changes.
==============================================================================
1. Copy the zoom.vim script to
$HOME/vimfiles/plugin or $HOME/.vim/plugin directory.
Refer to ':help add-plugin', ':help add-global-plugin' and
':help runtimepath' for more details about Vim plugins.
2. Restart Vim.
==============================================================================
" vim: set ff=unix et ft=vim nowrap :