diff options
| author | Ben Beltran <ben@freshout.us> | 2013-06-05 10:50:57 -0500 |
|---|---|---|
| committer | Ben Beltran <ben@freshout.us> | 2013-06-05 10:50:57 -0500 |
| commit | fe337504f2fb3ded76326b1e3d4d02787a27d853 (patch) | |
| tree | b84891d78de37ae078ea9850a541799b5bca8085 /vim/plugin | |
| parent | e23d7a9f7363bdc69e95a1df31e093db15459fcf (diff) | |
Aand that's all the plugins.
Diffstat (limited to 'vim/plugin')
| -rw-r--r-- | vim/plugin/31-create-scala.vim | 55 | ||||
| -rw-r--r-- | vim/plugin/fugitive.vim | 2220 | ||||
| -rw-r--r-- | vim/plugin/gist.vim | 826 | ||||
| -rw-r--r-- | vim/plugin/indent-object.vim | 224 | ||||
| -rw-r--r-- | vim/plugin/rails.vim | 339 | ||||
| -rw-r--r-- | vim/plugin/searchfold_0.9.vim | 319 | ||||
| -rw-r--r-- | vim/plugin/showmarks.vim | 507 | ||||
| -rw-r--r-- | vim/plugin/snipMate.vim | 271 | ||||
| -rw-r--r-- | vim/plugin/supertab.vim | 737 | ||||
| -rw-r--r-- | vim/plugin/surround.vim | 625 | ||||
| -rw-r--r-- | vim/plugin/syntastic.vim | 614 | ||||
| -rw-r--r-- | vim/plugin/tagbar.vim | 118 | ||||
| -rw-r--r-- | vim/plugin/taglist.vim | 4546 | ||||
| -rw-r--r-- | vim/plugin/unimpaired.vim | 315 | ||||
| -rw-r--r-- | vim/plugin/vim-rspec.rb | 32 | ||||
| -rw-r--r-- | vim/plugin/vim-rspec.vim | 174 | ||||
| -rw-r--r-- | vim/plugin/vim-rspec.xsl | 55 |
17 files changed, 0 insertions, 11977 deletions
diff --git a/vim/plugin/31-create-scala.vim b/vim/plugin/31-create-scala.vim deleted file mode 100644 index e4ecb44..0000000 --- a/vim/plugin/31-create-scala.vim +++ /dev/null @@ -1,55 +0,0 @@ -" Vim plugin that generates new Scala source file when you type -" vim nonexistent.scala. -" Scripts tries to detect package name from the directory path, e. g. -" .../src/main/scala/com/mycompany/myapp/app.scala gets header -" package com.mycompany.myapp -" -" Author : Stepan Koltsov <yozh@mx1.ru> - -function! MakeScalaFile() - if exists("b:template_used") && b:template_used - return - endif - - let b:template_used = 1 - - let filename = expand("<afile>:p") - let x = substitute(filename, "\.scala$", "", "") - - let p = substitute(x, "/[^/]*$", "", "") - let p = substitute(p, "/", ".", "g") - let p = substitute(p, ".*\.src$", "@", "") " unnamed package - let p = substitute(p, ".*\.src\.", "!", "") - let p = substitute(p, "^!main\.scala\.", "!", "") " - let p = substitute(p, "^!.*\.ru\.", "!ru.", "") - let p = substitute(p, "^!.*\.org\.", "!org.", "") - let p = substitute(p, "^!.*\.com\.", "!com.", "") - - " ! marks that we found package name. - if match(p, "^!") == 0 - let p = substitute(p, "^!", "", "") - else - " Don't know package name. - let p = "@" - endif - - let class = substitute(x, ".*/", "", "") - - if p != "@" - call append("0", "package " . p) - endif - - "norm G - "call append(".", "class " . class . " {") - - "norm G - "call append(".", "} /// end of " . class) - - call append(".", "// vim: set ts=4 sw=4 et:") - call append(".", "") - -endfunction - -au BufNewFile *.scala call MakeScalaFile() - -" vim: set ts=4 sw=4 et: diff --git a/vim/plugin/fugitive.vim b/vim/plugin/fugitive.vim deleted file mode 100644 index 17d52fc..0000000 --- a/vim/plugin/fugitive.vim +++ /dev/null @@ -1,2220 +0,0 @@ -" fugitive.vim - A Git wrapper so awesome, it should be illegal -" Maintainer: Tim Pope <http://tpo.pe/> -" Version: 1.2 -" GetLatestVimScripts: 2975 1 :AutoInstall: fugitive.vim - -if exists('g:loaded_fugitive') || &cp - finish -endif -let g:loaded_fugitive = 1 - -if !exists('g:fugitive_git_executable') - let g:fugitive_git_executable = 'git' -endif - -" Utility {{{1 - -function! s:function(name) abort - return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) -endfunction - -function! s:sub(str,pat,rep) abort - return substitute(a:str,'\v\C'.a:pat,a:rep,'') -endfunction - -function! s:gsub(str,pat,rep) abort - return substitute(a:str,'\v\C'.a:pat,a:rep,'g') -endfunction - -function! s:shellesc(arg) abort - if a:arg =~ '^[A-Za-z0-9_/.-]\+$' - return a:arg - elseif &shell =~# 'cmd' && a:arg !~# '"' - return '"'.a:arg.'"' - else - return shellescape(a:arg) - endif -endfunction - -function! s:fnameescape(file) abort - if exists('*fnameescape') - return fnameescape(a:file) - else - return escape(a:file," \t\n*?[{`$\\%#'\"|!<") - endif -endfunction - -function! s:throw(string) abort - let v:errmsg = 'fugitive: '.a:string - throw v:errmsg -endfunction - -function! s:warn(str) - echohl WarningMsg - echomsg a:str - echohl None - let v:warningmsg = a:str -endfunction - -function! s:shellslash(path) - if exists('+shellslash') && !&shellslash - return s:gsub(a:path,'\\','/') - else - return a:path - endif -endfunction - -function! s:recall() - let rev = s:buffer().rev() - if rev ==# ':' - return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*') - endif - return rev -endfunction - -function! s:add_methods(namespace, method_names) abort - for name in a:method_names - let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name) - endfor -endfunction - -let s:commands = [] -function! s:command(definition) abort - let s:commands += [a:definition] -endfunction - -function! s:define_commands() - for command in s:commands - exe 'command! -buffer '.command - endfor -endfunction - -function! s:compatibility_check() - if exists('b:git_dir') && exists('*GitBranchInfoCheckGitDir') && !exists('g:fugitive_did_compatibility_warning') - let g:fugitive_did_compatibility_warning = 1 - call s:warn("See http://github.com/tpope/vim-fugitive/issues#issue/1 for why you should remove git-branch-info.vim") - endif -endfunction - -augroup fugitive_utility - autocmd! - autocmd User Fugitive call s:define_commands() - autocmd VimEnter * call s:compatibility_check() -augroup END - -let s:abstract_prototype = {} - -" }}}1 -" Initialization {{{1 - -function! s:ExtractGitDir(path) abort - let path = s:shellslash(a:path) - if path =~? '^fugitive://.*//' - return matchstr(path,'fugitive://\zs.\{-\}\ze//') - endif - let fn = fnamemodify(path,':s?[\/]$??') - let ofn = "" - let nfn = fn - while fn != ofn - if filereadable(fn . '/.git/HEAD') - return s:sub(simplify(fnamemodify(fn . '/.git',':p')),'\W$','') - elseif fn =~ '\.git$' && filereadable(fn . '/HEAD') - return s:sub(simplify(fnamemodify(fn,':p')),'\W$','') - endif - let ofn = fn - let fn = fnamemodify(ofn,':h') - endwhile - return '' -endfunction - -function! s:Detect(path) - if exists('b:git_dir') && b:git_dir ==# '' - unlet b:git_dir - endif - if !exists('b:git_dir') - let dir = s:ExtractGitDir(a:path) - if dir != '' - let b:git_dir = dir - endif - endif - if exists('b:git_dir') - silent doautocmd User Fugitive - cnoremap <expr> <buffer> <C-R><C-G> <SID>recall() - let buffer = fugitive#buffer() - if expand('%:p') =~# '//' - call buffer.setvar('&path',s:sub(buffer.getvar('&path'),'^\.%(,|$)','')) - endif - if stridx(buffer.getvar('&tags'),escape(b:git_dir.'/tags',', ')) == -1 - call buffer.setvar('&tags',escape(b:git_dir.'/tags',', ').','.buffer.getvar('&tags')) - if &filetype != '' - call buffer.setvar('&tags',escape(b:git_dir.'/'.&filetype.'.tags',', ').','.buffer.getvar('&tags')) - endif - endif - endif -endfunction - -augroup fugitive - autocmd! - autocmd BufNewFile,BufReadPost * call s:Detect(expand('<amatch>:p')) - autocmd FileType netrw call s:Detect(expand('<afile>:p')) - autocmd VimEnter * if expand('<amatch>')==''|call s:Detect(getcwd())|endif - autocmd BufWinLeave * execute getwinvar(+winnr(), 'fugitive_leave') -augroup END - -" }}}1 -" Repository {{{1 - -let s:repo_prototype = {} -let s:repos = {} - -function! s:repo(...) abort - let dir = a:0 ? a:1 : (exists('b:git_dir') && b:git_dir !=# '' ? b:git_dir : s:ExtractGitDir(expand('%:p'))) - if dir !=# '' - if has_key(s:repos,dir) - let repo = get(s:repos,dir) - else - let repo = {'git_dir': dir} - let s:repos[dir] = repo - endif - return extend(extend(repo,s:repo_prototype,'keep'),s:abstract_prototype,'keep') - endif - call s:throw('not a git repository: '.expand('%:p')) -endfunction - -function! s:repo_dir(...) dict abort - return join([self.git_dir]+a:000,'/') -endfunction - -function! s:repo_tree(...) dict abort - if !self.bare() - let dir = fnamemodify(self.git_dir,':h') - return join([dir]+a:000,'/') - endif - call s:throw('no work tree') -endfunction - -function! s:repo_bare() dict abort - return self.dir() !~# '/\.git$' -endfunction - -function! s:repo_translate(spec) dict abort - if a:spec ==# '.' || a:spec ==# '/.' - return self.bare() ? self.dir() : self.tree() - elseif a:spec =~# '^/' - return fnamemodify(self.dir(),':h').a:spec - elseif a:spec =~# '^:[0-3]:' - return 'fugitive://'.self.dir().'//'.a:spec[1].'/'.a:spec[3:-1] - elseif a:spec ==# ':' - if $GIT_INDEX_FILE =~# '/[^/]*index[^/]*\.lock$' && fnamemodify($GIT_INDEX_FILE,':p')[0:strlen(s:repo().dir())] ==# s:repo().dir('') && filereadable($GIT_INDEX_FILE) - return fnamemodify($GIT_INDEX_FILE,':p') - else - return self.dir('index') - endif - elseif a:spec =~# '^:/' - let ref = self.rev_parse(matchstr(a:spec,'.[^:]*')) - return 'fugitive://'.self.dir().'//'.ref - elseif a:spec =~# '^:' - return 'fugitive://'.self.dir().'//0/'.a:spec[1:-1] - elseif a:spec =~# 'HEAD\|^refs/' && a:spec !~ ':' && filereadable(self.dir(a:spec)) - return self.dir(a:spec) - elseif filereadable(s:repo().dir('refs/'.a:spec)) - return self.dir('refs/'.a:spec) - elseif filereadable(s:repo().dir('refs/tags/'.a:spec)) - return self.dir('refs/tags/'.a:spec) - elseif filereadable(s:repo().dir('refs/heads/'.a:spec)) - return self.dir('refs/heads/'.a:spec) - elseif filereadable(s:repo().dir('refs/remotes/'.a:spec)) - return self.dir('refs/remotes/'.a:spec) - elseif filereadable(s:repo().dir('refs/remotes/'.a:spec.'/HEAD')) - return self.dir('refs/remotes/'.a:spec,'/HEAD') - else - try - let ref = self.rev_parse(matchstr(a:spec,'[^:]*')) - let path = s:sub(matchstr(a:spec,':.*'),'^:','/') - return 'fugitive://'.self.dir().'//'.ref.path - catch /^fugitive:/ - return self.tree(a:spec) - endtry - endif -endfunction - -call s:add_methods('repo',['dir','tree','bare','translate']) - -function! s:repo_git_command(...) dict abort - let git = g:fugitive_git_executable . ' --git-dir='.s:shellesc(self.git_dir) - return git.join(map(copy(a:000),'" ".s:shellesc(v:val)'),'') -endfunction - -function! s:repo_git_chomp(...) dict abort - return s:sub(system(call(self.git_command,a:000,self)),'\n$','') -endfunction - -function! s:repo_git_chomp_in_tree(...) dict abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - return call(s:repo().git_chomp, a:000, s:repo()) - finally - execute cd.'`=dir`' - endtry -endfunction - -function! s:repo_rev_parse(rev) dict abort - let hash = self.git_chomp('rev-parse','--verify',a:rev) - if hash =~ '\<\x\{40\}$' - return matchstr(hash,'\<\x\{40\}$') - endif - call s:throw('rev-parse '.a:rev.': '.hash) -endfunction - -call s:add_methods('repo',['git_command','git_chomp','git_chomp_in_tree','rev_parse']) - -function! s:repo_dirglob(base) dict abort - let base = s:sub(a:base,'^/','') - let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*/')),"\n") - call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]') - return matches -endfunction - -function! s:repo_superglob(base) dict abort - if a:base =~# '^/' || a:base !~# ':' - let results = [] - if a:base !~# '^/' - let heads = ["HEAD","ORIG_HEAD","FETCH_HEAD","MERGE_HEAD"] - let heads += sort(split(s:repo().git_chomp("rev-parse","--symbolic","--branches","--tags","--remotes"),"\n")) - call filter(heads,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - let results += heads - endif - if !self.bare() - let base = s:sub(a:base,'^/','') - let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*')),"\n") - call map(matches,'s:shellslash(v:val)') - call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val') - call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]') - let results += matches - endif - return results - - elseif a:base =~# '^:' - let entries = split(self.git_chomp('ls-files','--stage'),"\n") - call map(entries,'s:sub(v:val,".*(\\d)\\t(.*)",":\\1:\\2")') - if a:base !~# '^:[0-3]\%(:\|$\)' - call filter(entries,'v:val[1] == "0"') - call map(entries,'v:val[2:-1]') - endif - call filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - return entries - - else - let tree = matchstr(a:base,'.*[:/]') - let entries = split(self.git_chomp('ls-tree',tree),"\n") - call map(entries,'s:sub(v:val,"^04.*\\zs$","/")') - call map(entries,'tree.s:sub(v:val,".*\t","")') - return filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - endif -endfunction - -call s:add_methods('repo',['dirglob','superglob']) - -function! s:repo_config(conf) dict abort - return matchstr(system(s:repo().git_command('config').' '.a:conf),"[^\r\n]*") -endfun - -function! s:repo_user() dict abort - let username = s:repo().config('user.name') - let useremail = s:repo().config('user.email') - return username.' <'.useremail.'>' -endfun - -function! s:repo_aliases() dict abort - if !has_key(self,'_aliases') - let self._aliases = {} - for line in split(self.git_chomp('config','--get-regexp','^alias[.]'),"\n") - let self._aliases[matchstr(line,'\.\zs\S\+')] = matchstr(line,' \zs.*') - endfor - endif - return self._aliases -endfunction - -call s:add_methods('repo',['config', 'user', 'aliases']) - -function! s:repo_keywordprg() dict abort - let args = ' --git-dir='.escape(self.dir(),"\\\"' ").' show' - if has('gui_running') && !has('win32') - return g:fugitive_git_executable . ' --no-pager' . args - else - return g:fugitive_git_executable . args - endif -endfunction - -call s:add_methods('repo',['keywordprg']) - -" }}}1 -" Buffer {{{1 - -let s:buffer_prototype = {} - -function! s:buffer(...) abort - let buffer = {'#': bufnr(a:0 ? a:1 : '%')} - call extend(extend(buffer,s:buffer_prototype,'keep'),s:abstract_prototype,'keep') - if buffer.getvar('git_dir') !=# '' - return buffer - endif - call s:throw('not a git repository: '.expand('%:p')) -endfunction - -function! fugitive#buffer(...) abort - return s:buffer(a:0 ? a:1 : '%') -endfunction - -function! s:buffer_getvar(var) dict abort - return getbufvar(self['#'],a:var) -endfunction - -function! s:buffer_setvar(var,value) dict abort - return setbufvar(self['#'],a:var,a:value) -endfunction - -function! s:buffer_getline(lnum) dict abort - return getbufline(self['#'],a:lnum)[0] -endfunction - -function! s:buffer_repo() dict abort - return s:repo(self.getvar('git_dir')) -endfunction - -function! s:buffer_type(...) dict abort - if self.getvar('fugitive_type') != '' - let type = self.getvar('fugitive_type') - elseif fnamemodify(self.spec(),':p') =~# '.\git/refs/\|\.git/\w*HEAD$' - let type = 'head' - elseif self.getline(1) =~ '^tree \x\{40\}$' && self.getline(2) == '' - let type = 'tree' - elseif self.getline(1) =~ '^\d\{6\} \w\{4\} \x\{40\}\>\t' - let type = 'tree' - elseif self.getline(1) =~ '^\d\{6\} \x\{40\}\> \d\t' - let type = 'index' - elseif isdirectory(self.spec()) - let type = 'directory' - elseif self.spec() == '' - let type = 'null' - else - let type = 'file' - endif - if a:0 - return !empty(filter(copy(a:000),'v:val ==# type')) - else - return type - endif -endfunction - -if has('win32') - - function! s:buffer_spec() dict abort - let bufname = bufname(self['#']) - let retval = '' - for i in split(bufname,'[^:]\zs\\') - let retval = fnamemodify((retval==''?'':retval.'\').i,':.') - endfor - return s:shellslash(fnamemodify(retval,':p')) - endfunction - -else - - function! s:buffer_spec() dict abort - let bufname = bufname(self['#']) - return s:shellslash(bufname == '' ? '' : fnamemodify(bufname,':p')) - endfunction - -endif - -function! s:buffer_name() dict abort - return self.spec() -endfunction - -function! s:buffer_commit() dict abort - return matchstr(self.spec(),'^fugitive://.\{-\}//\zs\w*') -endfunction - -function! s:buffer_path(...) dict abort - let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*') - if rev != '' - let rev = s:sub(rev,'\w*','') - else - let rev = self.spec()[strlen(self.repo().tree()) : -1] - endif - return s:sub(s:sub(rev,'.\zs/$',''),'^/',a:0 ? a:1 : '') -endfunction - -function! s:buffer_rev() dict abort - let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*') - if rev =~ '^\x/' - return ':'.rev[0].':'.rev[2:-1] - elseif rev =~ '.' - return s:sub(rev,'/',':') - elseif self.spec() =~ '\.git/index$' - return ':' - elseif self.spec() =~ '\.git/refs/\|\.git/.*HEAD$' - return self.spec()[strlen(self.repo().dir())+1 : -1] - else - return self.path() - endif -endfunction - -function! s:buffer_sha1() dict abort - if self.spec() =~ '^fugitive://' || self.spec() =~ '\.git/refs/\|\.git/.*HEAD$' - return self.repo().rev_parse(self.rev()) - else - return '' - endif -endfunction - -function! s:buffer_expand(rev) dict abort - if a:rev =~# '^:[0-3]$' - let file = a:rev.self.path(':') - elseif a:rev =~# '^[-:]/$' - let file = '/'.self.path() - elseif a:rev =~# '^-' - let file = 'HEAD^{}'.a:rev[1:-1].self.path(':') - elseif a:rev =~# '^@{' - let file = 'HEAD'.a:rev.self.path(':') - elseif a:rev =~# '^[~^]' - let commit = s:sub(self.commit(),'^\d=$','HEAD') - let file = commit.a:rev.self.path(':') - else - let file = a:rev - endif - return s:sub(s:sub(file,'\%$',self.path()),'\.\@<=/$','') -endfunction - -function! s:buffer_containing_commit() dict abort - if self.commit() =~# '^\d$' - return ':' - elseif self.commit() =~# '.' - return self.commit() - else - return 'HEAD' - endif -endfunction - -call s:add_methods('buffer',['getvar','setvar','getline','repo','type','spec','name','commit','path','rev','sha1','expand','containing_commit']) - -" }}}1 -" Git {{{1 - -call s:command("-bang -nargs=? -complete=customlist,s:GitComplete Git :execute s:Git(<bang>0,<q-args>)") - -function! s:ExecuteInTree(cmd) abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - execute a:cmd - finally - execute cd.'`=dir`' - endtry -endfunction - -function! s:Git(bang,cmd) abort - if a:bang - return s:Edit('edit',1,a:cmd) - endif - let git = s:repo().git_command() - if has('gui_running') && !has('win32') - let git .= ' --no-pager' - endif - let cmd = matchstr(a:cmd,'\v\C.{-}%($|\\@<!%(\\\\)*\|)@=') - call s:ExecuteInTree('!'.git.' '.cmd) - call fugitive#reload_status() - return matchstr(a:cmd,'\v\C\\@<!%(\\\\)*\|\zs.*') -endfunction - -function! s:GitComplete(A,L,P) abort - if !exists('s:exec_path') - let s:exec_path = s:sub(system(g:fugitive_git_executable.' --exec-path'),'\n$','') - endif - let cmds = map(split(glob(s:exec_path.'/git-*'),"\n"),'s:sub(v:val[strlen(s:exec_path)+5 : -1],"\\.exe$","")') - if a:L =~ ' [[:alnum:]-]\+ ' - return s:repo().superglob(a:A) - elseif a:A == '' - return sort(cmds+keys(s:repo().aliases())) - else - return filter(sort(cmds+keys(s:repo().aliases())),'v:val[0:strlen(a:A)-1] ==# a:A') - endif -endfunction - -" }}}1 -" Gcd, Glcd {{{1 - -function! s:DirComplete(A,L,P) abort - let matches = s:repo().dirglob(a:A) - return matches -endfunction - -call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Gcd :cd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`") -call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Glcd :lcd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`") - -" }}}1 -" Gstatus {{{1 - -call s:command("-bar Gstatus :execute s:Status()") - -function! s:Status() abort - try - Gpedit : - wincmd P - nnoremap <buffer> <silent> q :<C-U>bdelete<CR> - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return '' -endfunction - -function! fugitive#reload_status() abort - let mytab = tabpagenr() - for tab in [mytab] + range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - if getbufvar(tabpagebuflist(tab)[winnr-1],'fugitive_type') ==# 'index' - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - if !&modified - call s:BufReadIndex() - endif - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - endif - endfor - endfor -endfunction - -function! s:StageReloadSeek(target,lnum1,lnum2) - let jump = a:target - let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.*') - if f !=# '' | let jump = f | endif - let f = matchstr(getline(a:lnum2+1),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.*') - if f !=# '' | let jump = f | endif - silent! edit! - 1 - redraw - call search('^#\t\%([[:alpha:] ]\+: *\)\=\V'.jump.'\%( (new commits)\)\=\$','W') -endfunction - -function! s:StageDiff(diff) abort - let section = getline(search('^# .*:$','bcnW')) - let line = getline('.') - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - if filename ==# '' && section ==# '# Changes to be committed:' - return 'Git diff --cached' - elseif filename ==# '' - return 'Git diff' - elseif line =~# '^#\trenamed:' && filename =~# ' -> ' - let [old, new] = split(filename,' -> ') - execute 'Gedit '.s:fnameescape(':0:'.new) - return a:diff.' HEAD:'.s:fnameescape(old) - elseif section ==# '# Changes to be committed:' - execute 'Gedit '.s:fnameescape(':0:'.filename) - return a:diff.' -' - else - execute 'Gedit '.s:fnameescape('/'.filename) - return a:diff - endif -endfunction - -function! s:StageDiffEdit() abort - let section = getline(search('^# .*:$','bcnW')) - let line = getline('.') - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - let arg = (filename ==# '' ? '.' : filename) - if section ==# '# Changes to be committed:' - return 'Git! diff --cached '.s:shellesc(arg) - elseif section ==# '# Untracked files:' - let repo = s:repo() - call repo.git_chomp_in_tree('add','--intent-to-add',arg) - if arg ==# '.' - silent! edit! - 1 - if !search('^# Change\%(d but not updated\|s not staged for commit\):$','W') - call search('^# Change','W') - endif - else - call s:StageReloadSeek(arg,line('.'),line('.')) - endif - return '' - else - return 'Git! diff '.s:shellesc(arg) - endif -endfunction - -function! s:StageToggle(lnum1,lnum2) abort - try - let output = '' - for lnum in range(a:lnum1,a:lnum2) - let line = getline(lnum) - let repo = s:repo() - if line ==# '# Changes to be committed:' - call repo.git_chomp_in_tree('reset','-q') - silent! edit! - 1 - if !search('^# Untracked files:$','W') - call search('^# Change','W') - endif - return '' - elseif line =~# '^# Change\%(d but not updated\|s not staged for commit\):$' - call repo.git_chomp_in_tree('add','-u') - silent! edit! - 1 - if !search('^# Untracked files:$','W') - call search('^# Change','W') - endif - return '' - elseif line ==# '# Untracked files:' - call repo.git_chomp_in_tree('add','.') - silent! edit! - 1 - call search('^# Change','W') - return '' - endif - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (\a\+ [[:alpha:], ]\+)\)\=$') - if filename ==# '' - continue - endif - if !exists('first_filename') - let first_filename = filename - endif - execute lnum - let section = getline(search('^# .*:$','bnW')) - if line =~# '^#\trenamed:' && filename =~ ' -> ' - let cmd = ['mv','--'] + reverse(split(filename,' -> ')) - let filename = cmd[-1] - elseif section =~? ' to be ' - let cmd = ['reset','-q','--',filename] - elseif line =~# '^#\tdeleted:' - let cmd = ['rm','--',filename] - else - let cmd = ['add','--',filename] - endif - let output .= call(repo.git_chomp_in_tree,cmd,s:repo())."\n" - endfor - if exists('first_filename') - call s:StageReloadSeek(first_filename,a:lnum1,a:lnum2) - endif - echo s:sub(s:gsub(output,'\n+','\n'),'\n$','') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return 'checktime' -endfunction - -function! s:StagePatch(lnum1,lnum2) abort - let add = [] - let reset = [] - - for lnum in range(a:lnum1,a:lnum2) - let line = getline(lnum) - if line ==# '# Changes to be committed:' - return 'Git reset --patch' - elseif line =~# '^# Change\%(d but not updated\|s not staged for commit\):$' - return 'Git add --patch' - endif - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - if filename ==# '' - continue - endif - if !exists('first_filename') - let first_filename = filename - endif - execute lnum - let section = getline(search('^# .*:$','bnW')) - if line =~# '^#\trenamed:' && filename =~ ' -> ' - let reset += [split(filename,' -> ')[1]] - elseif section =~? ' to be ' - let reset += [filename] - elseif line !~# '^#\tdeleted:' - let add += [filename] - endif - endfor - try - if !empty(add) - execute "Git add --patch -- ".join(map(add,'s:shellesc(v:val)')) - endif - if !empty(reset) - execute "Git reset --patch -- ".join(map(add,'s:shellesc(v:val)')) - endif - if exists('first_filename') - silent! edit! - 1 - redraw - call search('^#\t\%([[:alpha:] ]\+: *\)\=\V'.first_filename.'\%( (new commits)\)\=\$','W') - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return 'checktime' -endfunction - -" }}}1 -" Gcommit {{{1 - -call s:command("-nargs=? -complete=customlist,s:CommitComplete Gcommit :execute s:Commit(<q-args>)") - -function! s:Commit(args) abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - let msgfile = s:repo().dir('COMMIT_EDITMSG') - let outfile = tempname() - let errorfile = tempname() - try - execute cd.'`=s:repo().tree()`' - if &shell =~# 'cmd' - let command = '' - let old_editor = $GIT_EDITOR - let $GIT_EDITOR = 'false' - else - let command = 'env GIT_EDITOR=false ' - endif - let command .= s:repo().git_command('commit').' '.a:args - if &shell =~# 'csh' - silent execute '!('.command.' > '.outfile.') >& '.errorfile - elseif a:args =~# '\%(^\| \)--interactive\>' - execute '!'.command.' 2> '.errorfile - else - silent execute '!'.command.' > '.outfile.' 2> '.errorfile - endif - if !has('gui_running') - redraw! - endif - if !v:shell_error - if filereadable(outfile) - for line in readfile(outfile) - echo line - endfor - endif - return '' - else - let errors = readfile(errorfile) - let error = get(errors,-2,get(errors,-1,'!')) - if error =~# '\<false''\=\.$' - let args = a:args - let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-[se]|--edit|--interactive)%($| )','') - let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-F|--file|-m|--message)%(\s+|\=)%(''[^'']*''|"%(\\.|[^"])*"|\\.|\S)*','') - let args = s:gsub(args,'%(^| )@<=[%#]%(:\w)*','\=expand(submatch(0))') - let args = '-F '.s:shellesc(msgfile).' '.args - if args !~# '\%(^\| \)--cleanup\>' - let args = '--cleanup=strip '.args - endif - if bufname('%') == '' && line('$') == 1 && getline(1) == '' && !&mod - keepalt edit `=msgfile` - elseif s:buffer().type() ==# 'index' - keepalt edit `=msgfile` - execute (search('^#','n')+1).'wincmd+' - setlocal nopreviewwindow - else - keepalt split `=msgfile` - endif - let b:fugitive_commit_arguments = args - setlocal bufhidden=delete filetype=gitcommit - return '1' - elseif error ==# '!' - return s:Status() - else - call s:throw(error) - endif - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - finally - if exists('old_editor') - let $GIT_EDITOR = old_editor - endif - call delete(outfile) - call delete(errorfile) - execute cd.'`=dir`' - call fugitive#reload_status() - endtry -endfunction - -function! s:CommitComplete(A,L,P) abort - if a:A =~ '^-' || type(a:A) == type(0) " a:A is 0 on :Gcommit -<Tab> - let args = ['-C', '-F', '-a', '-c', '-e', '-i', '-m', '-n', '-o', '-q', '-s', '-t', '-u', '-v', '--all', '--allow-empty', '--amend', '--author=', '--cleanup=', '--dry-run', '--edit', '--file=', '--include', '--interactive', '--message=', '--no-verify', '--only', '--quiet', '--reedit-message=', '--reuse-message=', '--signoff', '--template=', '--untracked-files', '--verbose'] - return filter(args,'v:val[0 : strlen(a:A)-1] ==# a:A') - else - return s:repo().superglob(a:A) - endif -endfunction - -function! s:FinishCommit() - let args = getbufvar(+expand('<abuf>'),'fugitive_commit_arguments') - if !empty(args) - call setbufvar(+expand('<abuf>'),'fugitive_commit_arguments','') - return s:Commit(args) - endif - return '' -endfunction - -augroup fugitive_commit - autocmd! - autocmd VimLeavePre,BufDelete *.git/COMMIT_EDITMSG execute s:sub(s:FinishCommit(), '^echoerr (.*)', 'echohl ErrorMsg|echo \1|echohl NONE') -augroup END - -" }}}1 -" Ggrep, Glog {{{1 - -if !exists('g:fugitive_summary_format') - let g:fugitive_summary_format = '%s' -endif - -call s:command("-bang -nargs=? -complete=customlist,s:EditComplete Ggrep :execute s:Grep(<bang>0,<q-args>)") -call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Glog :execute s:Log('grep<bang>',<f-args>)") - -function! s:Grep(bang,arg) abort - let grepprg = &grepprg - let grepformat = &grepformat - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - let &grepprg = s:repo().git_command('--no-pager', 'grep', '-n') - let &grepformat = '%f:%l:%m' - exe 'grep! '.escape(matchstr(a:arg,'\v\C.{-}%($|[''" ]\@=\|)@='),'|') - let list = getqflist() - for entry in list - if bufname(entry.bufnr) =~ ':' - let entry.filename = s:repo().translate(bufname(entry.bufnr)) - unlet! entry.bufnr - elseif a:arg =~# '\%(^\| \)--cached\>' - let entry.filename = s:repo().translate(':0:'.bufname(entry.bufnr)) - unlet! entry.bufnr - endif - endfor - call setqflist(list,'r') - if !a:bang && !empty(list) - return 'cfirst'.matchstr(a:arg,'\v\C[''" ]\zs\|.*') - else - return matchstr(a:arg,'\v\C[''" ]\|\zs.*') - endif - finally - let &grepprg = grepprg - let &grepformat = grepformat - execute cd.'`=dir`' - endtry -endfunction - -function! s:Log(cmd,...) - let path = s:buffer().path('/') - if path =~# '^/\.git\%(/\|$\)' || index(a:000,'--') != -1 - let path = '' - endif - let cmd = ['--no-pager', 'log', '--no-color'] - let cmd += [escape('--pretty=format:fugitive://'.s:repo().dir().'//%H'.path.'::'.g:fugitive_summary_format,'%')] - if empty(filter(a:000[0 : index(a:000,'--')],'v:val !~# "^-"')) - if s:buffer().commit() =~# '\x\{40\}' - let cmd += [s:buffer().commit()] - elseif s:buffer().path() =~# '^\.git/refs/\|^\.git/.*HEAD$' - let cmd += [s:buffer().path()[5:-1]] - endif - end - let cmd += map(copy(a:000),'s:sub(v:val,"^\\%(%(:\\w)*)","\\=fnamemodify(s:buffer().path(),submatch(1))")') - if path =~# '/.' - let cmd += ['--',path[1:-1]] - endif - let grepformat = &grepformat - let grepprg = &grepprg - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - let &grepprg = call(s:repo().git_command,cmd,s:repo()) - let &grepformat = '%f::%m' - exe a:cmd - finally - let &grepformat = grepformat - let &grepprg = grepprg - execute cd.'`=dir`' - endtry -endfunction - -" }}}1 -" Gedit, Gpedit, Gsplit, Gvsplit, Gtabedit, Gread {{{1 - -function! s:Edit(cmd,bang,...) abort - if a:cmd !~# 'read' - if &previewwindow && getbufvar('','fugitive_type') ==# 'index' - wincmd p - if &diff - let mywinnr = winnr() - for winnr in range(winnr('$'),1,-1) - if winnr != mywinnr && getwinvar(winnr,'&diff') - execute winnr.'wincmd w' - close - wincmd p - endif - endfor - endif - endif - endif - - if a:bang - let args = s:gsub(a:0 ? a:1 : '', '\\@<!%(\\\\)*\zs[%#]', '\=s:buffer().expand(submatch(0))') - if a:cmd =~# 'read' - let git = s:repo().git_command() - let last = line('$') - silent call s:ExecuteInTree((a:cmd ==# 'read' ? '$read' : a:cmd).'!'.git.' --no-pager '.args) - if a:cmd ==# 'read' - silent execute '1,'.last.'delete_' - endif - call fugitive#reload_status() - diffupdate - return 'redraw|echo '.string(':!'.git.' '.args) - else - let temp = tempname() - let s:temp_files[temp] = s:repo().dir() - silent execute a:cmd.' '.temp - if a:cmd =~# 'pedit' - wincmd P - endif - let echo = s:Edit('read',1,args) - silent write! - setlocal buftype=nowrite nomodified filetype=git foldmarker=<<<<<<<,>>>>>>> - if getline(1) !~# '^diff ' - setlocal readonly nomodifiable - endif - if a:cmd =~# 'pedit' - wincmd p - endif - return echo - endif - return '' - endif - - if a:0 && a:1 == '' - return '' - elseif a:0 - let file = s:buffer().expand(a:1) - elseif expand('%') ==# '' - let file = ':' - elseif s:buffer().commit() ==# '' && s:buffer().path('/') !~# '^/.git\>' - let file = s:buffer().path(':') - else - let file = s:buffer().path('/') - endif - try - let file = s:repo().translate(file) - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - if a:cmd ==# 'read' - return 'silent %delete_|read '.s:fnameescape(file).'|silent 1delete_|diffupdate|'.line('.') - else - return a:cmd.' '.s:fnameescape(file) - endif -endfunction - -function! s:EditComplete(A,L,P) abort - return s:repo().superglob(a:A) -endfunction - -function! s:EditRunComplete(A,L,P) abort - if a:L =~# '^\w\+!' - return s:GitComplete(a:A,a:L,a:P) - else - return s:repo().superglob(a:A) - endif -endfunction - -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Ge :execute s:Edit('edit<bang>',0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gedit :execute s:Edit('edit<bang>',0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gpedit :execute s:Edit('pedit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gsplit :execute s:Edit('split',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gvsplit :execute s:Edit('vsplit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gtabedit :execute s:Edit('tabedit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -count -complete=customlist,s:EditRunComplete Gread :execute s:Edit((!<count> && <line1> ? '' : <count>).'read',<bang>0,<f-args>)") - -" }}}1 -" Gwrite, Gwq {{{1 - -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gwrite :execute s:Write(<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gw :execute s:Write(<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gwq :execute s:Wq(<bang>0,<f-args>)") - -function! s:Write(force,...) abort - if exists('b:fugitive_commit_arguments') - return 'write|bdelete' - elseif expand('%:t') == 'COMMIT_EDITMSG' && $GIT_INDEX_FILE != '' - return 'wq' - elseif s:buffer().type() == 'index' - return 'Gcommit' - elseif s:buffer().path() ==# '' && getline(4) =~# '^+++ ' - let filename = getline(4)[6:-1] - setlocal buftype= - silent write - setlocal buftype=nowrite - if matchstr(getline(2),'index [[:xdigit:]]\+\.\.\zs[[:xdigit:]]\{7\}') ==# s:repo().rev_parse(':0:'.filename)[0:6] - let err = s:repo().git_chomp('apply','--cached','--reverse',s:buffer().spec()) - else - let err = s:repo().git_chomp('apply','--cached',s:buffer().spec()) - endif - if err !=# '' - let v:errmsg = split(err,"\n")[0] - return 'echoerr v:errmsg' - elseif a:force - return 'bdelete' - else - return 'Gedit '.fnameescape(filename) - endif - endif - let mytab = tabpagenr() - let mybufnr = bufnr('') - let path = a:0 ? a:1 : s:buffer().path() - if path =~# '^:\d\>' - return 'write'.(a:force ? '! ' : ' ').s:fnameescape(s:repo().translate(s:buffer().expand(path))) - endif - let always_permitted = (s:buffer().path() ==# path && s:buffer().commit() =~# '^0\=$') - if !always_permitted && !a:force && s:repo().git_chomp_in_tree('diff','--name-status','HEAD','--',path) . s:repo().git_chomp_in_tree('ls-files','--others','--',path) !=# '' - let v:errmsg = 'fugitive: file has uncommitted changes (use ! to override)' - return 'echoerr v:errmsg' - endif - let file = s:repo().translate(path) - let treebufnr = 0 - for nr in range(1,bufnr('$')) - if fnamemodify(bufname(nr),':p') ==# file - let treebufnr = nr - endif - endfor - - if treebufnr > 0 && treebufnr != bufnr('') - let temp = tempname() - silent execute '%write '.temp - for tab in [mytab] + range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - if tabpagebuflist(tab)[winnr-1] == treebufnr - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - let lnum = line('.') - let last = line('$') - silent execute '$read '.temp - silent execute '1,'.last.'delete_' - silent write! - silent execute lnum - let did = 1 - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - endif - endfor - endfor - if !exists('did') - call writefile(readfile(temp,'b'),file,'b') - endif - else - execute 'write! '.s:fnameescape(s:repo().translate(path)) - endif - - if a:force - let error = s:repo().git_chomp_in_tree('add', '--force', file) - else - let error = s:repo().git_chomp_in_tree('add', file) - endif - if v:shell_error - let v:errmsg = 'fugitive: '.error - return 'echoerr v:errmsg' - endif - if s:buffer().path() ==# path && s:buffer().commit() =~# '^\d$' - set nomodified - endif - - let one = s:repo().translate(':1:'.path) - let two = s:repo().translate(':2:'.path) - let three = s:repo().translate(':3:'.path) - for nr in range(1,bufnr('$')) - if bufloaded(nr) && !getbufvar(nr,'&modified') && (bufname(nr) == one || bufname(nr) == two || bufname(nr) == three) - execute nr.'bdelete' - endif - endfor - - unlet! restorewinnr - let zero = s:repo().translate(':0:'.path) - for tab in range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - let bufnr = tabpagebuflist(tab)[winnr-1] - let bufname = bufname(bufnr) - if bufname ==# zero && bufnr != mybufnr - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - let lnum = line('.') - let last = line('$') - silent $read `=file` - silent execute '1,'.last.'delete_' - silent execute lnum - set nomodified - diffupdate - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - break - endif - endfor - endfor - call fugitive#reload_status() - return 'checktime' -endfunction - -function! s:Wq(force,...) abort - let bang = a:force ? '!' : '' - if exists('b:fugitive_commit_arguments') - return 'wq'.bang - endif - let result = call(s:function('s:Write'),[a:force]+a:000) - if result =~# '^\%(write\|wq\|echoerr\)' - return s:sub(result,'^write','wq') - else - return result.'|quit'.bang - endif -endfunction - -" }}}1 -" Gdiff {{{1 - -call s:command("-bang -bar -nargs=? -complete=customlist,s:EditComplete Gdiff :execute s:Diff(<bang>0,<f-args>)") -call s:command("-bar -nargs=? -complete=customlist,s:EditComplete Gvdiff :execute s:Diff(0,<f-args>)") -call s:command("-bar -nargs=? -complete=customlist,s:EditComplete Gsdiff :execute s:Diff(1,<f-args>)") - -augroup fugitive_diff - autocmd! - autocmd BufWinLeave * if s:diff_window_count() == 2 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff_all(getbufvar(+expand('<abuf>'), 'git_dir')) | endif - autocmd BufWinEnter * if s:diff_window_count() == 1 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff() | endif -augroup END - -function! s:diff_window_count() - let c = 0 - for nr in range(1,winnr('$')) - let c += getwinvar(nr,'&diff') - endfor - return c -endfunction - -function! s:diffthis() - if !&diff - let w:fugitive_diff_restore = 'setlocal nodiff noscrollbind' - let w:fugitive_diff_restore .= ' scrollopt=' . &l:scrollopt - let w:fugitive_diff_restore .= &l:wrap ? ' wrap' : ' nowrap' - let w:fugitive_diff_restore .= ' foldmethod=' . &l:foldmethod - let w:fugitive_diff_restore .= ' foldcolumn=' . &l:foldcolumn - diffthis - endif -endfunction - -function! s:diffoff() - if exists('w:fugitive_diff_restore') - execute w:fugitive_diff_restore - unlet w:fugitive_diff_restore - else - diffoff - endif -endfunction - -function! s:diffoff_all(dir) - for nr in range(1,winnr('$')) - if getwinvar(nr,'&diff') - if nr != winnr() - execute nr.'wincmd w' - let restorewinnr = 1 - endif - if exists('b:git_dir') && b:git_dir ==# a:dir - call s:diffoff() - endif - if exists('restorewinnr') - wincmd p - endif - endif - endfor -endfunction - -function! s:buffer_compare_age(commit) dict abort - let scores = {':0': 1, ':1': 2, ':2': 3, ':': 4, ':3': 5} - let my_score = get(scores,':'.self.commit(),0) - let their_score = get(scores,':'.a:commit,0) - if my_score || their_score - return my_score < their_score ? -1 : my_score != their_score - elseif self.commit() ==# a:commit - return 0 - endif - let base = self.repo().git_chomp('merge-base',self.commit(),a:commit) - if base ==# self.commit() - return -1 - elseif base ==# a:commit - return 1 - endif - let my_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',self.commit()) - let their_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',a:commit) - return my_time < their_time ? -1 : my_time != their_time -endfunction - -call s:add_methods('buffer',['compare_age']) - -function! s:Diff(bang,...) abort - let split = a:bang ? 'split' : 'vsplit' - if exists(':DiffGitCached') - return 'DiffGitCached' - elseif (!a:0 || a:1 == ':') && s:buffer().commit() =~# '^[0-1]\=$' && s:repo().git_chomp_in_tree('ls-files', '--unmerged', '--', s:buffer().path()) !=# '' - let nr = bufnr('') - execute 'leftabove '.split.' `=fugitive#buffer().repo().translate(s:buffer().expand('':2''))`' - execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>' - call s:diffthis() - wincmd p - execute 'rightbelow '.split.' `=fugitive#buffer().repo().translate(s:buffer().expand('':3''))`' - execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>' - call s:diffthis() - wincmd p - call s:diffthis() - return '' - elseif a:0 - if a:1 ==# '' - return '' - elseif a:1 ==# '/' - let file = s:buffer().path('/') - elseif a:1 ==# ':' - let file = s:buffer().path(':0:') - elseif a:1 =~# '^:/.' - try - let file = s:repo().rev_parse(a:1).s:buffer().path(':') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - else - let file = s:buffer().expand(a:1) - endif - if file !~# ':' && file !~# '^/' && s:repo().git_chomp('cat-file','-t',file) =~# '^\%(tag\|commit\)$' - let file = file.s:buffer().path(':') - endif - else - let file = s:buffer().path(s:buffer().commit() == '' ? ':0:' : '/') - endif - try - let spec = s:repo().translate(file) - let commit = matchstr(spec,'\C[^:/]//\zs\x\+') - if s:buffer().compare_age(commit) < 0 - execute 'rightbelow '.split.' `=spec`' - else - execute 'leftabove '.split.' `=spec`' - endif - call s:diffthis() - wincmd p - call s:diffthis() - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -" }}}1 -" Gmove, Gremove {{{1 - -function! s:Move(force,destination) - if a:destination =~# '^/' - let destination = a:destination[1:-1] - else - let destination = fnamemodify(s:sub(a:destination,'[%#]%(:\w)*','\=expand(submatch(0))'),':p') - if destination[0:strlen(s:repo().tree())] ==# s:repo().tree('') - let destination = destination[strlen(s:repo().tree('')):-1] - endif - endif - if isdirectory(s:buffer().name()) - " Work around Vim parser idiosyncrasy - let discarded = s:buffer().setvar('&swapfile',0) - endif - let message = call(s:repo().git_chomp_in_tree,['mv']+(a:force ? ['-f'] : [])+['--', s:buffer().path(), destination], s:repo()) - if v:shell_error - let v:errmsg = 'fugitive: '.message - return 'echoerr v:errmsg' - endif - let destination = s:repo().tree(destination) - if isdirectory(destination) - let destination = fnamemodify(s:sub(destination,'/$','').'/'.expand('%:t'),':.') - endif - call fugitive#reload_status() - if s:buffer().commit() == '' - if isdirectory(destination) - return 'edit '.s:fnameescape(destination) - else - return 'saveas! '.s:fnameescape(destination) - endif - else - return 'file '.s:fnameescape(s:repo().translate(':0:'.destination) - endif -endfunction - -function! s:MoveComplete(A,L,P) - if a:A =~ '^/' - return s:repo().superglob(a:A) - else - let matches = split(glob(a:A.'*'),"\n") - call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val') - return matches - endif -endfunction - -function! s:Remove(force) - if s:buffer().commit() ==# '' - let cmd = ['rm'] - elseif s:buffer().commit() ==# '0' - let cmd = ['rm','--cached'] - else - let v:errmsg = 'fugitive: rm not supported here' - return 'echoerr v:errmsg' - endif - if a:force - let cmd += ['--force'] - endif - let message = call(s:repo().git_chomp_in_tree,cmd+['--',s:buffer().path()],s:repo()) - if v:shell_error - let v:errmsg = 'fugitive: '.s:sub(message,'error:.*\zs\n\(.*-f.*',' (add ! to force)') - return 'echoerr '.string(v:errmsg) - else - call fugitive#reload_status() - return 'bdelete'.(a:force ? '!' : '') - endif -endfunction - -augroup fugitive_remove - autocmd! - autocmd User Fugitive if s:buffer().commit() =~# '^0\=$' | - \ exe "command! -buffer -bar -bang -nargs=1 -complete=customlist,s:MoveComplete Gmove :execute s:Move(<bang>0,<q-args>)" | - \ exe "command! -buffer -bar -bang Gremove :execute s:Remove(<bang>0)" | - \ endif -augroup END - -" }}}1 -" Gblame {{{1 - -augroup fugitive_blame - autocmd! - autocmd BufReadPost *.fugitiveblame setfiletype fugitiveblame - autocmd FileType fugitiveblame setlocal nomodeline | if exists('b:git_dir') | let &l:keywordprg = s:repo().keywordprg() | endif - autocmd Syntax fugitiveblame call s:BlameSyntax() - autocmd User Fugitive if s:buffer().type('file', 'blob') | exe "command! -buffer -bar -bang -range=0 -nargs=* Gblame :execute s:Blame(<bang>0,<line1>,<line2>,<count>,[<f-args>])" | endif -augroup END - -function! s:Blame(bang,line1,line2,count,args) abort - try - if s:buffer().path() == '' - call s:throw('file or blob required') - endif - if filter(copy(a:args),'v:val !~# "^\\%(--root\|--show-name\\|-\\=\\%([ltwfs]\\|[MC]\\d*\\)\\+\\)$"') != [] - call s:throw('unsupported option') - endif - call map(a:args,'s:sub(v:val,"^\\ze[^-]","-")') - let cmd = ['--no-pager', 'blame', '--show-number'] + a:args - if s:buffer().commit() =~# '\D\|..' - let cmd += [s:buffer().commit()] - else - let cmd += ['--contents', '-'] - endif - let basecmd = escape(call(s:repo().git_command,cmd+['--',s:buffer().path()],s:repo()),'!') - try - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - if !s:repo().bare() - let dir = getcwd() - execute cd.'`=s:repo().tree()`' - endif - if a:count - execute 'write !'.substitute(basecmd,' blame ',' blame -L '.a:line1.','.a:line2.' ','g') - else - let error = tempname() - let temp = error.'.fugitiveblame' - if &shell =~# 'csh' - silent! execute '%write !('.basecmd.' > '.temp.') >& '.error - else - silent! execute '%write !'.basecmd.' > '.temp.' 2> '.error - endif - if exists('l:dir') - execute cd.'`=dir`' - unlet dir - endif - if v:shell_error - call s:throw(join(readfile(error),"\n")) - endif - let bufnr = bufnr('') - let restore = 'call setwinvar(bufwinnr('.bufnr.'),"&scrollbind",0)' - if &l:wrap - let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&wrap",1)' - endif - if &l:foldenable - let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&foldenable",1)' - endif - let winnr = winnr() - windo set noscrollbind - exe winnr.'wincmd w' - setlocal scrollbind nowrap nofoldenable - let top = line('w0') + &scrolloff - let current = line('.') - let s:temp_files[temp] = s:repo().dir() - exe 'leftabove vsplit '.temp - let b:fugitive_blamed_bufnr = bufnr - let w:fugitive_leave = restore - let b:fugitive_blame_arguments = join(a:args,' ') - execute top - normal! zt - execute current - execute "vertical resize ".(match(getline('.'),'\s\+\d\+)')+1) - setlocal nomodified nomodifiable nonumber scrollbind nowrap foldcolumn=0 nofoldenable filetype=fugitiveblame - if exists('+relativenumber') - setlocal norelativenumber - endif - nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>BlameJump('')<CR> - nnoremap <buffer> <silent> P :<C-U>exe <SID>BlameJump('^'.v:count1)<CR> - nnoremap <buffer> <silent> ~ :<C-U>exe <SID>BlameJump('~'.v:count1)<CR> - nnoremap <buffer> <silent> o :<C-U>exe <SID>Edit((&splitbelow ? "botright" : "topleft")." split", 0, matchstr(getline('.'),'\x\+'))<CR> - nnoremap <buffer> <silent> O :<C-U>exe <SID>Edit("tabedit", 0, matchstr(getline('.'),'\x\+'))<CR> - syncbind - endif - finally - if exists('l:dir') - execute cd.'`=dir`' - endif - endtry - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BlameJump(suffix) abort - let commit = matchstr(getline('.'),'^\^\=\zs\x\+') - if commit =~# '^0\+$' - let commit = ':0' - endif - let lnum = matchstr(getline('.'),'\d\+\ze\s\+[([:digit:]]') - let path = matchstr(getline('.'),'^\^\=\zs\x\+\s\+\zs.\{-\}\ze\s*\d\+ ') - if path ==# '' - let path = s:buffer(b:fugitive_blamed_bufnr).path() - endif - let args = b:fugitive_blame_arguments - let offset = line('.') - line('w0') - let bufnr = bufnr('%') - let winnr = bufwinnr(b:fugitive_blamed_bufnr) - if winnr > 0 - exe winnr.'wincmd w' - endif - execute s:Edit('edit', 0, commit.a:suffix.':'.path) - if winnr > 0 - exe bufnr.'bdelete' - endif - execute 'Gblame '.args - execute lnum - let delta = line('.') - line('w0') - offset - if delta > 0 - execute 'norm! 'delta."\<C-E>" - elseif delta < 0 - execute 'norm! '(-delta)."\<C-Y>" - endif - syncbind - return '' -endfunction - -function! s:BlameSyntax() abort - let b:current_syntax = 'fugitiveblame' - syn match FugitiveblameBoundary "^\^" - syn match FugitiveblameBlank "^\s\+\s\@=" nextgroup=FugitiveblameAnnotation,fugitiveblameOriginalFile,FugitiveblameOriginalLineNumber skipwhite - syn match FugitiveblameHash "\%(^\^\=\)\@<=\x\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite - syn match FugitiveblameUncommitted "\%(^\^\=\)\@<=0\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite - syn region FugitiveblameAnnotation matchgroup=FugitiveblameDelimiter start="(" end="\%( \d\+\)\@<=)" contained keepend oneline - syn match FugitiveblameTime "[0-9:/+-][0-9:/+ -]*[0-9:/+-]\%( \+\d\+)\)\@=" contained containedin=FugitiveblameAnnotation - syn match FugitiveblameLineNumber " \@<=\d\+)\@=" contained containedin=FugitiveblameAnnotation - syn match FugitiveblameOriginalFile " \%(\f\+\D\@<=\|\D\@=\f\+\)\%(\%(\s\+\d\+\)\=\s\%((\|\s*\d\+)\)\)\@=" contained nextgroup=FugitiveblameOriginalLineNumber,FugitiveblameAnnotation skipwhite - syn match FugitiveblameOriginalLineNumber " \@<=\d\+\%(\s(\)\@=" contained nextgroup=FugitiveblameAnnotation skipwhite - syn match FugitiveblameOriginalLineNumber " \@<=\d\+\%(\s\+\d\+)\)\@=" contained nextgroup=FugitiveblameShort skipwhite - syn match FugitiveblameShort "\d\+)" contained contains=FugitiveblameLineNumber - syn match FugitiveblameNotCommittedYet "(\@<=Not Committed Yet\>" contained containedin=FugitiveblameAnnotation - hi def link FugitiveblameBoundary Keyword - hi def link FugitiveblameHash Identifier - hi def link FugitiveblameUncommitted Function - hi def link FugitiveblameTime PreProc - hi def link FugitiveblameLineNumber Number - hi def link FugitiveblameOriginalFile String - hi def link FugitiveblameOriginalLineNumber Float - hi def link FugitiveblameShort FugitiveblameDelimiter - hi def link FugitiveblameDelimiter Delimiter - hi def link FugitiveblameNotCommittedYet Comment -endfunction - -" }}}1 -" Gbrowse {{{1 - -call s:command("-bar -bang -count=0 -nargs=? -complete=customlist,s:EditComplete Gbrowse :execute s:Browse(<bang>0,<line1>,<count>,<f-args>)") - -function! s:Browse(bang,line1,count,...) abort - try - let rev = a:0 ? substitute(a:1,'@[[:alnum:]_-]*\%(://.\{-\}\)\=$','','') : '' - if rev ==# '' - let expanded = s:buffer().rev() - elseif rev ==# ':' - let expanded = s:buffer().path('/') - else - let expanded = s:buffer().expand(rev) - endif - let full = s:repo().translate(expanded) - let commit = '' - if full =~# '^fugitive://' - let commit = matchstr(full,'://.*//\zs\w\+') - let path = matchstr(full,'://.*//\w\+\zs/.*') - if commit =~ '..' - let type = s:repo().git_chomp('cat-file','-t',commit.s:sub(path,'^/',':')) - else - let type = 'blob' - endif - let path = path[1:-1] - elseif s:repo().bare() - let path = '.git/' . full[strlen(s:repo().dir())+1:-1] - let type = '' - else - let path = full[strlen(s:repo().tree())+1:-1] - if path =~# '^\.git/' - let type = '' - elseif isdirectory(full) - let type = 'tree' - else - let type = 'blob' - endif - endif - if path =~# '^\.git/.*HEAD' && filereadable(s:repo().dir(path[5:-1])) - let body = readfile(s:repo().dir(path[5:-1]))[0] - if body =~# '^\x\{40\}$' - let commit = body - let type = 'commit' - let path = '' - elseif body =~# '^ref: refs/' - let path = '.git/' . matchstr(body,'ref: \zs.*') - endif - endif - - if a:0 && a:1 =~# '@[[:alnum:]_-]*\%(://.\{-\}\)\=$' - let remote = matchstr(a:1,'@\zs[[:alnum:]_-]\+\%(://.\{-\}\)\=$') - elseif path =~# '^\.git/refs/remotes/.' - let remote = matchstr(path,'^\.git/refs/remotes/\zs[^/]\+') - else - let remote = 'origin' - let branch = matchstr(rev,'^[[:alnum:]/._-]\+\ze[:^~@]') - if branch ==# '' && path =~# '^\.git/refs/\w\+/' - let branch = s:sub(path,'^\.git/refs/\w+/','') - endif - if filereadable(s:repo().dir('refs/remotes/'.branch)) - let remote = matchstr(branch,'[^/]\+') - let rev = rev[strlen(remote)+1:-1] - else - if branch ==# '' - let branch = matchstr(s:repo().head_ref(),'\<refs/heads/\zs.*') - endif - if branch != '' - let remote = s:repo().git_chomp('config','branch.'.branch.'.remote') - if remote =~# '^\.\=$' - let remote = 'origin' - elseif rev[0:strlen(branch)-1] ==# branch && rev[strlen(branch)] =~# '[:^~@]' - let rev = s:repo().git_chomp('config','branch.'.branch.'.merge')[11:-1] . rev[strlen(branch):-1] - endif - endif - endif - endif - - let raw = s:repo().git_chomp('config','remote.'.remote.'.url') - if raw ==# '' - let raw = remote - endif - - let url = s:github_url(s:repo(),raw,rev,commit,path,type,a:line1,a:count) - if url == '' - let url = s:instaweb_url(s:repo(),rev,commit,path,type,a:count ? a:line1 : 0) - endif - - if url == '' - call s:throw("Instaweb failed to start and '".remote."' is not a GitHub remote") - endif - - if a:bang - let @* = url - return 'echomsg '.string(url) - else - return 'echomsg '.string(url).'|call fugitive#buffer().repo().git_chomp("web--browse",'.string(url).')' - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:github_url(repo,url,rev,commit,path,type,line1,line2) abort - let path = a:path - let repo_path = matchstr(a:url,'^\%(https\=://\|git://\|git@\)github\.com[/:]\zs.\{-\}\ze\%(\.git\)\=$') - if repo_path ==# '' - return '' - endif - let root = 'https://github.com/' . repo_path - if path =~# '^\.git/refs/heads/' - let branch = a:repo.git_chomp('config','branch.'.path[16:-1].'.merge')[11:-1] - if branch ==# '' - return root . '/commits/' . path[16:-1] - else - return root . '/commits/' . branch - endif - elseif path =~# '^\.git/refs/.' - return root . '/commits/' . matchstr(path,'[^/]\+$') - elseif path =~# '.git/\%(config$\|hooks\>\)' - return root . '/admin' - elseif path =~# '^\.git\>' - return root - endif - if a:rev =~# '^[[:alnum:]._-]\+:' - let commit = matchstr(a:rev,'^[^:]*') - elseif a:commit =~# '^\d\=$' - let local = matchstr(a:repo.head_ref(),'\<refs/heads/\zs.*') - let commit = a:repo.git_chomp('config','branch.'.local.'.merge')[11:-1] - if commit ==# '' - let commit = local - endif - else - let commit = a:commit - endif - if a:type == 'tree' - let url = s:sub(root . '/tree/' . commit . '/' . path,'/$','') - elseif a:type == 'blob' - let url = root . '/blob/' . commit . '/' . path - if a:line2 && a:line1 == a:line2 - let url .= '#L' . a:line1 - elseif a:line2 - let url .= '#L' . a:line1 . '-' . a:line2 - endif - elseif a:type == 'tag' - let commit = matchstr(getline(3),'^tag \zs.*') - let url = root . '/tree/' . commit - else - let url = root . '/commit/' . commit - endif - return url -endfunction - -function! s:instaweb_url(repo,rev,commit,path,type,...) abort - let output = a:repo.git_chomp('instaweb','-b','unknown') - if output =~# 'http://' - let root = matchstr(output,'http://.*').'/?p='.fnamemodify(a:repo.dir(),':t') - else - return '' - endif - if a:path =~# '^\.git/refs/.' - return root . ';a=shortlog;h=' . matchstr(a:path,'^\.git/\zs.*') - elseif a:path =~# '^\.git\>' - return root - endif - let url = root - if a:commit =~# '^\x\{40\}$' - if a:type ==# 'commit' - let url .= ';a=commit' - endif - let url .= ';h=' . a:repo.rev_parse(a:commit . (a:path == '' ? '' : ':' . a:path)) - else - if a:type ==# 'blob' - let tmp = tempname() - silent execute 'write !'.a:repo.git_command('hash-object','-w','--stdin').' > '.tmp - let url .= ';h=' . readfile(tmp)[0] - else - try - let url .= ';h=' . a:repo.rev_parse((a:commit == '' ? 'HEAD' : ':' . a:commit) . ':' . a:path) - catch /^fugitive:/ - call s:throw('fugitive: cannot browse uncommitted file') - endtry - endif - let root .= ';hb=' . matchstr(a:repo.head_ref(),'[^ ]\+$') - endif - if a:path !=# '' - let url .= ';f=' . a:path - endif - if a:0 && a:1 - let url .= '#l' . a:1 - endif - return url -endfunction - -" }}}1 -" File access {{{1 - -function! s:ReplaceCmd(cmd,...) abort - let fn = bufname('') - let tmp = tempname() - let prefix = '' - try - if a:0 && a:1 != '' - if &shell =~# 'cmd' - let old_index = $GIT_INDEX_FILE - let $GIT_INDEX_FILE = a:1 - else - let prefix = 'env GIT_INDEX_FILE='.s:shellesc(a:1).' ' - endif - endif - if &shell =~# 'cmd' - call system('cmd /c "'.prefix.a:cmd.' > '.tmp.'"') - else - call system(' ('.prefix.a:cmd.' > '.tmp.') ') - endif - finally - if exists('old_index') - let $GIT_INDEX_FILE = old_index - endif - endtry - silent exe 'keepalt file '.tmp - silent edit! - silent exe 'keepalt file '.s:fnameescape(fn) - call delete(tmp) - if bufname('$') == tmp - silent execute 'bwipeout '.bufnr('$') - endif - silent exe 'doau BufReadPost '.s:fnameescape(fn) -endfunction - -function! s:BufReadIndex() - if !exists('b:fugitive_display_format') - let b:fugitive_display_format = filereadable(expand('%').'.lock') - endif - let b:fugitive_display_format = b:fugitive_display_format % 2 - let b:fugitive_type = 'index' - try - let b:git_dir = s:repo().dir() - setlocal noro ma - if fnamemodify($GIT_INDEX_FILE !=# '' ? $GIT_INDEX_FILE : b:git_dir . '/index', ':p') ==# expand('%:p') - let index = '' - else - let index = expand('%:p') - endif - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('ls-files','--stage'),index) - set ft=git nospell - else - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - call s:ReplaceCmd(s:repo().git_command('status'),index) - finally - execute cd.'`=dir`' - endtry - set ft=gitcommit - endif - setlocal ro noma nomod nomodeline bufhidden=wipe - call s:JumpInit() - nunmap <buffer> P - nunmap <buffer> ~ - nnoremap <buffer> <silent> <C-N> :call search('^#\t.*','W')<Bar>.<CR> - nnoremap <buffer> <silent> <C-P> :call search('^#\t.*','Wbe')<Bar>.<CR> - nnoremap <buffer> <silent> - :<C-U>execute <SID>StageToggle(line('.'),line('.')+v:count1-1)<CR> - xnoremap <buffer> <silent> - :<C-U>execute <SID>StageToggle(line("'<"),line("'>"))<CR> - nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += 1<Bar>exe <SID>BufReadIndex()<CR> - nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= 1<Bar>exe <SID>BufReadIndex()<CR> - nnoremap <buffer> <silent> C :<C-U>Gcommit<CR> - nnoremap <buffer> <silent> cA :<C-U>Gcommit --amend --reuse-message=HEAD<CR> - nnoremap <buffer> <silent> ca :<C-U>Gcommit --amend<CR> - nnoremap <buffer> <silent> cc :<C-U>Gcommit<CR> - nnoremap <buffer> <silent> D :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> dd :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> dh :<C-U>execute <SID>StageDiff('Gsdiff')<CR> - nnoremap <buffer> <silent> ds :<C-U>execute <SID>StageDiff('Gsdiff')<CR> - nnoremap <buffer> <silent> dp :<C-U>execute <SID>StageDiffEdit()<CR> - nnoremap <buffer> <silent> dv :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line('.'),line('.')+v:count1-1)<CR> - xnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line("'<"),line("'>"))<CR> - nnoremap <buffer> <silent> q :<C-U>if bufnr('$') == 1<Bar>quit<Bar>else<Bar>bdelete<Bar>endif<CR> - nnoremap <buffer> <silent> R :<C-U>edit<CR> - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:FileRead() - try - let repo = s:repo(s:ExtractGitDir(expand('<amatch>'))) - let path = s:sub(s:sub(matchstr(expand('<amatch>'),'fugitive://.\{-\}//\zs.*'),'/',':'),'^\d:',':&') - let hash = repo.rev_parse(path) - if path =~ '^:' - let type = 'blob' - else - let type = repo.git_chomp('cat-file','-t',hash) - endif - " TODO: use count, if possible - return "read !".escape(repo.git_command('cat-file',type,hash),'%#\') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BufReadIndexFile() - try - let b:fugitive_type = 'blob' - let b:git_dir = s:repo().dir() - call s:ReplaceCmd(s:repo().git_command('cat-file','blob',s:buffer().sha1())) - if &bufhidden ==# '' - setlocal bufhidden=delete - endif - return '' - catch /^fugitive: rev-parse/ - silent exe 'doau BufNewFile '.s:fnameescape(bufname('')) - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BufWriteIndexFile() - let tmp = tempname() - try - let path = matchstr(expand('<amatch>'),'//\d/\zs.*') - let stage = matchstr(expand('<amatch>'),'//\zs\d') - silent execute 'write !'.s:repo().git_command('hash-object','-w','--stdin').' > '.tmp - let sha1 = readfile(tmp)[0] - let old_mode = matchstr(s:repo().git_chomp('ls-files','--stage',path),'^\d\+') - if old_mode == '' - let old_mode = executable(s:repo().tree(path)) ? '100755' : '100644' - endif - let info = old_mode.' '.sha1.' '.stage."\t".path - call writefile([info],tmp) - if has('win32') - let error = system('type '.tmp.'|'.s:repo().git_command('update-index','--index-info')) - else - let error = system(s:repo().git_command('update-index','--index-info').' < '.tmp) - endif - if v:shell_error == 0 - setlocal nomodified - silent execute 'doautocmd BufWritePost '.s:fnameescape(expand('%:p')) - call fugitive#reload_status() - return '' - else - return 'echoerr '.string('fugitive: '.error) - endif - finally - call delete(tmp) - endtry -endfunction - -function! s:BufReadObject() - try - setlocal noro ma - let b:git_dir = s:repo().dir() - let hash = s:buffer().sha1() - if !exists("b:fugitive_type") - let b:fugitive_type = s:repo().git_chomp('cat-file','-t',hash) - endif - if b:fugitive_type !~# '^\%(tag\|commit\|tree\|blob\)$' - return "echoerr 'fugitive: unrecognized git type'" - endif - let firstline = getline('.') - if !exists('b:fugitive_display_format') && b:fugitive_type != 'blob' - let b:fugitive_display_format = +getbufvar('#','fugitive_display_format') - endif - - let pos = getpos('.') - silent %delete - setlocal endofline - - if b:fugitive_type == 'tree' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('ls-tree',hash)) - else - call s:ReplaceCmd(s:repo().git_command('show','--no-color',hash)) - endif - elseif b:fugitive_type == 'tag' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - else - call s:ReplaceCmd(s:repo().git_command('cat-file','-p',hash)) - endif - elseif b:fugitive_type == 'commit' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - else - call s:ReplaceCmd(s:repo().git_command('show','--no-color','--pretty=format:tree %T%nparent %P%nauthor %an <%ae> %ad%ncommitter %cn <%ce> %cd%nencoding %e%n%n%s%n%n%b',hash)) - call search('^parent ') - if getline('.') ==# 'parent ' - silent delete_ - else - silent s/\%(^parent\)\@<! /\rparent /ge - endif - if search('^encoding \%(<unknown>\)\=$','W',line('.')+3) - silent delete_ - end - 1 - endif - elseif b:fugitive_type ==# 'blob' - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - endif - call setpos('.',pos) - setlocal ro noma nomod nomodeline - if &bufhidden ==# '' - setlocal bufhidden=delete - endif - if b:fugitive_type !=# 'blob' - set filetype=git - nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += v:count1<Bar>exe <SID>BufReadObject()<CR> - nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= v:count1<Bar>exe <SID>BufReadObject()<CR> - else - call s:JumpInit() - endif - - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -augroup fugitive_files - autocmd! - autocmd BufReadCmd *.git/index exe s:BufReadIndex() - autocmd BufReadCmd *.git/*index*.lock exe s:BufReadIndex() - autocmd FileReadCmd fugitive://**//[0-3]/** exe s:FileRead() - autocmd BufReadCmd fugitive://**//[0-3]/** exe s:BufReadIndexFile() - autocmd BufWriteCmd fugitive://**//[0-3]/** exe s:BufWriteIndexFile() - autocmd BufReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:BufReadObject() - autocmd FileReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:FileRead() - autocmd FileType git call s:JumpInit() -augroup END - -" }}}1 -" Temp files {{{1 - -let s:temp_files = {} - -augroup fugitive_temp - autocmd! - autocmd BufNewFile,BufReadPost * - \ if has_key(s:temp_files,expand('<amatch>:p')) | - \ let b:git_dir = s:temp_files[expand('<amatch>:p')] | - \ let b:git_type = 'temp' | - \ call s:Detect(expand('<amatch>:p')) | - \ setlocal bufhidden=delete | - \ nnoremap <buffer> <silent> q :<C-U>bdelete<CR> | - \ endif -augroup END - -" }}}1 -" Go to file {{{1 - -function! s:JumpInit() abort - nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>GF("edit")<CR> - if !&modifiable - nnoremap <buffer> <silent> o :<C-U>exe <SID>GF("split")<CR> - nnoremap <buffer> <silent> O :<C-U>exe <SID>GF("tabedit")<CR> - nnoremap <buffer> <silent> P :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'^'.v:count1.<SID>buffer().path(':'))<CR> - nnoremap <buffer> <silent> ~ :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'~'.v:count1.<SID>buffer().path(':'))<CR> - nnoremap <buffer> <silent> C :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cc :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> co :<C-U>exe <SID>Edit('split',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cO :<C-U>exe <SID>Edit('tabedit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cp :<C-U>exe <SID>Edit('pedit',0,<SID>buffer().containing_commit())<CR> - endif -endfunction - -function! s:GF(mode) abort - try - let buffer = s:buffer() - let myhash = buffer.sha1() - if myhash ==# '' && getline(1) =~# '^\%(commit\|tag\) \w' - let myhash = matchstr(getline(1),'^\w\+ \zs\S\+') - endif - - if buffer.type('tree') - let showtree = (getline(1) =~# '^tree ' && getline(2) == "") - if showtree && line('.') == 1 - return "" - elseif showtree && line('.') > 2 - return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(getline('.'),'/$','')) - elseif getline('.') =~# '^\d\{6\} \l\{3,8\} \x\{40\}\t' - return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(matchstr(getline('.'),'\t\zs.*'),'/$','')) - endif - - elseif buffer.type('blob') - let ref = expand("<cfile>") - try - let sha1 = buffer.repo().rev_parse(ref) - catch /^fugitive:/ - endtry - if exists('sha1') - return s:Edit(a:mode,0,ref) - endif - - else - - " Index - if getline('.') =~# '^\d\{6\} \x\{40\} \d\t' - let ref = matchstr(getline('.'),'\x\{40\}') - let file = ':'.s:sub(matchstr(getline('.'),'\d\t.*'),'\t',':') - return s:Edit(a:mode,0,file) - - elseif getline('.') =~# '^#\trenamed:.* -> ' - let file = '/'.matchstr(getline('.'),' -> \zs.*') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# '^#\t[[:alpha:] ]\+: *.' - let file = '/'.matchstr(getline('.'),': *\zs.\{-\}\ze\%( (new commits)\)\=$') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# '^#\t.' - let file = '/'.matchstr(getline('.'),'#\t\zs.*') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# ': needs merge$' - let file = '/'.matchstr(getline('.'),'.*\ze: needs merge$') - return s:Edit(a:mode,0,file).'|Gdiff' - - elseif getline('.') ==# '# Not currently on any branch.' - return s:Edit(a:mode,0,'HEAD') - elseif getline('.') =~# '^# On branch ' - let file = 'refs/heads/'.getline('.')[12:] - return s:Edit(a:mode,0,file) - elseif getline('.') =~# "^# Your branch .*'" - let file = matchstr(getline('.'),"'\\zs\\S\\+\\ze'") - return s:Edit(a:mode,0,file) - endif - - let showtree = (getline(1) =~# '^tree ' && getline(2) == "") - - if getline('.') =~# '^ref: ' - let ref = strpart(getline('.'),5) - - elseif getline('.') =~# '^commit \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~# '^parent \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - let line = line('.') - let parent = 0 - while getline(line) =~# '^parent ' - let parent += 1 - let line -= 1 - endwhile - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~ '^tree \x\{40\}$' - let ref = matchstr(getline('.'),'\x\{40\}') - if s:repo().rev_parse(myhash.':') == ref - let ref = myhash.':' - endif - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~# '^object \x\{40\}$' && getline(line('.')+1) =~ '^type \%(commit\|tree\|blob\)$' - let ref = matchstr(getline('.'),'\x\{40\}') - let type = matchstr(getline(line('.')+1),'type \zs.*') - - elseif getline('.') =~# '^\l\{3,8\} '.myhash.'$' - return '' - - elseif getline('.') =~# '^\l\{3,8\} \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - echoerr "warning: unknown context ".matchstr(getline('.'),'^\l*') - - elseif getline('.') =~# '^[+-]\{3\} [ab/]' - let ref = getline('.')[4:] - - elseif getline('.') =~# '^rename from ' - let ref = 'a/'.getline('.')[12:] - elseif getline('.') =~# '^rename to ' - let ref = 'b/'.getline('.')[10:] - - elseif getline('.') =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)' - let dref = matchstr(getline('.'),'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)') - let ref = matchstr(getline('.'),'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)') - let dcmd = 'Gdiff' - - elseif getline('.') =~# '^index ' && getline(line('.')-1) =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)' - let line = getline(line('.')-1) - let dref = matchstr(line,'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)') - let ref = matchstr(line,'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)') - let dcmd = 'Gdiff!' - - elseif line('$') == 1 && getline('.') =~ '^\x\{40\}$' - let ref = getline('.') - else - let ref = '' - endif - - if myhash ==# '' - let ref = s:sub(ref,'^a/','HEAD:') - let ref = s:sub(ref,'^b/',':0:') - if exists('dref') - let dref = s:sub(dref,'^a/','HEAD:') - endif - else - let ref = s:sub(ref,'^a/',myhash.'^:') - let ref = s:sub(ref,'^b/',myhash.':') - if exists('dref') - let dref = s:sub(dref,'^a/',myhash.'^:') - endif - endif - - if ref ==# '/dev/null' - " Empty blob - let ref = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391' - endif - - if exists('dref') - return s:Edit(a:mode,0,ref) . '|'.dcmd.' '.s:fnameescape(dref) - elseif ref != "" - return s:Edit(a:mode,0,ref) - endif - - endif - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -" }}}1 -" Statusline {{{1 - -function! s:repo_head_ref() dict abort - return readfile(s:repo().dir('HEAD'))[0] -endfunction - -call s:add_methods('repo',['head_ref']) - -function! fugitive#statusline(...) - if !exists('b:git_dir') - return '' - endif - let status = '' - if s:buffer().commit() != '' - let status .= ':' . s:buffer().commit()[0:7] - endif - let head = s:repo().head_ref() - if head =~# '^ref: ' - let status .= s:sub(head,'^ref: %(refs/%(heads/|remotes/|tags/)=)=','(').')' - elseif head =~# '^\x\{40\}$' - let status .= '('.head[0:7].')' - endif - if &statusline =~# '%[MRHWY]' && &statusline !~# '%[mrhwy]' - return ',GIT'.status - else - return '[Git'.status.']' - endif -endfunction - -" }}}1 - -" vim:set ft=vim ts=8 sw=2 sts=2: diff --git a/vim/plugin/gist.vim b/vim/plugin/gist.vim deleted file mode 100644 index 9081d00..0000000 --- a/vim/plugin/gist.vim +++ /dev/null @@ -1,826 +0,0 @@ -"============================================================================= -" File: gist.vim -" Author: Yasuhiro Matsumoto <mattn.jp@gmail.com> -" Last Change: 20-Aug-2011. -" Version: 5.0 -" WebPage: http://github.com/mattn/gist-vim -" License: BSD -" Usage: -" -" :Gist -" post current buffer to gist, using default privicy option -" (see g:gist_private) -" -" :'<,'>Gist -" post selected text to gist., using default privicy option -" This applies to all permutations listed below (except multi) -" (see g:gist_private) -" -" :Gist -p -" create a private gist -" -" :Gist -P -" create a public gist -" (only relevant if you've set gists to be private by default) -" -" :Gist -P -" post whole text to gist as public -" This is only relevant if you've set gists to be private by default -" :Gist -a -" create a gist anonymously -" -" :Gist -m -" create a gist with all open buffers -" -" :Gist -e -" edit the gist. (you need to have opend the gist buffer first) -" you can update the gist with :w command on gist buffer -" -" :Gist -d -" delete the gist. (you need to have opend the gist buffer first) -" password authentication is needed -" -" :Gist -f -" fork the gist. (you need to have opend the gist buffer first) -" password authentication is needed -" -" :Gist -e foo.js -" edit the gist with name 'foo.js'. (you need to have opend the gist buffer first) -" -" :Gist XXXXX -" get gist XXXXX -" -" :Gist -c XXXXX -" get gist XXXXX and add to clipboard -" -" :Gist -l -" list your public gists -" -" :Gist -l mattn -" list gists from mattn -" -" :Gist -la -" list all your (public and private) gists -" -" Tips: -" * if set g:gist_clip_command, gist.vim will copy the gist code -" with option '-c'. -" -" # mac -" let g:gist_clip_command = 'pbcopy' -" -" # linux -" let g:gist_clip_command = 'xclip -selection clipboard' -" -" # others(cygwin?) -" let g:gist_clip_command = 'putclip' -" -" * if you want to detect filetype from gist's filename... -" -" # detect filetype if vim failed auto-detection. -" let g:gist_detect_filetype = 1 -" -" # detect filetype always. -" let g:gist_detect_filetype = 2 -" -" * if you want to open browser after the post... -" -" let g:gist_open_browser_after_post = 1 -" -" * if you want to change the browser... -" -" let g:gist_browser_command = 'w3m %URL%' -" -" or -" -" let g:gist_browser_command = 'opera %URL% &' -" -" on windows, should work with original setting. -" -" * if you want to show your private gists with ':Gist -l' -" -" let g:gist_show_privates = 1 -" -" * if don't you want to copy URL of the post... -" -" let g:gist_put_url_to_clipboard_after_post = 0 -" -" or if you want to copy URL and add linefeed at the last of URL, -" -" let g:gist_put_url_to_clipboard_after_post = 2 -" -" default value is 1. -" -" Thanks: -" MATSUU Takuto: -" removed carriage return -" gist_browser_command enhancement -" edit support -" -" GetLatestVimScripts: 2423 1 :AutoInstall: gist.vim -" script type: plugin - -if &cp || (exists('g:loaded_gist_vim') && g:loaded_gist_vim) - finish -endif -let g:loaded_gist_vim = 1 - -if (!exists('g:github_user') || !exists('g:github_token')) && !executable('git') - echohl ErrorMsg | echomsg "Gist: require 'git' command" | echohl None - finish -endif - -if !executable('curl') - echohl ErrorMsg | echomsg "Gist: require 'curl' command" | echohl None - finish -endif - -if !exists('g:gist_open_browser_after_post') - let g:gist_open_browser_after_post = 0 -endif - -if !exists('g:gist_put_url_to_clipboard_after_post') - let g:gist_put_url_to_clipboard_after_post = 1 -endif - -if !exists('g:gist_curl_options') - let g:gist_curl_options = "" -endif - -if !exists('g:gist_browser_command') - if has('win32') || has('win64') - let g:gist_browser_command = "!start rundll32 url.dll,FileProtocolHandler %URL%" - elseif has('mac') - let g:gist_browser_command = "open %URL%" - elseif executable('xdg-open') - let g:gist_browser_command = "xdg-open %URL%" - else - let g:gist_browser_command = "firefox %URL% &" - endif -endif - -if !exists('g:gist_detect_filetype') - let g:gist_detect_filetype = 0 -endif - -if !exists('g:gist_private') - let g:gist_private = 0 -endif - -if !exists('g:gist_show_privates') - let g:gist_show_privates = 0 -endif - -if !exists('g:gist_cookie_dir') - let g:gist_cookie_dir = substitute(expand('<sfile>:p:h'), '[/\\]plugin$', '', '').'/cookies' -endif - -function! s:nr2hex(nr) - let n = a:nr - let r = "" - while n - let r = '0123456789ABCDEF'[n % 16] . r - let n = n / 16 - endwhile - return r -endfunction - -function! s:encodeURIComponent(instr) - let instr = iconv(a:instr, &enc, "utf-8") - let len = strlen(instr) - let i = 0 - let outstr = '' - while i < len - let ch = instr[i] - if ch =~# '[0-9A-Za-z-._~!''()*]' - let outstr = outstr . ch - elseif ch == ' ' - let outstr = outstr . '+' - else - let outstr = outstr . '%' . substitute('0' . s:nr2hex(char2nr(ch)), '^.*\(..\)$', '\1', '') - endif - let i = i + 1 - endwhile - return outstr -endfunction - -" Note: A colon in the file name has side effects on Windows due to NTFS Alternate Data Streams; avoid it. -let s:bufprefix = 'gist' . (has('unix') ? ':' : '_') -function! s:GistList(user, token, gistls, page) - if a:gistls == '-all' - let url = 'https://gist.github.com/gists' - elseif g:gist_show_privates && a:gistls == a:user - let url = 'https://gist.github.com/mine' - else - let url = 'https://gist.github.com/'.a:gistls - endif - let winnum = bufwinnr(bufnr(s:bufprefix.a:gistls)) - if winnum != -1 - if winnum != bufwinnr('%') - exe winnum 'wincmd w' - endif - setlocal modifiable - else - exec 'silent split' s:bufprefix.a:gistls - endif - if a:page > 1 - let oldlines = getline(0, line('$')) - let url = url . '?page=' . a:page - endif - - setlocal foldmethod=manual - let oldlines = [] - if g:gist_show_privates - echon 'Login to gist... ' - silent %d _ - let res = s:GistGetPage(url, a:user, '', '-L') - silent put =res.content - else - silent %d _ - exec 'silent r! curl -s' g:gist_curl_options url - endif - - 1delete _ - silent! %s/>/>\r/g - silent! %s/</\r</g - silent! %g/<pre/,/<\/pre/join! - silent! %g/<span class="date"/,/<\/span/join - silent! %g/^<span class="date"/s/> */>/g - silent! %v/^\(gist:\|<pre>\|<span class="date">\)/d _ - silent! %s/<div[^>]*>/\r /g - silent! %s/<\/pre>/\r/g - silent! %g/^gist:/,/<span class="date"/join - silent! %s/<[^>]\+>//g - silent! %s/\r//g - silent! %s/ / /g - silent! %s/"/"/g - silent! %s/&/\&/g - silent! %s/>/>/g - silent! %s/</</g - silent! %s/&#\(\d\d\);/\=nr2char(submatch(1))/g - silent! %g/^gist: /s/ //g - - call append(0, oldlines) - $put='more...' - - let b:user = a:user - let b:token = a:token - let b:gistls = a:gistls - let b:page = a:page - setlocal buftype=nofile bufhidden=hide noswapfile - setlocal nomodified - syntax match SpecialKey /^gist:/he=e-1 - nnoremap <silent> <buffer> <cr> :call <SID>GistListAction()<cr> - - cal cursor(1+len(oldlines),1) - setlocal foldmethod=expr - setlocal foldexpr=getline(v:lnum)=~'^\\(gist:\\\|more\\)'?'>1':'=' - setlocal foldtext=getline(v:foldstart) -endfunction - -function! s:GistGetFileName(gistid) - let url = 'https://gist.github.com/'.a:gistid - let res = system('curl -s '.g:gist_curl_options.' '.url) - let res = substitute(res, '^.*<a href="/raw/[^"]\+/\([^"]\+\)".*$', '\1', '') - if res =~ '/' - return '' - else - return res - endif -endfunction - -function! s:GistDetectFiletype(gistid) - let url = 'https://gist.github.com/'.a:gistid - let mx = '^.*<div class=".\{-}type-\([^"]\+\)">.*$' - let res = system('curl -s '.g:gist_curl_options.' '.url) - let res = substitute(matchstr(res, mx), mx, '\1', '') - let res = substitute(res, '.*\(\.[^\.]\+\)$', '\1', '') - let res = substitute(res, '-', '', 'g') - " TODO: more filetype detection that is specified in html. - if res == 'bat' | let res = 'dosbatch' | endif - if res == 'as' | let res = 'actionscript' | endif - if res == 'bash' | let res = 'sh' | endif - if res == 'cl' | let res = 'lisp' | endif - if res == 'rb' | let res = 'ruby' | endif - if res == 'viml' | let res = 'vim' | endif - if res == 'plain' || res == 'text' | let res = '' | endif - - if res =~ '^\.' - silent! exec "doau BufRead *".res - else - silent! exec "setlocal ft=".tolower(res) - endif -endfunction - -function! s:GistWrite(fname) - if substitute(a:fname, '\\', '/', 'g') == expand("%:p:gs@\\@/@") - Gist -e - else - exe "w".(v:cmdbang ? "!" : "") fnameescape(v:cmdarg) fnameescape(a:fname) - silent! exe "file" fnameescape(a:fname) - silent! au! BufWriteCmd <buffer> - endif -endfunction - -function! s:GistGet(user, token, gistid, clipboard) - let url = 'https://raw.github.com/gist/'.a:gistid - let winnum = bufwinnr(bufnr(s:bufprefix.a:gistid)) - if winnum != -1 - if winnum != bufwinnr('%') - exe winnum 'wincmd w' - endif - setlocal modifiable - else - exec 'silent split' s:bufprefix.a:gistid - endif - filetype detect - silent %d _ - exec 'silent 0r! curl -s' g:gist_curl_options url - $delete _ - setlocal buftype=acwrite bufhidden=delete noswapfile - setlocal nomodified - doau StdinReadPost <buffer> - if (&ft == '' && g:gist_detect_filetype == 1) || g:gist_detect_filetype == 2 - call s:GistDetectFiletype(a:gistid) - endif - if a:clipboard - if exists('g:gist_clip_command') - exec 'silent w !'.g:gist_clip_command - else - %yank + - endif - endif - 1 - au! BufWriteCmd <buffer> call s:GistWrite(expand("<amatch>")) -endfunction - -function! s:GistListAction() - let line = getline('.') - let mx = '^gist:\(\w\+\).*' - if line =~# mx - let gistid = substitute(line, mx, '\1', '') - call s:GistGet(g:github_user, g:github_token, gistid, 0) - return - endif - if line =~# '^more\.\.\.$' - delete - call s:GistList(b:user, b:token, b:gistls, b:page+1) - return - endif -endfunction - -function! s:GistUpdate(user, token, content, gistid, gistnm) - if len(a:gistnm) == 0 - let name = s:GistGetFileName(a:gistid) - else - let name = a:gistnm - endif - let namemx = '^[^.]\+\(.\+\)$' - let ext = '' - if name =~ namemx - let ext = substitute(name, namemx, '\1', '') - endif - let query = [ - \ '_method=put', - \ 'file_ext[gistfile1%s]=%s', - \ 'file_name[gistfile1%s]=%s', - \ 'file_contents[gistfile1%s]=%s', - \ 'login=%s', - \ 'token=%s', - \ ] - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(ext), s:encodeURIComponent(ext), - \ s:encodeURIComponent(ext), s:encodeURIComponent(name), - \ s:encodeURIComponent(ext), s:encodeURIComponent(a:content), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) - unlet query - - let file = tempname() - call writefile([squery], file) - echon 'Updating it to gist... ' - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists/'.a:gistid - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let headers = split(res, '\(\r\?\n\|\r\n\?\)') - let location = matchstr(headers, '^Location: ') - let location = substitute(location, '^[^:]\+: ', '', '') - if len(location) > 0 && location =~ '^\(http\|https\):\/\/gist\.github\.com\/' - setlocal nomodified - redraw - echo 'Done: '.location - else - let message = matchstr(headers, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Edit failed: '.message | echohl None - endif - return location -endfunction - -function! s:GistGetPage(url, user, param, opt) - if !isdirectory(g:gist_cookie_dir) - call mkdir(g:gist_cookie_dir, 'p') - endif - let cookie_file = g:gist_cookie_dir.'/github' - - if len(a:url) == 0 - call delete(cookie_file) - return - endif - - let quote = &shellxquote == '"' ? "'" : '"' - if !filereadable(cookie_file) - let password = inputsecret('Password:') - if len(password) == 0 - echo 'Canceled' - return - endif - let url = 'https://gist.github.com/login?return_to=gist' - let res = system('curl -L -s '.g:gist_curl_options.' -c '.quote.cookie_file.quote.' '.quote.url.quote) - let token = substitute(res, '^.* name="authenticity_token" type="hidden" value="\([^"]\+\)".*$', '\1', '') - - let query = [ - \ 'authenticity_token=%s', - \ 'login=%s', - \ 'password=%s', - \ 'return_to=gist', - \ 'commit=Log+in', - \ ] - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(token), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(password)) - unlet query - - let file = tempname() - let command = 'curl -s '.g:gist_curl_options.' -i' - let command .= ' -b '.quote.cookie_file.quote - let command .= ' -c '.quote.cookie_file.quote - let command .= ' '.quote.'https://gist.github.com/session'.quote - let command .= ' -d @' . quote.file.quote - call writefile([squery], file) - let res = system(command) - call delete(file) - let res = matchstr(split(res, '\(\r\?\n\|\r\n\?\)'), '^Location: ') - let res = substitute(res, '^[^:]\+: ', '', '') - if len(res) == 0 - call delete(cookie_file) - return '' - endif - endif - let command = 'curl -s '.g:gist_curl_options.' -i '.a:opt - if len(a:param) - let command .= ' -d '.quote.a:param.quote - endif - let command .= ' -b '.quote.cookie_file.quote - let command .= ' '.quote.a:url.quote - let res = iconv(system(command), "utf-8", &encoding) - let pos = stridx(res, "\r\n\r\n") - if pos != -1 - let content = res[pos+4:] - else - let pos = stridx(res, "\n\n") - let content = res[pos+2:] - endif - return { - \ "header" : split(res[0:pos], '\r\?\n'), - \ "content" : content - \} -endfunction - -function! s:GistDelete(user, token, gistid) - echon 'Deleting gist... ' - let res = s:GistGetPage('https://gist.github.com/'.a:gistid, a:user, '', '') - if (!len(res)) - echohl ErrorMsg | echomsg 'Wrong password? no response received from github trying to delete ' . a:gistid | echohl None - return - endif - let mx = '^.* name="authenticity_token" type="hidden" value="\([^"]\+\)".*$' - let token = substitute(matchstr(res.content, mx), mx, '\1', '') - if len(token) > 0 - let res = s:GistGetPage('https://gist.github.com/delete/'.a:gistid, a:user, '_method=delete&authenticity_token='.token, '') - if len(res.content) > 0 - redraw - echo 'Done: ' - else - let message = matchstr(res.header, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Delete failed: '.message | echohl None - endif - else - echohl ErrorMsg | echomsg 'Delete failed' | echohl None - endif -endfunction - - -" GistPost function: -" Post new gist to github -" -" if there is an embedded gist url or gist id in your file, -" it will just update it. -" -- by c9s -" -" embedded gist url format: -" -" Gist: https://gist.github.com/123123 -" -" embedded gist id format: -" -" GistID: 123123 -" -function! s:GistPost(user, token, content, private) - - " find GistID: in content, then we should just update - for l in split(a:content, "\n") - if l =~ '\<GistID:' - let gistid = matchstr(l, 'GistID:\s*[0-9a-z]\+') - - if strlen(gistid) == 0 - echohl WarningMsg | echo "GistID error" | echohl None - return - endif - echo "Found GistID: " . gistid - - cal s:GistUpdate(a:user, a:token, a:content, gistid, '') - return - elseif l =~ '\<Gist:' - let gistid = matchstr(l, 'Gist:\s*https://gist.github.com/[0-9a-z]\+') - - if strlen(gistid) == 0 - echohl WarningMsg | echo "GistID error" | echohl None - return - endif - echo "Found GistID: " . gistid - - cal s:GistUpdate(a:user, a:token, a:content, gistid, '') - return - endif - endfor - - let ext = expand('%:e') - let ext = len(ext) ? '.'.ext : '' - let name = expand('%:t') - - let query = [ - \ 'file_ext[gistfile1]=%s', - \ 'file_name[gistfile1]=%s', - \ 'file_contents[gistfile1]=%s', - \ ] - - if len(a:user) > 0 && len(a:token) > 0 - call add(query, 'login=%s') - call add(query, 'token=%s') - else - call add(query, '%.0s%.0s') - endif - - if a:private - call add(query, 'action_button=private') - endif - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(ext), - \ s:encodeURIComponent(name), - \ s:encodeURIComponent(a:content), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) - unlet query - - let file = tempname() - call writefile([squery], file) - echon 'Posting it to gist... ' - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists' - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let headers = split(res, '\(\r\?\n\|\r\n\?\)') - let location = matchstr(headers, '^Location: ') - let location = substitute(location, '^[^:]\+: ', '', '') - if len(location) > 0 && location =~ '^\(http\|https\):\/\/gist\.github\.com\/' - redraw - echo 'Done: '.location - else - let message = matchstr(headers, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Post failed: '.message | echohl None - endif - return location -endfunction - -function! s:GistPostBuffers(user, token, private) - let bufnrs = range(1, bufnr("$")) - let bn = bufnr('%') - let query = [] - if len(a:user) > 0 && len(a:token) > 0 - call add(query, 'login=%s') - call add(query, 'token=%s') - else - call add(query, '%.0s%.0s') - endif - if a:private - call add(query, 'action_button=private') - endif - let squery = printf(join(query, "&"), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) . '&' - - let query = [ - \ 'file_ext[gistfile]=%s', - \ 'file_name[gistfile]=%s', - \ 'file_contents[gistfile]=%s', - \ ] - let format = join(query, "&") . '&' - - let index = 1 - for bufnr in bufnrs - if !bufexists(bufnr) || buflisted(bufnr) == 0 - continue - endif - echo "Creating gist content".index."... " - silent! exec "buffer!" bufnr - let content = join(getline(1, line('$')), "\n") - let ext = expand('%:e') - let ext = len(ext) ? '.'.ext : '' - let name = expand('%:t') - let squery .= printf(substitute(format, 'gistfile', 'gistfile'.index, 'g'), - \ s:encodeURIComponent(ext), - \ s:encodeURIComponent(name), - \ s:encodeURIComponent(content)) - let index = index + 1 - endfor - silent! exec "buffer!" bn - - let file = tempname() - call writefile([squery], file) - echo "Posting it to gist... " - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists' - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let res = matchstr(split(res, '\(\r\?\n\|\r\n\?\)'), '^Location: ') - let res = substitute(res, '^.*: ', '', '') - if len(res) > 0 && res =~ '^\(http\|https\):\/\/gist\.github\.com\/' - redraw - echo 'Done: '.res - else - echohl ErrorMsg | echomsg 'Post failed' | echohl None - endif - return res -endfunction - -function! Gist(line1, line2, ...) - if !exists('g:github_user') - let g:github_user = substitute(system('git config --global github.user'), "\n", '', '') - if strlen(g:github_user) == 0 - let g:github_user = $GITHUB_USER - end - endif - if !exists('g:github_token') - let g:github_token = substitute(system('git config --global github.token'), "\n", '', '') - if strlen(g:github_token) == 0 - let g:github_token = $GITHUB_TOKEN - end - endif - if strlen(g:github_user) == 0 || strlen(g:github_token) == 0 - echohl ErrorMsg - echomsg "You have no setting for github." - echohl WarningMsg - echo "git config --global github.user your-name" - echo "git config --global github.token your-token" - echo "or set g:github_user and g:github_token in your vimrc" - echo "or set shell env vars GITHUB_USER and GITHUB_TOKEN" - echohl None - return 0 - end - - let bufname = bufname("%") - let user = g:github_user - let token = g:github_token - let gistid = '' - let gistls = '' - let gistnm = '' - let private = g:gist_private - let multibuffer = 0 - let clipboard = 0 - let deletepost = 0 - let editpost = 0 - let listmx = '^\(-l\|--list\)\s*\([^\s]\+\)\?$' - let bufnamemx = '^' . s:bufprefix .'\([0-9a-f]\+\)$' - - let args = (a:0 > 0) ? split(a:1, ' ') : [] - for arg in args - if arg =~ '^\(-la\|--listall\)$\C' - let gistls = '-all' - elseif arg =~ '^\(-l\|--list\)$\C' - if g:gist_show_privates - let gistls = 'mine' - else - let gistls = g:github_user - endif - elseif arg == '--abandon\C' - call s:GistGetPage('', '', '', '') - return - elseif arg =~ '^\(-m\|--multibuffer\)$\C' - let multibuffer = 1 - elseif arg =~ '^\(-p\|--private\)$\C' - let private = 1 - elseif arg =~ '^\(-P\|--public\)$\C' - let private = 0 - elseif arg =~ '^\(-a\|--anonymous\)$\C' - let user = '' - let token = '' - elseif arg =~ '^\(-c\|--clipboard\)$\C' - let clipboard = 1 - elseif arg =~ '^\(-d\|--delete\)$\C' && bufname =~ bufnamemx - let deletepost = 1 - let gistid = substitute(bufname, bufnamemx, '\1', '') - elseif arg =~ '^\(-e\|--edit\)$\C' && bufname =~ bufnamemx - let editpost = 1 - let gistid = substitute(bufname, bufnamemx, '\1', '') - elseif arg =~ '^\(-f\|--fork\)$\C' && bufname =~ bufnamemx - let gistid = substitute(bufname, bufnamemx, '\1', '') - let res = s:GistGetPage("https://gist.github.com/fork/".gistid, g:github_user, '', '') - let loc = filter(res.header, 'v:val =~ "^Location:"')[0] - let loc = substitute(loc, '^[^:]\+: ', '', '') - let mx = '^https://gist.github.com/\([0-9a-z]\+\)$' - if loc =~ mx - let gistid = substitute(loc, mx, '\1', '') - else - echohl ErrorMsg | echomsg 'Fork failed' | echohl None - return - endif - elseif arg !~ '^-' && len(gistnm) == 0 - if editpost == 1 || deletepost == 1 - let gistnm = arg - elseif len(gistls) > 0 && arg != '^\w\+$\C' - let gistls = arg - elseif arg =~ '^[0-9a-z]\+$\C' - let gistid = arg - else - echohl ErrorMsg | echomsg 'Invalid arguments' | echohl None - unlet args - return 0 - endif - elseif len(arg) > 0 - echohl ErrorMsg | echomsg 'Invalid arguments' | echohl None - unlet args - return 0 - endif - endfor - unlet args - "echo "gistid=".gistid - "echo "gistls=".gistls - "echo "gistnm=".gistnm - "echo "private=".private - "echo "clipboard=".clipboard - "echo "editpost=".editpost - "echo "deletepost=".deletepost - - if len(gistls) > 0 - call s:GistList(user, token, gistls, 1) - elseif len(gistid) > 0 && editpost == 0 && deletepost == 0 - call s:GistGet(user, token, gistid, clipboard) - else - let url = '' - if multibuffer == 1 - let url = s:GistPostBuffers(user, token, private) - else - let content = join(getline(a:line1, a:line2), "\n") - if editpost == 1 - let url = s:GistUpdate(user, token, content, gistid, gistnm) - elseif deletepost == 1 - call s:GistDelete(user, token, gistid) - else - let url = s:GistPost(user, token, content, private) - endif - endif - if len(url) > 0 - if g:gist_open_browser_after_post - let cmd = substitute(g:gist_browser_command, '%URL%', url, 'g') - if cmd =~ '^!' - silent! exec cmd - elseif cmd =~ '^:[A-Z]' - exec cmd - else - call system(cmd) - endif - endif - if g:gist_put_url_to_clipboard_after_post > 0 - if g:gist_put_url_to_clipboard_after_post == 2 - let url = url . "\n" - endif - if exists('g:gist_clip_command') - call system(g:gist_clip_command, url) - elseif has('unix') && !has('xterm_clipboard') - let @" = url - else - let @+ = url - endif - endif - endif - endif - return 1 -endfunction - -command! -nargs=? -range=% Gist :call Gist(<line1>, <line2>, <f-args>) -" vim:set et: diff --git a/vim/plugin/indent-object.vim b/vim/plugin/indent-object.vim deleted file mode 100644 index afb8edd..0000000 --- a/vim/plugin/indent-object.vim +++ /dev/null @@ -1,224 +0,0 @@ -"-------------------------------------------------------------------------------- -" -" Copyright (c) 2010 Michael Smith <msmith@msmith.id.au> -" -" http://github.com/michaeljsmith/vim-indent-object -" -" 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. -" -"-------------------------------------------------------------------------------- - -" Mappings excluding line below. -onoremap <silent>ai :<C-u>cal <Sid>HandleTextObjectMapping(0, 0, 0, [line("."), line("."), col("."), col(".")])<CR> -onoremap <silent>ii :<C-u>cal <Sid>HandleTextObjectMapping(1, 0, 0, [line("."), line("."), col("."), col(".")])<CR> -vnoremap <silent>ai :<C-u>cal <Sid>HandleTextObjectMapping(0, 0, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv -vnoremap <silent>ii :<C-u>cal <Sid>HandleTextObjectMapping(1, 0, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv - -" Mappings including line below. -onoremap <silent>aI :<C-u>cal <Sid>HandleTextObjectMapping(0, 1, 0, [line("."), line("."), col("."), col(".")])<CR> -onoremap <silent>iI :<C-u>cal <Sid>HandleTextObjectMapping(1, 1, 0, [line("."), line("."), col("."), col(".")])<CR> -vnoremap <silent>aI :<C-u>cal <Sid>HandleTextObjectMapping(0, 1, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv -vnoremap <silent>iI :<C-u>cal <Sid>HandleTextObjectMapping(1, 1, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv - -let s:l0 = -1 -let s:l1 = -1 -let s:c0 = -1 -let s:c1 = -1 - -function! <Sid>TextObject(inner, incbelow, vis, range, count) - - " Record the current state of the visual region. - let vismode = "V" - - " Detect if this is a completely new visual selction session. - let new_vis = 0 - let new_vis = new_vis || s:l0 != a:range[0] - let new_vis = new_vis || s:l1 != a:range[1] - let new_vis = new_vis || s:c0 != a:range[2] - let new_vis = new_vis || s:c1 != a:range[3] - - let s:l0 = a:range[0] - let s:l1 = a:range[1] - let s:c0 = a:range[2] - let s:c1 = a:range[3] - - " Repeatedly increase the scope of the selection. - let itr_cnt = 0 - let cnt = a:count - while cnt > 0 - - " Look for the minimum indentation in the current visual region. - let l = s:l0 - let idnt_invalid = 1000 - let idnt = idnt_invalid - while l <= s:l1 - if !(getline(l) =~ "^\\s*$") - let idnt = min([idnt, indent(l)]) - endif - let l += 1 - endwhile - - " Keep track of where the range should be expanded to. - let l_1 = s:l0 - let l_1o = l_1 - let l2 = s:l1 - let l2o = l2 - - " If we are highlighting only blank lines, we may not have found a - " valid indent. In this case we need to look for the next and previous - " non blank lines and check which of those has the largest indent. - if idnt == idnt_invalid - let idnt = 0 - let pnb = prevnonblank(s:l0) - if pnb - let idnt = max([idnt, indent(pnb)]) - let l_1 = pnb - endif - let nnb = nextnonblank(s:l0) - if nnb - let idnt = max([idnt, indent(nnb)]) - endif - - " If we are in whitespace at the beginning of a block, skip over - " it when we are selecting the range. Similarly, if we are in - " whitespace at the end, ignore it. - if idnt > indent(pnb) - let l_1 = nnb - endif - if idnt > indent(nnb) - let l2 = pnb - endif - endif - - " Search backward for the first line with less indent than the target - " indent (skipping blank lines). - let blnk = getline(l_1) =~ "^\\s*$" - while l_1 > 0 && ((idnt == 0 && !blnk) || (idnt != 0 && (blnk || indent(l_1) >= idnt))) - if !blnk || !a:inner - let l_1o = l_1 - endif - let l_1 -= 1 - let blnk = getline(l_1) =~ "^\\s*$" - endwhile - - " Search forward for the first line with more indent than the target - " indent (skipping blank lines). - let line_cnt = line("$") - let blnk = getline(l2) =~ "^\\s*$" - while l2 <= line_cnt && ((idnt == 0 && !blnk) || (idnt != 0 && (blnk || indent(l2) >= idnt))) - if !blnk || !a:inner - let l2o = l2 - endif - let l2 += 1 - let blnk = getline(l2) =~ "^\\s*$" - endwhile - - " Determine which of these extensions to include. Include neither if - " we are selecting an 'inner' object. Exclude the bottom unless are - " told to include it. - let idnt2 = max([indent(l_1), indent(l2)]) - if indent(l_1) < idnt2 || a:inner - let l_1 = l_1o - endif - if indent(l2) < idnt2 || a:inner || !a:incbelow - let l2 = l2o - endif - let l_1 = max([l_1, 1]) - let l2 = min([l2, line("$")]) - - " Extend the columns to the start and end. - " If inner is selected, set the final cursor pos to the start - " of the text in the line. - let c_1 = 1 - if a:inner - let c_1 = match(getline(l_1), "\\c\\S") + 1 - endif - let c2 = len(getline(l2)) - if !a:inner - let c2 += 1 - endif - - " Make sure there's no change if we haven't really made a - " significant change in linewise mode - this makes sure that - " we can iteratively increase selection in linewise mode. - if itr_cnt == 0 && vismode ==# 'V' && s:l0 == l_1 && s:l1 == l2 - let c_1 = s:c0 - let c2 = s:c1 - endif - - " Check whether the visual region has changed. - let chg = 0 - let chg = chg || s:l0 != l_1 - let chg = chg || s:l1 != l2 - let chg = chg || s:c0 != c_1 - let chg = chg || s:c1 != c2 - - if vismode ==# 'V' && new_vis - let chg = 1 - endif - - " Update the vars. - let s:l0 = l_1 - let s:l1 = l2 - let s:c0 = c_1 - let s:c1 = c2 - - " If there was no change, then don't decrement the count (it didn't - " count because it didn't do anything). - if chg - let cnt = cnt - 1 - else - " Since this didn't work, push the selection back one char. This - " will have the effect of getting the enclosing block. Do it at - " the beginning rather than the end - the beginning is very likely - " to be only one indentation level different. - if s:l0 == 0 - return - endif - let s:l0 -= 1 - let s:c0 = len(getline(s:l0)) - endif - - let itr_cnt += 1 - - endwhile - - " Apply the range we have found. Make sure to use the current visual mode. - call cursor(s:l0, s:c0) - exe "normal! " . vismode - call cursor(s:l1, s:c1) - normal! o - - " Update these static variables - we need to keep these up-to-date between - " invocations because it's the only way we can detect whether it's a new - " visual mode. We need to know if it's a new visual mode because otherwise - " if there's a single line block in visual line mode and we select it with - " "V", we can't tell whether it's already been selected using Vii. - exe "normal! \<Esc>" - let s:l0 = line("'<") - let s:l1 = line("'>") - let s:c0 = col("'<") - let s:c1 = col("'>") - normal gv - -endfunction - -function! <Sid>HandleTextObjectMapping(inner, incbelow, vis, range) - call <Sid>TextObject(a:inner, a:incbelow, a:vis, a:range, v:count1) -endfunction diff --git a/vim/plugin/rails.vim b/vim/plugin/rails.vim deleted file mode 100644 index 2dd17f7..0000000 --- a/vim/plugin/rails.vim +++ /dev/null @@ -1,339 +0,0 @@ -" rails.vim - Detect a rails application -" Author: Tim Pope <http://tpo.pe/> -" GetLatestVimScripts: 1567 1 :AutoInstall: rails.vim - -" Install this file as plugin/rails.vim. See doc/rails.txt for details. (Grab -" it from the URL above if you don't have it.) To access it from Vim, see -" :help add-local-help (hint: :helptags ~/.vim/doc) Afterwards, you should be -" able to do :help rails - -if exists('g:loaded_rails') || &cp || v:version < 700 - finish -endif -let g:loaded_rails = 1 - -" Utility Functions {{{1 - -function! s:error(str) - echohl ErrorMsg - echomsg a:str - echohl None - let v:errmsg = a:str -endfunction - -function! s:autoload(...) - if !exists("g:autoloaded_rails") && v:version >= 700 - runtime! autoload/rails.vim - endif - if exists("g:autoloaded_rails") - if a:0 - exe a:1 - endif - return 1 - endif - if !exists("g:rails_no_autoload_warning") - let g:rails_no_autoload_warning = 1 - if v:version >= 700 - call s:error("Disabling rails.vim: autoload/rails.vim is missing") - else - call s:error("Disabling rails.vim: Vim version 7 or higher required") - endif - endif - return "" -endfunction - -" }}}1 -" Configuration {{{ - -function! s:SetOptDefault(opt,val) - if !exists("g:".a:opt) - let g:{a:opt} = a:val - endif -endfunction - -call s:SetOptDefault("rails_statusline",1) -call s:SetOptDefault("rails_syntax",1) -call s:SetOptDefault("rails_mappings",1) -call s:SetOptDefault("rails_abbreviations",1) -call s:SetOptDefault("rails_ctags_arguments","--languages=-javascript") -call s:SetOptDefault("rails_default_file","README") -call s:SetOptDefault("rails_root_url",'http://localhost:3000/') -call s:SetOptDefault("rails_modelines",0) -call s:SetOptDefault("rails_menu",0) -call s:SetOptDefault("rails_gnu_screen",1) -call s:SetOptDefault("rails_history_size",5) -call s:SetOptDefault("rails_generators","controller\ngenerator\nhelper\nintegration_test\nmailer\nmetal\nmigration\nmodel\nobserver\nperformance_test\nplugin\nresource\nscaffold\nscaffold_controller\nsession_migration\nstylesheets") -if exists("g:loaded_dbext") && executable("sqlite3") && ! executable("sqlite") - " Since dbext can't find it by itself - call s:SetOptDefault("dbext_default_SQLITE_bin","sqlite3") -endif - -" }}}1 -" Detection {{{1 - -function! s:escvar(r) - let r = fnamemodify(a:r,':~') - let r = substitute(r,'\W','\="_".char2nr(submatch(0))."_"','g') - let r = substitute(r,'^\d','_&','') - return r -endfunction - -function! s:Detect(filename) - let fn = substitute(fnamemodify(a:filename,":p"),'\c^file://','','') - let sep = matchstr(fn,'^[^\\/]\{3,\}\zs[\\/]') - if sep != "" - let fn = getcwd().sep.fn - endif - if fn =~ '[\/]config[\/]environment\.rb$' - return s:BufInit(strpart(fn,0,strlen(fn)-22)) - endif - if isdirectory(fn) - let fn = fnamemodify(fn,':s?[\/]$??') - else - let fn = fnamemodify(fn,':s?\(.*\)[\/][^\/]*$?\1?') - endif - let ofn = "" - let nfn = fn - while nfn != ofn && nfn != "" - if exists("s:_".s:escvar(nfn)) - return s:BufInit(nfn) - endif - let ofn = nfn - let nfn = fnamemodify(nfn,':h') - endwhile - let ofn = "" - while fn != ofn - if filereadable(fn . "/config/environment.rb") - return s:BufInit(fn) - endif - let ofn = fn - let fn = fnamemodify(ofn,':s?\(.*\)[\/]\(app\|config\|db\|doc\|features\|lib\|log\|public\|script\|spec\|stories\|test\|tmp\|vendor\)\($\|[\/].*$\)?\1?') - endwhile - return 0 -endfunction - -function! s:BufInit(path) - let s:_{s:escvar(a:path)} = 1 - if s:autoload() - return RailsBufInit(a:path) - endif -endfunction - -" }}}1 -" Initialization {{{1 - -augroup railsPluginDetect - autocmd! - autocmd BufNewFile,BufRead * call s:Detect(expand("<afile>:p")) - autocmd VimEnter * if expand("<amatch>") == "" && !exists("b:rails_root") | call s:Detect(getcwd()) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif - autocmd FileType netrw if !exists("b:rails_root") | call s:Detect(expand("<afile>:p")) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif - autocmd BufEnter * if exists("b:rails_root")|silent doau User BufEnterRails|endif - autocmd BufLeave * if exists("b:rails_root")|silent doau User BufLeaveRails|endif - autocmd Syntax railslog if s:autoload()|call rails#log_syntax()|endif -augroup END - -command! -bar -bang -nargs=* -complete=dir Rails :if s:autoload()|call rails#new_app_command(<bang>0,<f-args>)|endif - -" }}}1 -" abolish.vim support {{{1 - -function! s:function(name) - return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) -endfunction - -augroup railsPluginAbolish - autocmd! - autocmd VimEnter * call s:abolish_setup() -augroup END - -function! s:abolish_setup() - if exists('g:Abolish') && has_key(g:Abolish,'Coercions') - if !has_key(g:Abolish.Coercions,'l') - let g:Abolish.Coercions.l = s:function('s:abolish_l') - endif - if !has_key(g:Abolish.Coercions,'t') - let g:Abolish.Coercions.t = s:function('s:abolish_t') - endif - endif -endfunction - -function! s:abolish_l(word) - let singular = rails#singularize(a:word) - return a:word ==? singular ? rails#pluralize(a:word) : singular -endfunction - -function! s:abolish_t(word) - if a:word =~# '\u' - return rails#pluralize(rails#underscore(a:word)) - else - return rails#singularize(rails#camelize(a:word)) - endif -endfunction - -" }}}1 -" Menus {{{1 - -if !(g:rails_menu && has("menu")) - finish -endif - -function! s:sub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'') -endfunction - -function! s:gsub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'g') -endfunction - -function! s:menucmd(priority) - return 'anoremenu <script> '.(exists("$CREAM") ? 87 : '').s:gsub(g:rails_installed_menu,'[^.]','').'.'.a:priority.' ' -endfunction - -function! s:CreateMenus() abort - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - exe "aunmenu ".s:gsub(g:rails_installed_menu,'\&','') - unlet g:rails_installed_menu - endif - if has("menu") && (exists("g:did_install_default_menus") || exists("$CREAM")) && g:rails_menu - if g:rails_menu > 1 - let g:rails_installed_menu = '&Rails' - else - let g:rails_installed_menu = '&Plugin.&Rails' - endif - let dots = s:gsub(g:rails_installed_menu,'[^.]','') - let menucmd = s:menucmd(200) - if exists("$CREAM") - exe menucmd.g:rails_installed_menu.'.-PSep- :' - exe menucmd.g:rails_installed_menu.'.&Related\ file\ :R\ /\ Alt+] :R<CR>' - exe menucmd.g:rails_installed_menu.'.&Alternate\ file\ :A\ /\ Alt+[ :A<CR>' - exe menucmd.g:rails_installed_menu.'.&File\ under\ cursor\ Ctrl+Enter :Rfind<CR>' - else - exe menucmd.g:rails_installed_menu.'.-PSep- :' - exe menucmd.g:rails_installed_menu.'.&Related\ file\ :R\ /\ ]f :R<CR>' - exe menucmd.g:rails_installed_menu.'.&Alternate\ file\ :A\ /\ [f :A<CR>' - exe menucmd.g:rails_installed_menu.'.&File\ under\ cursor\ gf :Rfind<CR>' - endif - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Controller :Rcontroller application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Helper :Rhelper application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Javascript :Rjavascript application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Layout :Rlayout application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &README :R doc/README_FOR_APP<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Environment :Renvironment<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Database\ Configuration :R config/database.yml<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Database\ &Schema :Rmigration 0<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.R&outes :Rinitializer<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Test\ Helper :Rintegrationtest<CR>' - exe menucmd.g:rails_installed_menu.'.-FSep- :' - exe menucmd.g:rails_installed_menu.'.Ra&ke\ :Rake :Rake<CR>' - let menucmd = substitute(menucmd,'200 $','500 ','') - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Start\ :Rserver :Rserver<CR>' - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Force\ start\ :Rserver! :Rserver!<CR>' - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Kill\ :Rserver!\ - :Rserver! -<CR>' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.&Evaluate\ Ruby\.\.\.\ :Rp :call <SID>menuprompt("Rp","Code to execute and output: ")<CR>' - exe menucmd.g:rails_installed_menu.'.&Console\ :Rscript :Rscript console<CR>' - exe menucmd.g:rails_installed_menu.'.&Preview\ :Rpreview :Rpreview<CR>' - exe menucmd.g:rails_installed_menu.'.&Log\ file\ :Rlog :Rlog<CR>' - exe substitute(s:sub(menucmd,'anoremenu','vnoremenu'),'<script>','<script> <silent>','').g:rails_installed_menu.'.E&xtract\ as\ partial\ :Rextract :call <SID>menuprompt("'."'".'<,'."'".'>Rextract","Partial name (e.g., template or /controller/template): ")<CR>' - exe menucmd.g:rails_installed_menu.'.&Migration\ writer\ :Rinvert :Rinvert<CR>' - exe menucmd.' '.g:rails_installed_menu.'.-HSep- :' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.&Help\ :help\ rails :if <SID>autoload()<Bar>exe RailsHelpCommand("")<Bar>endif<CR>' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.Abo&ut\ :if <SID>autoload()<Bar>exe RailsHelpCommand("about")<Bar>endif<CR>' - let g:rails_did_menus = 1 - call s:ProjectMenu() - call s:menuBufLeave() - if exists("b:rails_root") - call s:menuBufEnter() - endif - endif -endfunction - -function! s:ProjectMenu() - if exists("g:rails_did_menus") && g:rails_history_size > 0 - if !exists("g:RAILS_HISTORY") - let g:RAILS_HISTORY = "" - endif - let history = g:RAILS_HISTORY - let menu = s:gsub(g:rails_installed_menu,'\&','') - silent! exe "aunmenu <script> ".menu.".Projects" - let dots = s:gsub(menu,'[^.]','') - exe 'anoremenu <script> <silent> '.(exists("$CREAM") ? '87' : '').dots.'.100 '.menu.'.Pro&jects.&New\.\.\.\ :Rails :call <SID>menuprompt("Rails","New application path and additional arguments: ")<CR>' - exe 'anoremenu <script> '.menu.'.Pro&jects.-FSep- :' - while history =~ '\n' - let proj = matchstr(history,'^.\{-\}\ze\n') - let history = s:sub(history,'^.{-}\n','') - exe 'anoremenu <script> '.menu.'.Pro&jects.'.s:gsub(proj,'[.\\ ]','\\&').' :e '.s:gsub(proj."/".g:rails_default_file,'[ !%#]','\\&')."<CR>" - endwhile - endif -endfunction - -function! s:menuBufEnter() - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - let menu = s:gsub(g:rails_installed_menu,'\&','') - exe 'amenu enable '.menu.'.*' - if RailsFileType() !~ '^view\>' - exe 'vmenu disable '.menu.'.Extract\ as\ partial' - endif - if RailsFileType() !~ '^\%(db-\)\=migration$' || RailsFilePath() =~ '\<db/schema\.rb$' - exe 'amenu disable '.menu.'.Migration\ writer' - endif - call s:ProjectMenu() - silent! exe 'aunmenu '.menu.'.Rake\ tasks' - silent! exe 'aunmenu '.menu.'.Generate' - silent! exe 'aunmenu '.menu.'.Destroy' - if rails#app().cache.needs('rake_tasks') || empty(rails#app().rake_tasks()) - exe substitute(s:menucmd(300),'<script>','<script> <silent>','').g:rails_installed_menu.'.Rake\ &tasks\ :Rake.Fill\ this\ menu :call rails#app().rake_tasks()<Bar>call <SID>menuBufLeave()<Bar>call <SID>menuBufEnter()<CR>' - else - let i = 0 - while i < len(rails#app().rake_tasks()) - let task = rails#app().rake_tasks()[i] - exe s:menucmd(300).g:rails_installed_menu.'.Rake\ &tasks\ :Rake.'.s:sub(task,':',':.').' :Rake '.task.'<CR>' - let i += 1 - endwhile - endif - let i = 0 - let menucmd = substitute(s:menucmd(400),'<script>','<script> <silent>','').g:rails_installed_menu - while i < len(rails#app().generators()) - let generator = rails#app().generators()[i] - exe menucmd.'.&Generate\ :Rgen.'.s:gsub(generator,'_','\\ ').' :call <SID>menuprompt("Rgenerate '.generator.'","Arguments for script/generate '.generator.': ")<CR>' - exe menucmd.'.&Destroy\ :Rdestroy.'.s:gsub(generator,'_','\\ ').' :call <SID>menuprompt("Rdestroy '.generator.'","Arguments for script/destroy '.generator.': ")<CR>' - let i += 1 - endwhile - endif -endfunction - -function! s:menuBufLeave() - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - let menu = s:gsub(g:rails_installed_menu,'\&','') - exe 'amenu disable '.menu.'.*' - exe 'amenu enable '.menu.'.Help\ ' - exe 'amenu enable '.menu.'.About\ ' - exe 'amenu enable '.menu.'.Projects' - silent! exe 'aunmenu '.menu.'.Rake\ tasks' - silent! exe 'aunmenu '.menu.'.Generate' - silent! exe 'aunmenu '.menu.'.Destroy' - exe s:menucmd(300).g:rails_installed_menu.'.Rake\ tasks\ :Rake.-TSep- :' - exe s:menucmd(400).g:rails_installed_menu.'.&Generate\ :Rgen.-GSep- :' - exe s:menucmd(400).g:rails_installed_menu.'.&Destroy\ :Rdestroy.-DSep- :' - endif -endfunction - -function! s:menuprompt(vimcmd,prompt) - let res = inputdialog(a:prompt,'','!!!') - if res == '!!!' - return "" - endif - exe a:vimcmd." ".res -endfunction - -call s:CreateMenus() - -augroup railsPluginMenu - autocmd! - autocmd User BufEnterRails call s:menuBufEnter() - autocmd User BufLeaveRails call s:menuBufLeave() - " g:RAILS_HISTORY hasn't been set when s:InitPlugin() is called. - autocmd VimEnter * call s:ProjectMenu() -augroup END - -" }}}1 -" vim:set sw=2 sts=2: diff --git a/vim/plugin/searchfold_0.9.vim b/vim/plugin/searchfold_0.9.vim deleted file mode 100644 index 1fb9ba8..0000000 --- a/vim/plugin/searchfold_0.9.vim +++ /dev/null @@ -1,319 +0,0 @@ -" Vim global plugin -- create folds based on last search pattern -" General: {{{1 -" File: searchfold.vim -" Created: 2008 Jan 19 -" Last Change: 2011 May 24 -" Rev Days: 18 -" Author: Andy Wokula <anwoku@yahoo.de> -" Credits: Antonio Colombo's f.vim (Vimscript #318, 2005 May 10) -" Vim Version: Vim 7.0 -" Version: 0.9 - -" Description: -" Provide mappings to fold away lines not matching the last search pattern -" and to restore old fold settings afterwards. Uses manual fold method, -" which allows for nested folds to hide or show more context. Doesn't -" preserve the user's manual folds. - -" Usage: -" <Leader>z fold away lines not matching the last search pattern. -" -" With [count], change the initial foldlevel to ([count] minus -" one). The setting will be stored in g:searchfold_foldlevel -" and will be reused when [count] is omitted. -" -" <Leader>iz fold away lines that do match the last search pattern -" (inverse folding), also with [count]. -" -" <Leader>Z restore the previous fold settings. -" -" Minor Extra: If already in restored state, show a dialog to -" revert all involved local fold options to the global -" defaults. The "(s)how" just prints info. - -" Customization: -" :let g:searchfold_maxdepth = 7 -" (number) -" maximum fold depth -" -" :let g:searchfold_usestep = 1 -" (boolean) -" Controls how folds are organized: If 1 (default), each "zr" -" (after "\z") unfolds the same amount of lines above and -" below a match. If 0, only one more line is unfolded above a -" match. This applies for next "\z" or "\iz". -" -" :let g:searchfold_postZ_do_zv = 1 -" (boolean) -" If 1, execute "zv" (view cursor line) after <Leader>Z. -" -" :let g:searchfold_foldlevel = 0 -" (number) -" Initial 'foldlevel' to set for <Leader>z and <Leader>iz. -" -" :let g:searchfold_do_maps = 1 -" (boolean) -" Whether to map the default keys or not. -" -" Hint: For boolean options, 1 actually means any non-zero number. - -" Related: Vimscript #158 (foldutil.vim) ... still to be checked out -" http://www.noah.org/wiki/Vim#Folding -" Vimscript #2302 (foldsearch.vim) -" Vimscript #578 (allfold.tar.gz) -" -" Changes: -" v0.9 redraw removed, plug map renamed, comments (usestep ...) -" v0.8 added inverse folding (<Leader>iz), g:searchfold_foldlevel, -" count for <Leader>z, <Plug> mappings, disabled F(), (fixes) -" v0.7 b:searchfold fallback, s:foldtext check -" v0.6 (after v0.4) added customization vars (usestep, maxdepth, Zpost) -" reverting global fold settings adds to cmd-history -" v0.4 decreasing fold step always 1 -" maxdepth 7 (before: 6) -" v0.3 (after v0.1) added a modified F() from f.vim -" functions now with return values -" v0.2 (skipped) - -" Init Folklore: {{{1 -if exists("loaded_searchfold") - finish -endif -let loaded_searchfold = 1 - -if v:version<700 - echo "Searchfold: you need at least Vim 7.0" - finish -endif - -" Customization: {{{1 -if !exists("g:searchfold_maxdepth") - let g:searchfold_maxdepth = 7 -endif -if !exists("g:searchfold_usestep") - let g:searchfold_usestep = 1 -endif -if !exists("g:searchfold_postZ_do_zv") - let g:searchfold_postZ_do_zv = 1 -endif -if !exists("g:searchfold_foldlevel") - let g:searchfold_foldlevel = 0 -endif -if !exists("g:searchfold_do_maps") - let g:searchfold_do_maps = 1 -endif - -" s:variables {{{1 -let s:foldtext = "(v:folddashes.'').((v:foldend)-(v:foldstart)+(1))" -" use unique notation of 'foldtext' to identify active searchfold in a -" window - -func! s:FoldNested(from, to) " {{{1 - " create one fold from line a:from to line a:to, with more nested folds - " return 1 if folds were created - " return 0 if from > to - let nlines = a:to - a:from - if nlines < 0 - return 0 - elseif nlines < 3 - " range of 1 line possible - exec a:from.",".a:to. "fold" - return 1 - endif - - " calc folds, start with most outer fold - " - range of inner folds at least 2 lines (from<to) - " - limit nesting (depth) - " - snap folds at start and end of file - " - at greater "depth" (here depth->0), don't create folds with few - " lines only (check to-from>step) - if g:searchfold_maxdepth < 1 || g:searchfold_maxdepth > 12 - let g:searchfold_maxdepth = 7 - endif - let depth = g:searchfold_maxdepth - let step = 1 " decstep:'' - let step1 = 1 " (const) decstep:'1' - let from = a:from - let to = a:to - " let decstep = exists("g:searchfold_usestep") && g:searchfold_usestep ? "" : "1" - let decstep = g:searchfold_usestep ? "" : "1" - let foldranges = [] - let lined = line("$") - while depth>0 && from<to && to-from>step - call insert(foldranges, from.",".to) - let from += from>1 ? step : 0 - " let to -= to<lined ? 1 : 0 - let to -= to<lined ? step{decstep} : 0 - let step += step " arbitrary - let depth -= 1 - endwhile - - " create folds, start with most inner fold - for range in foldranges - exec range. "fold" - endfor - - return 1 -endfunc - -func! s:CreateFolds(inverse) " {{{1 - " create search folds for the whole buffer based on last search pattern - let sav_cur = getpos(".") - - let matches = [] " list of lnums - if !a:inverse - global//call add(matches, line(".")) - else - vglobal//call add(matches, line(".")) - endif - - let nmatches = len(matches) - if nmatches > 0 - call s:FoldNested(1, matches[0]-1) - let imax = nmatches - 1 - let i = 0 - while i < imax - if matches[i]+1 < matches[i+1] - call s:FoldNested(matches[i]+1, matches[i+1]-1) - endif - let i += 1 - endwhile - call s:FoldNested(matches[imax]+1, line("$")) - endif - - let &l:foldlevel = g:searchfold_foldlevel - call cursor(sav_cur[1:]) - - return nmatches -endfunc - -func! <sid>SearchFoldEnable(inverse) "{{{1 - " return number of matches - if !search("", "n") - " last search pattern not found, do nothing - return 0 - endif - if (!exists("w:searchfold") || w:searchfold.bufnr != bufnr("")) - \ && &fdt != s:foldtext - " remember settings - let w:searchfold = { "bufnr": bufnr(""), - \ "fdm": &fdm, - \ "fdl": &fdl, - \ "fdt": &fdt, - \ "fen": &fen, - \ "fml": &fml } - " else: do not remember settings if already enabled - endif - setlocal foldmethod=manual - setlocal foldlevel=0 - let &l:foldtext=s:foldtext - setlocal foldenable - setlocal foldminlines=0 - normal! zE - if exists("w:searchfold") - let b:searchfold = w:searchfold - endif - return s:CreateFolds(a:inverse) -endfunc -func! SearchFoldRestore() "{{{1 - " turn off - if exists("w:searchfold") && w:searchfold.bufnr == bufnr("") - " restore settings; var has the right settings if exists, but - " doesn't survive window split or win close/restore - let &l:fdm = w:searchfold.fdm - let &l:fdl = w:searchfold.fdl - let &l:fdt = w:searchfold.fdt - let &l:fen = w:searchfold.fen - let &l:fml = w:searchfold.fml - if &fdm == "manual" - " remove all search folds (old folds are lost anyway): - normal! zE - endif - unlet w:searchfold - elseif exists("b:searchfold") && &fdt == s:foldtext - " fallback only, may have wrong settings if overwritten - let &l:fdm = b:searchfold.fdm - let &l:fdl = b:searchfold.fdl - let &l:fdt = b:searchfold.fdt - let &l:fen = b:searchfold.fen - let &l:fml = b:searchfold.fml - if &fdm == "manual" - normal! zE - endif - else - let choice = input("Revert to global fold settings? (y/[n]/(s)how):")[0] - let setargs = 'fdm< fdl< fdt< fen< fml<' - if choice == "y" - let cmd = 'setlocal '. setargs - echo ':'. cmd - exec cmd - " call histadd(':', cmd) - elseif choice == "s" - let setargs = tr(setargs, "<","?") - let cmd = 'setglobal '. setargs - echo ':'. cmd - exec cmd - let cmd = 'setlocal '. setargs - echo ':'. cmd - exec cmd - endif - return - endif - if g:searchfold_postZ_do_zv - normal! zv - endif -endfunc - -"" func! F() range "{{{1 -" " commented out 2010 Jun 01 -" " range arg: ignore range given by accident -" let pat = input("Which regexp? ", @/) -" if pat == "" -" if exists("w:searchfold") -" call SearchFoldRestore() -" endif -" return -" endif -" let @/ = pat -" call histadd("search", @/) -" call SearchFold() -" endfunc - -" :call F() only for backwards compatibility - -func! SearchFold(...) "{{{1 - let inverse = a:0>=1 && a:1 - if v:count >= 1 - let g:searchfold_foldlevel = v:count - 1 - endif - let nmatches = <sid>SearchFoldEnable(inverse) - " at most one match per line counted - if nmatches == 0 - echohl ErrorMsg - echomsg "Searchfold: Pattern not found:" @/ - echohl none - elseif nmatches == line("$") - echomsg "Searchfold: Pattern found in every line:" @/ - elseif nmatches == 1 - echo "Searchfold: 1 line found" - else - echo "Searchfold:" nmatches "lines found" - endif - " 2011 Feb 06 commented out: - " let &hls = &hls - " redraw -endfunc - -" Mappings: {{{1 -nn <silent> <Plug>SearchFoldNormal :<C-U>call SearchFold(0)<CR> -nn <silent> <Plug>SearchFoldInverse :<C-U>call SearchFold(1)<CR> -nn <silent> <Plug>SearchFoldRestore :<C-U>call SearchFoldRestore()<CR> - -if g:searchfold_do_maps - nmap <Leader>z <Plug>SearchFoldNormal - nmap <Leader>iz <Plug>SearchFoldInverse - nmap <Leader>Z <Plug>SearchFoldRestore -endif - -" Modeline: {{{1 -" vim:set fdm=marker ts=8 sts=4 sw=4 noet: diff --git a/vim/plugin/showmarks.vim b/vim/plugin/showmarks.vim deleted file mode 100644 index c6931c2..0000000 --- a/vim/plugin/showmarks.vim +++ /dev/null @@ -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 diff --git a/vim/plugin/snipMate.vim b/vim/plugin/snipMate.vim deleted file mode 100644 index ef03b12..0000000 --- a/vim/plugin/snipMate.vim +++ /dev/null @@ -1,271 +0,0 @@ -" File: snipMate.vim -" Author: Michael Sanders -" Version: 0.84 -" 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 - -" Reset snippets for filetype. -fun! ResetSnippets(ft) - let ft = a:ft == '' ? '_' : a:ft - for dict in [s:snippets, s:multi_snips, g:did_ft] - if has_key(dict, ft) - unlet dict[ft] - endif - endfor -endf - -" Reset snippets for all filetypes. -fun! ResetAllSnippets() - let s:snippets = {} | let s:multi_snips = {} | let g:did_ft = {} -endf - -" Reload snippets for filetype. -fun! ReloadSnippets(ft) - let ft = a:ft == '' ? '_' : a:ft - call ResetSnippets(ft) - call GetSnippets(g:snippets_dir, ft) -endf - -" Reload snippets for all filetypes. -fun! ReloadAllSnippets() - for ft in keys(g:did_ft) - call ReloadSnippets(ft) - endfor -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 diff --git a/vim/plugin/supertab.vim b/vim/plugin/supertab.vim deleted file mode 100644 index 67f8c5c..0000000 --- a/vim/plugin/supertab.vim +++ /dev/null @@ -1,737 +0,0 @@ -" Author: -" Original: Gergely Kontra <kgergely@mcl.hu> -" Current: Eric Van Dewoestine <ervandew@gmail.com> (as of version 0.4) -" Please direct all correspondence to Eric. -" Version: 1.6 -" GetLatestVimScripts: 1643 1 :AutoInstall: supertab.vim -" -" Description: {{{ -" Use your tab key to do all your completion in insert mode! -" You can cycle forward and backward with the <Tab> and <S-Tab> keys -" Note: you must press <Tab> once to be able to cycle back -" -" http://www.vim.org/scripts/script.php?script_id=1643 -" }}} -" -" License: {{{ -" Copyright (c) 2002 - 2011 -" 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 Gergely Kontra or 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 Gergely -" Kontra or 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. -" }}} -" -" Testing Info: {{{ -" Running vim + supertab with the absolute bar minimum settings: -" $ vim -u NONE -U NONE -c "set nocp | runtime plugin/supertab.vim" -" }}} - -if v:version < 700 - finish -endif - -if exists('complType') " Integration with other completion functions. - finish -endif - -let s:save_cpo=&cpo -set cpo&vim - -" Global Variables {{{ - - if !exists("g:SuperTabDefaultCompletionType") - let g:SuperTabDefaultCompletionType = "<c-p>" - endif - - if !exists("g:SuperTabContextDefaultCompletionType") - let g:SuperTabContextDefaultCompletionType = "<c-p>" - endif - - if !exists("g:SuperTabCompletionContexts") - let g:SuperTabCompletionContexts = ['s:ContextText'] - endif - - if !exists("g:SuperTabRetainCompletionDuration") - let g:SuperTabRetainCompletionDuration = 'insert' - endif - - if !exists("g:SuperTabNoCompleteBefore") - " retain backwards compatability - if exists("g:SuperTabMidWordCompletion") && !g:SuperTabMidWordCompletion - let g:SuperTabNoCompleteBefore = ['\k'] - else - let g:SuperTabNoCompleteBefore = [] - endif - endif - - if !exists("g:SuperTabNoCompleteAfter") - " retain backwards compatability - if exists("g:SuperTabLeadingSpaceCompletion") && g:SuperTabLeadingSpaceCompletion - let g:SuperTabNoCompleteAfter = [] - else - let g:SuperTabNoCompleteAfter = ['\s'] - endif - endif - - if !exists("g:SuperTabMappingForward") - let g:SuperTabMappingForward = '<tab>' - endif - if !exists("g:SuperTabMappingBackward") - let g:SuperTabMappingBackward = '<s-tab>' - endif - - if !exists("g:SuperTabMappingTabLiteral") - let g:SuperTabMappingTabLiteral = '<c-tab>' - endif - - if !exists("g:SuperTabLongestEnhanced") - let g:SuperTabLongestEnhanced = 0 - endif - - if !exists("g:SuperTabLongestHighlight") - let g:SuperTabLongestHighlight = 0 - endif - - if !exists("g:SuperTabCrMapping") - let g:SuperTabCrMapping = 1 - endif - -" }}} - -" Script Variables {{{ - - " construct the help text. - let s:tabHelp = - \ "Hit <CR> or CTRL-] on the completion type you wish to switch to.\n" . - \ "Use :help ins-completion for more information.\n" . - \ "\n" . - \ "|<c-n>| - Keywords in 'complete' searching down.\n" . - \ "|<c-p>| - Keywords in 'complete' searching up (SuperTab default).\n" . - \ "|<c-x><c-l>| - Whole lines.\n" . - \ "|<c-x><c-n>| - Keywords in current file.\n" . - \ "|<c-x><c-k>| - Keywords in 'dictionary'.\n" . - \ "|<c-x><c-t>| - Keywords in 'thesaurus', thesaurus-style.\n" . - \ "|<c-x><c-i>| - Keywords in the current and included files.\n" . - \ "|<c-x><c-]>| - Tags.\n" . - \ "|<c-x><c-f>| - File names.\n" . - \ "|<c-x><c-d>| - Definitions or macros.\n" . - \ "|<c-x><c-v>| - Vim command-line.\n" . - \ "|<c-x><c-u>| - User defined completion.\n" . - \ "|<c-x><c-o>| - Omni completion.\n" . - \ "|<c-x>s| - Spelling suggestions." - - " set the available completion types and modes. - let s:types = - \ "\<c-e>\<c-y>\<c-l>\<c-n>\<c-k>\<c-t>\<c-i>\<c-]>" . - \ "\<c-f>\<c-d>\<c-v>\<c-n>\<c-p>\<c-u>\<c-o>\<c-n>\<c-p>s" - let s:modes = '/^E/^Y/^L/^N/^K/^T/^I/^]/^F/^D/^V/^P/^U/^O/s' - let s:types = s:types . "np" - let s:modes = s:modes . '/n/p' - -" }}} - -" SuperTabSetDefaultCompletionType(type) {{{ -" Globally available function that users can use to set the default -" completion type for the current buffer, like in an ftplugin. -function! SuperTabSetDefaultCompletionType(type) - " init hack for <c-x><c-v> workaround. - let b:complCommandLine = 0 - - let b:SuperTabDefaultCompletionType = a:type - - " set the current completion type to the default - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) -endfunction " }}} - -" SuperTabSetCompletionType(type) {{{ -" Globally available function that users can use to create mappings to quickly -" switch completion modes. Useful when a user wants to restore the default or -" switch to another mode without having to kick off a completion of that type -" or use SuperTabHelp. Note, this function only changes the current -" completion type, not the default, meaning that the default will still be -" restored once the configured retension duration has been met (see -" g:SuperTabRetainCompletionDuration). To change the default for the current -" buffer, use SuperTabDefaultCompletionType(type) instead. Example mapping to -" restore SuperTab default: -" nmap <F6> :call SetSuperTabCompletionType("<c-p>")<cr> -function! SuperTabSetCompletionType(type) - call s:InitBuffer() - exec "let b:complType = \"" . escape(a:type, '<') . "\"" -endfunction " }}} - -" SuperTabAlternateCompletion(type) {{{ -" Function which can be mapped to a key to kick off an alternate completion -" other than the default. For instance, if you have 'context' as the default -" and want to map ctrl+space to issue keyword completion. -" Note: due to the way vim expands ctrl characters in mappings, you cannot -" create the alternate mapping like so: -" imap <c-space> <c-r>=SuperTabAlternateCompletion("<c-p>")<cr> -" instead, you have to use \<lt> to prevent vim from expanding the key -" when creating the mapping. -" gvim: -" imap <c-space> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr> -" console: -" imap <nul> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr> -function! SuperTabAlternateCompletion(type) - call SuperTabSetCompletionType(a:type) - " end any current completion before attempting to start the new one. - " use feedkeys to prevent possible remapping of <c-e> from causing issues. - "call feedkeys("\<c-e>", 'n') - " ^ since we can't detect completion mode vs regular insert mode, we force - " vim into keyword completion mode and end that mode to prevent the regular - " insert behavior of <c-e> from occurring. - call feedkeys("\<c-x>\<c-p>\<c-e>", 'n') - call feedkeys(b:complType, 'n') - return '' -endfunction " }}} - -" SuperTabLongestHighlight(dir) {{{ -" When longest highlight is enabled, this function is used to do the actual -" selection of the completion popup entry. -function! SuperTabLongestHighlight(dir) - if !pumvisible() - return '' - endif - return a:dir == -1 ? "\<up>" : "\<down>" -endfunction " }}} - -" s:Init {{{ -" Global initilization when supertab is loaded. -function! s:Init() - " Setup mechanism to restore original completion type upon leaving insert - " mode if configured to do so - if g:SuperTabRetainCompletionDuration == 'insert' - augroup supertab_retain - autocmd! - autocmd InsertLeave * call s:SetDefaultCompletionType() - augroup END - endif -endfunction " }}} - -" s:InitBuffer {{{ -" Per buffer initilization. -function! s:InitBuffer() - if exists('b:SuperTabNoCompleteBefore') - return - endif - - let b:complReset = 0 - let b:complTypeManual = !exists('b:complTypeManual') ? '' : b:complTypeManual - let b:complTypeContext = '' - - " init hack for <c-x><c-v> workaround. - let b:complCommandLine = 0 - - if !exists('b:SuperTabNoCompleteBefore') - let b:SuperTabNoCompleteBefore = g:SuperTabNoCompleteBefore - endif - if !exists('b:SuperTabNoCompleteAfter') - let b:SuperTabNoCompleteAfter = g:SuperTabNoCompleteAfter - endif - - let b:SuperTabDefaultCompletionType = g:SuperTabDefaultCompletionType - - " set the current completion type to the default - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) -endfunction " }}} - -" s:ManualCompletionEnter() {{{ -" Handles manual entrance into completion mode. -function! s:ManualCompletionEnter() - if &smd - echo '' | echohl ModeMsg | echo '-- ^X++ mode (' . s:modes . ')' | echohl None - endif - let complType = nr2char(getchar()) - if stridx(s:types, complType) != -1 - if stridx("\<c-e>\<c-y>", complType) != -1 " no memory, just scroll... - return "\<c-x>" . complType - elseif stridx('np', complType) != -1 - let complType = nr2char(char2nr(complType) - 96) - else - let complType = "\<c-x>" . complType - endif - - let b:complTypeManual = complType - - if index(['insert', 'session'], g:SuperTabRetainCompletionDuration) != -1 - let b:complType = complType - endif - - " Hack to workaround bug when invoking command line completion via <c-r>= - if complType == "\<c-x>\<c-v>" - return s:CommandLineCompletion() - endif - - " optionally enable enhanced longest completion - if g:SuperTabLongestEnhanced && &completeopt =~ 'longest' - call s:EnableLongestEnhancement() - endif - - if g:SuperTabLongestHighlight && - \ &completeopt =~ 'longest' && - \ &completeopt =~ 'menu' && - \ !pumvisible() - let dir = (complType == "\<c-x>\<c-p>") ? -1 : 1 - call feedkeys("\<c-r>=SuperTabLongestHighlight(" . dir . ")\<cr>", 'n') - endif - - return complType - endif - - echohl "Unknown mode" - return complType -endfunction " }}} - -" s:SetCompletionType() {{{ -" Sets the completion type based on what the user has chosen from the help -" buffer. -function! s:SetCompletionType() - let chosen = substitute(getline('.'), '.*|\(.*\)|.*', '\1', '') - if chosen != getline('.') - let winnr = b:winnr - close - exec winnr . 'winc w' - call SuperTabSetCompletionType(chosen) - endif -endfunction " }}} - -" s:SetDefaultCompletionType() {{{ -function! s:SetDefaultCompletionType() - if exists('b:SuperTabDefaultCompletionType') && - \ (!exists('b:complCommandLine') || !b:complCommandLine) - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) - endif -endfunction " }}} - -" s:SuperTab(command) {{{ -" Used to perform proper cycle navigation as the user requests the next or -" previous entry in a completion list, and determines whether or not to simply -" retain the normal usage of <tab> based on the cursor position. -function! s:SuperTab(command) - if exists('b:SuperTabDisabled') && b:SuperTabDisabled - return "\<tab>" - endif - - call s:InitBuffer() - - if s:WillComplete() - " optionally enable enhanced longest completion - if g:SuperTabLongestEnhanced && &completeopt =~ 'longest' - call s:EnableLongestEnhancement() - endif - - if !pumvisible() - let b:complTypeManual = '' - endif - - " exception: if in <c-p> mode, then <c-n> should move up the list, and - " <c-p> down the list. - if a:command == 'p' && !b:complReset && - \ (b:complType == "\<c-p>" || - \ (b:complType == 'context' && - \ b:complTypeManual == '' && - \ b:complTypeContext == "\<c-p>")) - return "\<c-n>" - - elseif a:command == 'p' && !b:complReset && - \ (b:complType == "\<c-n>" || - \ (b:complType == 'context' && - \ b:complTypeManual == '' && - \ b:complTypeContext == "\<c-n>")) - return "\<c-p>" - - " already in completion mode and not resetting for longest enhancement, so - " just scroll to next/previous - elseif pumvisible() && !b:complReset - let type = b:complType == 'context' ? b:complTypeContext : b:complType - if a:command == 'n' - return type == "\<c-p>" ? "\<c-p>" : "\<c-n>" - endif - return type == "\<c-p>" ? "\<c-n>" : "\<c-p>" - endif - - " handle 'context' completion. - if b:complType == 'context' - let complType = s:ContextCompletion() - if complType == '' - exec "let complType = \"" . - \ escape(g:SuperTabContextDefaultCompletionType, '<') . "\"" - endif - let b:complTypeContext = complType - - " Hack to workaround bug when invoking command line completion via <c-r>= - elseif b:complType == "\<c-x>\<c-v>" - let complType = s:CommandLineCompletion() - else - let complType = b:complType - endif - - " highlight first result if longest enabled - if g:SuperTabLongestHighlight && - \ &completeopt =~ 'longest' && - \ &completeopt =~ 'menu' && - \ (!pumvisible() || b:complReset) - let dir = (complType == "\<c-p>") ? -1 : 1 - call feedkeys("\<c-r>=SuperTabLongestHighlight(" . dir . ")\<cr>", 'n') - endif - - if b:complReset - let b:complReset = 0 - " not an accurate condition for everyone, but better than sending <c-e> - " at the wrong time. - if pumvisible() - return "\<c-e>" . complType - endif - endif - - return complType - endif - - return "\<tab>" -endfunction " }}} - -" s:SuperTabHelp() {{{ -" Opens a help window where the user can choose a completion type to enter. -function! s:SuperTabHelp() - let winnr = winnr() - if bufwinnr("SuperTabHelp") == -1 - botright split SuperTabHelp - - setlocal noswapfile - setlocal buftype=nowrite - setlocal bufhidden=delete - - let saved = @" - let @" = s:tabHelp - silent put - call cursor(1, 1) - silent 1,delete - call cursor(4, 1) - let @" = saved - exec "resize " . line('$') - - syntax match Special "|.\{-}|" - - setlocal readonly - setlocal nomodifiable - - nmap <silent> <buffer> <cr> :call <SID>SetCompletionType()<cr> - nmap <silent> <buffer> <c-]> :call <SID>SetCompletionType()<cr> - else - exec bufwinnr("SuperTabHelp") . "winc w" - endif - let b:winnr = winnr -endfunction " }}} - -" s:WillComplete() {{{ -" Determines if completion should be kicked off at the current location. -function! s:WillComplete() - if pumvisible() - return 1 - endif - - let line = getline('.') - let cnum = col('.') - - " Start of line. - if line =~ '^\s*\%' . cnum . 'c' - return 0 - endif - - " honor SuperTabNoCompleteAfter - let pre = line[:cnum - 2] - for pattern in b:SuperTabNoCompleteAfter - if pre =~ pattern . '$' - return 0 - endif - endfor - - " honor SuperTabNoCompleteBefore - " Within a word, but user does not have mid word completion enabled. - let post = line[cnum - 1:] - for pattern in b:SuperTabNoCompleteBefore - if post =~ '^' . pattern - return 0 - endif - endfor - - return 1 -endfunction " }}} - -" s:EnableLongestEnhancement() {{{ -function! s:EnableLongestEnhancement() - augroup supertab_reset - autocmd! - autocmd InsertLeave,CursorMovedI <buffer> - \ call s:ReleaseKeyPresses() | autocmd! supertab_reset - augroup END - call s:CaptureKeyPresses() -endfunction " }}} - -" s:CompletionReset(char) {{{ -function! s:CompletionReset(char) - let b:complReset = 1 - return a:char -endfunction " }}} - -" s:CaptureKeyPresses() {{{ -function! s:CaptureKeyPresses() - if !exists('b:capturing') || !b:capturing - let b:capturing = 1 - " save any previous mappings - " TODO: capture additional info provided by vim 7.3.032 and up. - let b:captured = { - \ '<bs>': maparg('<bs>', 'i'), - \ '<c-h>': maparg('<c-h>', 'i'), - \ } - " TODO: use &keyword to get an accurate list of chars to map - for c in split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_', '.\zs') - exec 'imap <buffer> ' . c . ' <c-r>=<SID>CompletionReset("' . c . '")<cr>' - endfor - imap <buffer> <bs> <c-r>=<SID>CompletionReset("\<lt>bs>")<cr> - imap <buffer> <c-h> <c-r>=<SID>CompletionReset("\<lt>c-h>")<cr> - endif -endfunction " }}} - -" s:ReleaseKeyPresses() {{{ -function! s:ReleaseKeyPresses() - if exists('b:capturing') && b:capturing - let b:capturing = 0 - for c in split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_', '.\zs') - exec 'iunmap <buffer> ' . c - endfor - - iunmap <buffer> <bs> - iunmap <buffer> <c-h> - - " restore any previous mappings - for [key, rhs] in items(b:captured) - if rhs != '' - let args = substitute(rhs, '.*\(".\{-}"\).*', '\1', '') - if args != rhs - let args = substitute(args, '<', '<lt>', 'g') - let expr = substitute(rhs, '\(.*\)".\{-}"\(.*\)', '\1%s\2', '') - let rhs = printf(expr, args) - endif - exec printf("imap <silent> %s %s", key, rhs) - endif - endfor - unlet b:captured - - if mode() == 'i' && &completeopt =~ 'menu' - " force full exit from completion mode (don't exit insert mode since - " that will break repeating with '.') - call feedkeys("\<space>\<bs>", 'n') - endif - endif -endfunction " }}} - -" s:CommandLineCompletion() {{{ -" Hack needed to account for apparent bug in vim command line mode completion -" when invoked via <c-r>= -function! s:CommandLineCompletion() - " This hack will trigger InsertLeave which will then invoke - " s:SetDefaultCompletionType. To prevent default completion from being - " restored prematurely, set an internal flag for s:SetDefaultCompletionType - " to check for. - let b:complCommandLine = 1 - return "\<c-\>\<c-o>:call feedkeys('\<c-x>\<c-v>\<c-v>', 'n') | " . - \ "let b:complCommandLine = 0\<cr>" -endfunction " }}} - -" s:ContextCompletion() {{{ -function! s:ContextCompletion() - let contexts = exists('b:SuperTabCompletionContexts') ? - \ b:SuperTabCompletionContexts : g:SuperTabCompletionContexts - - for context in contexts - try - let Context = function(context) - let complType = Context() - unlet Context - if type(complType) == 1 && complType != '' - return complType - endif - catch /E700/ - echohl Error - echom 'supertab: no context function "' . context . '" found.' - echohl None - endtry - endfor - return '' -endfunction " }}} - -" s:ContextDiscover() {{{ -function! s:ContextDiscover() - let discovery = exists('g:SuperTabContextDiscoverDiscovery') ? - \ g:SuperTabContextDiscoverDiscovery : [] - - " loop through discovery list to find the default - if !empty(discovery) - for pair in discovery - let var = substitute(pair, '\(.*\):.*', '\1', '') - let type = substitute(pair, '.*:\(.*\)', '\1', '') - exec 'let value = ' . var - if value !~ '^\s*$' && value != '0' - exec "let complType = \"" . escape(type, '<') . "\"" - return complType - endif - endfor - endif -endfunction " }}} - -" s:ContextText() {{{ -function! s:ContextText() - let exclusions = exists('g:SuperTabContextTextFileTypeExclusions') ? - \ g:SuperTabContextTextFileTypeExclusions : [] - - if index(exclusions, &ft) == -1 - let curline = getline('.') - let cnum = col('.') - let synname = synIDattr(synID(line('.'), cnum - 1, 1), 'name') - if curline =~ '.*/\w*\%' . cnum . 'c' || - \ ((has('win32') || has('win64')) && curline =~ '.*\\\w*\%' . cnum . 'c') - return "\<c-x>\<c-f>" - - elseif curline =~ '.*\(\w\|[\])]\)\(\.\|::\|->\)\w*\%' . cnum . 'c' && - \ synname !~ '\(String\|Comment\)' - let omniPrecedence = exists('g:SuperTabContextTextOmniPrecedence') ? - \ g:SuperTabContextTextOmniPrecedence : ['&completefunc', '&omnifunc'] - - for omniFunc in omniPrecedence - if omniFunc !~ '^&' - let omniFunc = '&' . omniFunc - endif - if getbufvar(bufnr('%'), omniFunc) != '' - return omniFunc == '&omnifunc' ? "\<c-x>\<c-o>" : "\<c-x>\<c-u>" - endif - endfor - endif - endif -endfunction " }}} - -" s:ExpandMap(map) {{{ -function! s:ExpandMap(map) - let map = a:map - if map =~ '<Plug>' - let plug = substitute(map, '.\{-}\(<Plug>\w\+\).*', '\1', '') - let plug_map = maparg(plug, 'i') - let map = substitute(map, '.\{-}\(<Plug>\w\+\).*', plug_map, '') - endif - return map -endfunction " }}} - -" Key Mappings {{{ - " map a regular tab to ctrl-tab (note: doesn't work in console vim) - exec 'inoremap ' . g:SuperTabMappingTabLiteral . ' <tab>' - - imap <c-x> <c-r>=<SID>ManualCompletionEnter()<cr> - - imap <script> <Plug>SuperTabForward <c-r>=<SID>SuperTab('n')<cr> - imap <script> <Plug>SuperTabBackward <c-r>=<SID>SuperTab('p')<cr> - - exec 'imap ' . g:SuperTabMappingForward . ' <Plug>SuperTabForward' - exec 'imap ' . g:SuperTabMappingBackward . ' <Plug>SuperTabBackward' - - " After hitting <Tab>, hitting it once more will go to next match - " (because in XIM mode <c-n> and <c-p> mappings are ignored) - " and wont start a brand new completion - " The side effect, that in the beginning of line <c-n> and <c-p> inserts a - " <Tab>, but I hope it may not be a problem... - let ctrl_n = maparg('<c-n>', 'i') - if ctrl_n != '' - let ctrl_n = substitute(ctrl_n, '<', '<lt>', 'g') - exec 'imap <c-n> <c-r>=<SID>ForwardBack("n", "' . ctrl_n . '")<cr>' - else - imap <c-n> <Plug>SuperTabForward - endif - let ctrl_p = maparg('<c-p>', 'i') - if ctrl_p != '' - let ctrl_p = substitute(ctrl_p, '<', '<lt>', 'g') - exec 'imap <c-p> <c-r>=<SID>ForwardBack("p", "' . ctrl_p . '")<cr>' - else - imap <c-p> <Plug>SuperTabBackward - endif - function! s:ForwardBack(command, map) - exec "let map = \"" . escape(a:map, '<') . "\"" - return pumvisible() ? s:SuperTab(a:command) : map - endfunction - - if g:SuperTabCrMapping - if maparg('<CR>','i') =~ '<CR>' - let map = maparg('<cr>', 'i') - let cr = (map =~? '\(^\|[^)]\)<cr>') - let map = s:ExpandMap(map) - exec "inoremap <script> <cr> <c-r>=<SID>SelectCompletion(" . cr . ")<cr>" . map - else - inoremap <cr> <c-r>=<SID>SelectCompletion(1)<cr> - endif - function! s:SelectCompletion(cr) - " selecting a completion - if pumvisible() - " ugly hack to let other <cr> mappings for other plugins cooperate - " with supertab - let b:supertab_pumwasvisible = 1 - return "\<c-y>" - endif - - " only needed when chained with other mappings and one of them will - " issue a <cr>. - if exists('b:supertab_pumwasvisible') && !a:cr - unlet b:supertab_pumwasvisible - return '' - endif - - " not so pleasant hack to keep <cr> working for abbreviations - let word = substitute(getline('.'), '^.*\s\+\(.*\%' . col('.') . 'c\).*', '\1', '') - if maparg(word, 'i', 1) != '' - call feedkeys("\<c-]>", 't') - call feedkeys("\<cr>", 'n') - return '' - endif - - " only return a cr if nothing else is mapped to it since we don't want - " to duplicate a cr returned by another mapping. - return a:cr ? "\<cr>" : "" - endfunction - endif -" }}} - -" Command Mappings {{{ - if !exists(":SuperTabHelp") - command SuperTabHelp :call <SID>SuperTabHelp() - endif -" }}} - -call s:Init() - -let &cpo = s:save_cpo - -" vim:ft=vim:fdm=marker diff --git a/vim/plugin/surround.vim b/vim/plugin/surround.vim deleted file mode 100644 index ea28c02..0000000 --- a/vim/plugin/surround.vim +++ /dev/null @@ -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: diff --git a/vim/plugin/syntastic.vim b/vim/plugin/syntastic.vim deleted file mode 100644 index 0eb657a..0000000 --- a/vim/plugin/syntastic.vim +++ /dev/null @@ -1,614 +0,0 @@ -"============================================================================ -"File: syntastic.vim -"Description: vim plugin for on the fly syntax checking -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"Version: 2.3.0 -"Last Change: 16 Feb, 2012 -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists("g:loaded_syntastic_plugin") - finish -endif -let g:loaded_syntastic_plugin = 1 - -let s:running_windows = has("win16") || has("win32") || has("win64") - -if !s:running_windows - let s:uname = system('uname') -endif - -if !exists("g:syntastic_enable_signs") - let g:syntastic_enable_signs = 1 -endif -if !has('signs') - let g:syntastic_enable_signs = 0 -endif - -if !exists("g:syntastic_enable_balloons") - let g:syntastic_enable_balloons = 1 -endif -if !has('balloon_eval') - let g:syntastic_enable_balloons = 0 -endif - -if !exists("g:syntastic_enable_highlighting") - let g:syntastic_enable_highlighting = 1 -endif - -if !exists("g:syntastic_echo_current_error") - let g:syntastic_echo_current_error = 1 -endif - -if !exists("g:syntastic_auto_loc_list") - let g:syntastic_auto_loc_list = 2 -endif - -if !exists("g:syntastic_auto_jump") - let syntastic_auto_jump=0 -endif - -if !exists("g:syntastic_quiet_warnings") - let g:syntastic_quiet_warnings = 0 -endif - -if !exists("g:syntastic_stl_format") - let g:syntastic_stl_format = '[Syntax: line:%F (%t)]' -endif - -if !exists("g:syntastic_mode_map") - let g:syntastic_mode_map = {} -endif - -if !has_key(g:syntastic_mode_map, "mode") - let g:syntastic_mode_map['mode'] = 'active' -endif - -if !has_key(g:syntastic_mode_map, "active_filetypes") - let g:syntastic_mode_map['active_filetypes'] = [] -endif - -if !has_key(g:syntastic_mode_map, "passive_filetypes") - let g:syntastic_mode_map['passive_filetypes'] = [] -endif - -if !exists("g:syntastic_check_on_open") - let g:syntastic_check_on_open = 0 -endif - -if !exists("g:syntastic_loc_list_height") - let g:syntastic_loc_list_height = 10 -endif - -command! SyntasticToggleMode call s:ToggleMode() -command! SyntasticCheck call s:UpdateErrors(0) <bar> redraw! -command! Errors call s:ShowLocList() - -highlight link SyntasticError SpellBad -highlight link SyntasticWarning SpellCap - -augroup syntastic - if g:syntastic_echo_current_error - autocmd cursormoved * call s:EchoCurrentError() - endif - - autocmd BufReadPost * if g:syntastic_check_on_open | call s:UpdateErrors(1) | endif - autocmd BufWritePost * call s:UpdateErrors(1) - - autocmd BufWinEnter * if empty(&bt) | call s:AutoToggleLocList() | endif - autocmd BufWinLeave * if empty(&bt) | lclose | endif -augroup END - - -"refresh and redraw all the error info for this buf when saving or reading -function! s:UpdateErrors(auto_invoked) - if !empty(&buftype) - return - endif - - if !a:auto_invoked || s:ModeMapAllowsAutoChecking() - call s:CacheErrors() - end - - if s:BufHasErrorsOrWarningsToDisplay() - call setloclist(0, s:LocList()) - endif - - if g:syntastic_enable_balloons - call s:RefreshBalloons() - endif - - if g:syntastic_enable_signs - call s:RefreshSigns() - endif - - if g:syntastic_auto_jump && s:BufHasErrorsOrWarningsToDisplay() - silent! ll - endif - - call s:AutoToggleLocList() -endfunction - -"automatically open/close the location list window depending on the users -"config and buffer error state -function! s:AutoToggleLocList() - if s:BufHasErrorsOrWarningsToDisplay() - if g:syntastic_auto_loc_list == 1 - call s:ShowLocList() - endif - else - if g:syntastic_auto_loc_list > 0 - - "TODO: this will close the loc list window if one was opened by - "something other than syntastic - lclose - endif - endif -endfunction - -"lazy init the loc list for the current buffer -function! s:LocList() - if !exists("b:syntastic_loclist") - let b:syntastic_loclist = [] - endif - return b:syntastic_loclist -endfunction - -"clear the loc list for the buffer -function! s:ClearLocList() - let b:syntastic_loclist = [] -endfunction - -"detect and cache all syntax errors in this buffer -" -"depends on a function called SyntaxCheckers_{&ft}_GetLocList() existing -"elsewhere -function! s:CacheErrors() - call s:ClearLocList() - - if filereadable(expand("%")) - - "sub - for _ in filetypes otherwise we cant name syntax checker - "functions legally for filetypes like "gentoo-metadata" - let fts = substitute(&ft, '-', '_', 'g') - for ft in split(fts, '\.') - if s:Checkable(ft) - let errors = SyntaxCheckers_{ft}_GetLocList() - "make errors have type "E" by default - call SyntasticAddToErrors(errors, {'type': 'E'}) - call extend(s:LocList(), errors) - endif - endfor - endif -endfunction - -"toggle the g:syntastic_mode_map['mode'] -function! s:ToggleMode() - if g:syntastic_mode_map['mode'] == "active" - let g:syntastic_mode_map['mode'] = "passive" - else - let g:syntastic_mode_map['mode'] = "active" - endif - - call s:ClearLocList() - call s:UpdateErrors(1) - - echo "Syntastic: " . g:syntastic_mode_map['mode'] . " mode enabled" -endfunction - -"check the current filetypes against g:syntastic_mode_map to determine whether -"active mode syntax checking should be done -function! s:ModeMapAllowsAutoChecking() - let fts = split(&ft, '\.') - - if g:syntastic_mode_map['mode'] == 'passive' - "check at least one filetype is active - let actives = g:syntastic_mode_map["active_filetypes"] - return !empty(filter(fts, 'index(actives, v:val) != -1')) - else - "check no filetypes are passive - let passives = g:syntastic_mode_map["passive_filetypes"] - return empty(filter(fts, 'index(passives, v:val) != -1')) - endif -endfunction - -"return true if there are cached errors/warnings for this buf -function! s:BufHasErrorsOrWarnings() - return !empty(s:LocList()) -endfunction - -"return true if there are cached errors for this buf -function! s:BufHasErrors() - return len(s:ErrorsForType('E')) > 0 -endfunction - -function! s:BufHasErrorsOrWarningsToDisplay() - return s:BufHasErrors() || (!g:syntastic_quiet_warnings && s:BufHasErrorsOrWarnings()) -endfunction - -function! s:ErrorsForType(type) - return s:FilterLocList({'type': a:type}) -endfunction - -function! s:Errors() - return s:ErrorsForType("E") -endfunction - -function! s:Warnings() - return s:ErrorsForType("W") -endfunction - -"Filter a loc list (defaults to s:LocList()) by a:filters -"e.g. -" s:FilterLocList({'bufnr': 10, 'type': 'e'}) -" -"would return all errors in s:LocList() for buffer 10. -" -"Note that all comparisons are done with ==? -function! s:FilterLocList(filters, ...) - let llist = a:0 ? a:1 : s:LocList() - - let rv = deepcopy(llist) - for error in llist - for key in keys(a:filters) - let rhs = a:filters[key] - if type(rhs) == 1 "string - let rhs = '"' . rhs . '"' - endif - - call filter(rv, "v:val['".key."'] ==? " . rhs) - endfor - endfor - return rv -endfunction - -if g:syntastic_enable_signs - "define the signs used to display syntax and style errors/warns - sign define SyntasticError text=>> texthl=error - sign define SyntasticWarning text=>> texthl=todo - sign define SyntasticStyleError text=S> texthl=error - sign define SyntasticStyleWarning text=S> texthl=todo -endif - -"start counting sign ids at 5000, start here to hopefully avoid conflicting -"with any other code that places signs (not sure if this precaution is -"actually needed) -let s:first_sign_id = 5000 -let s:next_sign_id = s:first_sign_id - -"place signs by all syntax errs in the buffer -function! s:SignErrors() - if s:BufHasErrorsOrWarningsToDisplay() - - let errors = s:FilterLocList({'bufnr': bufnr('')}) - for i in errors - let sign_severity = 'Error' - let sign_subtype = '' - if has_key(i,'subtype') - let sign_subtype = i['subtype'] - endif - if i['type'] ==? 'w' - let sign_severity = 'Warning' - endif - let sign_type = 'Syntastic' . sign_subtype . sign_severity - - if !s:WarningMasksError(i, errors) - exec "sign place ". s:next_sign_id ." line=". i['lnum'] ." name=". sign_type ." file=". expand("%:p") - call add(s:BufSignIds(), s:next_sign_id) - let s:next_sign_id += 1 - endif - endfor - endif -endfunction - -"return true if the given error item is a warning that, if signed, would -"potentially mask an error if displayed at the same time -function! s:WarningMasksError(error, llist) - if a:error['type'] !=? 'w' - return 0 - endif - - return len(s:FilterLocList({ 'type': "E", 'lnum': a:error['lnum'] }, a:llist)) > 0 -endfunction - -"remove the signs with the given ids from this buffer -function! s:RemoveSigns(ids) - for i in a:ids - exec "sign unplace " . i - call remove(s:BufSignIds(), index(s:BufSignIds(), i)) - endfor -endfunction - -"get all the ids of the SyntaxError signs in the buffer -function! s:BufSignIds() - if !exists("b:syntastic_sign_ids") - let b:syntastic_sign_ids = [] - endif - return b:syntastic_sign_ids -endfunction - -"update the error signs -function! s:RefreshSigns() - let old_signs = copy(s:BufSignIds()) - call s:SignErrors() - call s:RemoveSigns(old_signs) - let s:first_sign_id = s:next_sign_id -endfunction - -"display the cached errors for this buf in the location list -function! s:ShowLocList() - if !empty(s:LocList()) - let num = winnr() - exec "lopen " . g:syntastic_loc_list_height - if num != winnr() - wincmd p - endif - endif -endfunction - -"remove all error highlights from the window -function! s:ClearErrorHighlights() - for match in getmatches() - if stridx(match['group'], 'Syntastic') == 0 - call matchdelete(match['id']) - endif - endfor -endfunction - -"check if a syntax checker exists for the given filetype - and attempt to -"load one -function! s:Checkable(ft) - if !exists("g:loaded_" . a:ft . "_syntax_checker") - exec "runtime syntax_checkers/" . a:ft . ".vim" - endif - - return exists("*SyntaxCheckers_". a:ft ."_GetLocList") -endfunction - -"set up error ballons for the current set of errors -function! s:RefreshBalloons() - let b:syntastic_balloons = {} - if s:BufHasErrorsOrWarningsToDisplay() - for i in s:LocList() - let b:syntastic_balloons[i['lnum']] = i['text'] - endfor - set beval bexpr=SyntasticErrorBalloonExpr() - endif -endfunction - -"print as much of a:msg as possible without "Press Enter" prompt appearing -function! s:WideMsg(msg) - let old_ruler = &ruler - let old_showcmd = &showcmd - - let msg = strpart(a:msg, 0, winwidth(0)-1) - - "This is here because it is possible for some error messages to begin with - "\n which will cause a "press enter" prompt. I have noticed this in the - "javascript:jshint checker and have been unable to figure out why it - "happens - let msg = substitute(msg, "\n", "", "g") - - set noruler noshowcmd - redraw - - echo msg - - let &ruler=old_ruler - let &showcmd=old_showcmd -endfunction - -"echo out the first error we find for the current line in the cmd window -function! s:EchoCurrentError() - "If we have an error or warning at the current line, show it - let errors = s:FilterLocList({'lnum': line("."), "type": 'e'}) - let warnings = s:FilterLocList({'lnum': line("."), "type": 'w'}) - - let b:syntastic_echoing_error = len(errors) || len(warnings) - if len(errors) - return s:WideMsg(errors[0]['text']) - endif - if len(warnings) - return s:WideMsg(warnings[0]['text']) - endif - - "Otherwise, clear the status line - if b:syntastic_echoing_error - echo - let b:syntastic_echoing_error = 0 - endif -endfunction - -"load the chosen checker for the current filetype - useful for filetypes like -"javascript that have more than one syntax checker -function! s:LoadChecker(checker) - exec "runtime syntax_checkers/" . &ft . "/" . a:checker . ".vim" -endfunction - -"return a string representing the state of buffer according to -"g:syntastic_stl_format -" -"return '' if no errors are cached for the buffer -function! SyntasticStatuslineFlag() - if s:BufHasErrorsOrWarningsToDisplay() - let errors = s:Errors() - let warnings = s:Warnings() - - let output = g:syntastic_stl_format - - "hide stuff wrapped in %E(...) unless there are errors - let output = substitute(output, '\C%E{\([^}]*\)}', len(errors) ? '\1' : '' , 'g') - - "hide stuff wrapped in %W(...) unless there are warnings - let output = substitute(output, '\C%W{\([^}]*\)}', len(warnings) ? '\1' : '' , 'g') - - "hide stuff wrapped in %B(...) unless there are both errors and warnings - let output = substitute(output, '\C%B{\([^}]*\)}', (len(warnings) && len(errors)) ? '\1' : '' , 'g') - - "sub in the total errors/warnings/both - let output = substitute(output, '\C%w', len(warnings), 'g') - let output = substitute(output, '\C%e', len(errors), 'g') - let output = substitute(output, '\C%t', len(s:LocList()), 'g') - - "first error/warning line num - let output = substitute(output, '\C%F', s:LocList()[0]['lnum'], 'g') - - "first error line num - let output = substitute(output, '\C%fe', len(errors) ? errors[0]['lnum'] : '', 'g') - - "first warning line num - let output = substitute(output, '\C%fw', len(warnings) ? warnings[0]['lnum'] : '', 'g') - - return output - else - return '' - endif -endfunction - -"A wrapper for the :lmake command. Sets up the make environment according to -"the options given, runs make, resets the environment, returns the location -"list -" -"a:options can contain the following keys: -" 'makeprg' -" 'errorformat' -" -"The corresponding options are set for the duration of the function call. They -"are set with :let, so dont escape spaces. -" -"a:options may also contain: -" 'defaults' - a dict containing default values for the returned errors -" 'subtype' - all errors will be assigned the given subtype -function! SyntasticMake(options) - let old_loclist = getloclist(0) - let old_makeprg = &makeprg - let old_shellpipe = &shellpipe - let old_shell = &shell - let old_errorformat = &errorformat - - if !s:running_windows && (s:uname !~ "FreeBSD") - "this is a hack to stop the screen needing to be ':redraw'n when - "when :lmake is run. Otherwise the screen flickers annoyingly - let &shellpipe='&>' - let &shell = '/bin/bash' - endif - - if has_key(a:options, 'makeprg') - let &makeprg = a:options['makeprg'] - endif - - if has_key(a:options, 'errorformat') - let &errorformat = a:options['errorformat'] - endif - - silent lmake! - let errors = getloclist(0) - - call setloclist(0, old_loclist) - let &makeprg = old_makeprg - let &errorformat = old_errorformat - let &shellpipe=old_shellpipe - let &shell=old_shell - - if !s:running_windows && s:uname =~ "FreeBSD" - redraw! - endif - - if has_key(a:options, 'defaults') - call SyntasticAddToErrors(errors, a:options['defaults']) - endif - - " Add subtype info if present. - if has_key(a:options, 'subtype') - call SyntasticAddToErrors(errors, {'subtype': a:options['subtype']}) - endif - - return errors -endfunction - -"get the error balloon for the current mouse position -function! SyntasticErrorBalloonExpr() - if !exists('b:syntastic_balloons') - return '' - endif - return get(b:syntastic_balloons, v:beval_lnum, '') -endfunction - -"highlight the list of errors (a:errors) using matchadd() -" -"a:termfunc is provided to highlight errors that do not have a 'col' key (and -"hence cant be done automatically). This function must take one arg (an error -"item) and return a regex to match that item in the buffer. -" -"an optional boolean third argument can be provided to force a:termfunc to be -"used regardless of whether a 'col' key is present for the error -function! SyntasticHighlightErrors(errors, termfunc, ...) - if !g:syntastic_enable_highlighting - return - endif - - call s:ClearErrorHighlights() - - let force_callback = a:0 && a:1 - for item in a:errors - let group = item['type'] == 'E' ? 'SyntasticError' : 'SyntasticWarning' - if item['col'] && !force_callback - let lastcol = col([item['lnum'], '$']) - let lcol = min([lastcol, item['col']]) - call matchadd(group, '\%'.item['lnum'].'l\%'.lcol.'c') - else - let term = a:termfunc(item) - if len(term) > 0 - call matchadd(group, '\%' . item['lnum'] . 'l' . term) - endif - endif - endfor -endfunction - -"take a list of errors and add default values to them from a:options -function! SyntasticAddToErrors(errors, options) - for i in range(0, len(a:errors)-1) - for key in keys(a:options) - if !has_key(a:errors[i], key) || empty(a:errors[i][key]) - let a:errors[i][key] = a:options[key] - endif - endfor - endfor - return a:errors -endfunction - -"take a list of syntax checkers for the current filetype and load the right -"one based on the global settings and checker executable availabity -" -"a:checkers should be a list of syntax checker names. These names are assumed -"to be the names of the vim syntax checker files that should be sourced, as -"well as the names of the actual syntax checker executables. The checkers -"should be listed in order of default preference. -" -"if a option called 'g:syntastic_[filetype]_checker' exists then attempt to -"load the checker that it points to -function! SyntasticLoadChecker(checkers) - let opt_name = "g:syntastic_" . &ft . "_checker" - - if exists(opt_name) - let opt_val = {opt_name} - if index(a:checkers, opt_val) != -1 && executable(opt_val) - call s:LoadChecker(opt_val) - else - echoerr &ft . " syntax not supported or not installed." - endif - else - for checker in a:checkers - if executable(checker) - return s:LoadChecker(checker) - endif - endfor - endif -endfunction - -" vim: set et sts=4 sw=4: diff --git a/vim/plugin/tagbar.vim b/vim/plugin/tagbar.vim deleted file mode 100644 index a078a18..0000000 --- a/vim/plugin/tagbar.vim +++ /dev/null @@ -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 diff --git a/vim/plugin/taglist.vim b/vim/plugin/taglist.vim deleted file mode 100644 index 59901f6..0000000 --- a/vim/plugin/taglist.vim +++ /dev/null @@ -1,4546 +0,0 @@ -" File: taglist.vim -" Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com) -" Version: 4.5 -" Last Modified: September 21, 2007 -" Copyright: Copyright (C) 2002-2007 Yegappan Lakshmanan -" 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. -" -" The "Tag List" plugin is a source code browser plugin for Vim and provides -" an overview of the structure of the programming language files and allows -" you to efficiently browse through source code files for different -" programming languages. You can visit the taglist plugin home page for more -" information: -" -" http://vim-taglist.sourceforge.net -" -" You can subscribe to the taglist mailing list to post your questions -" or suggestions for improvement or to report bugs. Visit the following -" page for subscribing to the mailing list: -" -" http://groups.yahoo.com/group/taglist/ -" -" For more information about using this plugin, after installing the -" taglist plugin, use the ":help taglist" command. -" -" Installation -" ------------ -" 1. Download the taglist.zip file and unzip the files to the $HOME/.vim -" or the $HOME/vimfiles or the $VIM/vimfiles directory. This should -" unzip the following two files (the directory structure should be -" preserved): -" -" plugin/taglist.vim - main taglist plugin file -" doc/taglist.txt - documentation (help) file -" -" Refer to the 'add-plugin', 'add-global-plugin' and 'runtimepath' -" Vim help pages for more details about installing Vim plugins. -" 2. Change to the $HOME/.vim/doc or $HOME/vimfiles/doc or -" $VIM/vimfiles/doc directory, start Vim and run the ":helptags ." -" command to process the taglist help file. -" 3. If the exuberant ctags utility is not present in your PATH, then set the -" Tlist_Ctags_Cmd variable to point to the location of the exuberant ctags -" utility (not to the directory) in the .vimrc file. -" 4. If you are running a terminal/console version of Vim and the -" terminal doesn't support changing the window width then set the -" 'Tlist_Inc_Winwidth' variable to 0 in the .vimrc file. -" 5. Restart Vim. -" 6. You can now use the ":TlistToggle" command to open/close the taglist -" window. You can use the ":help taglist" command to get more -" information about using the taglist plugin. -" -" ****************** Do not modify after this line ************************ - -" Line continuation used here -let s:cpo_save = &cpo -set cpo&vim - -if !exists('loaded_taglist') - " First time loading the taglist plugin - " - " To speed up the loading of Vim, the taglist plugin uses autoload - " mechanism to load the taglist functions. - " Only define the configuration variables, user commands and some - " auto-commands and finish sourcing the file - - " The taglist plugin requires the built-in Vim system() function. If this - " function is not available, then don't load the plugin. - if !exists('*system') - echomsg 'Taglist: Vim system() built-in function is not available. ' . - \ 'Plugin is not loaded.' - let loaded_taglist = 'no' - let &cpo = s:cpo_save - finish - endif - - " Location of the exuberant ctags tool - if !exists('Tlist_Ctags_Cmd') - if executable('exuberant-ctags') - " On Debian Linux, exuberant ctags is installed - " as exuberant-ctags - let Tlist_Ctags_Cmd = 'exuberant-ctags' - elseif executable('exctags') - " On Free-BSD, exuberant ctags is installed as exctags - let Tlist_Ctags_Cmd = 'exctags' - elseif executable('ctags') - let Tlist_Ctags_Cmd = 'ctags' - elseif executable('ctags.exe') - let Tlist_Ctags_Cmd = 'ctags.exe' - elseif executable('tags') - let Tlist_Ctags_Cmd = 'tags' - else - echomsg 'Taglist: Exuberant ctags (http://ctags.sf.net) ' . - \ 'not found in PATH. Plugin is not loaded.' - " Skip loading the plugin - let loaded_taglist = 'no' - let &cpo = s:cpo_save - finish - endif - endif - - - " Automatically open the taglist window on Vim startup - if !exists('Tlist_Auto_Open') - let Tlist_Auto_Open = 0 - endif - - " When the taglist window is toggle opened, move the cursor to the - " taglist window - if !exists('Tlist_GainFocus_On_ToggleOpen') - let Tlist_GainFocus_On_ToggleOpen = 0 - endif - - " Process files even when the taglist window is not open - if !exists('Tlist_Process_File_Always') - let Tlist_Process_File_Always = 0 - endif - - if !exists('Tlist_Show_Menu') - let Tlist_Show_Menu = 0 - endif - - " Tag listing sort type - 'name' or 'order' - if !exists('Tlist_Sort_Type') - let Tlist_Sort_Type = 'order' - endif - - " Tag listing window split (horizontal/vertical) control - if !exists('Tlist_Use_Horiz_Window') - let Tlist_Use_Horiz_Window = 0 - endif - - " Open the vertically split taglist window on the left or on the right - " side. This setting is relevant only if Tlist_Use_Horiz_Window is set to - " zero (i.e. only for vertically split windows) - if !exists('Tlist_Use_Right_Window') - let Tlist_Use_Right_Window = 0 - endif - - " Increase Vim window width to display vertically split taglist window. - " For MS-Windows version of Vim running in a MS-DOS window, this must be - " set to 0 otherwise the system may hang due to a Vim limitation. - if !exists('Tlist_Inc_Winwidth') - if (has('win16') || has('win95')) && !has('gui_running') - let Tlist_Inc_Winwidth = 0 - else - let Tlist_Inc_Winwidth = 1 - endif - endif - - " Vertically split taglist window width setting - if !exists('Tlist_WinWidth') - let Tlist_WinWidth = 30 - endif - - " Horizontally split taglist window height setting - if !exists('Tlist_WinHeight') - let Tlist_WinHeight = 10 - endif - - " Display tag prototypes or tag names in the taglist window - if !exists('Tlist_Display_Prototype') - let Tlist_Display_Prototype = 0 - endif - - " Display tag scopes in the taglist window - if !exists('Tlist_Display_Tag_Scope') - let Tlist_Display_Tag_Scope = 1 - endif - - " Use single left mouse click to jump to a tag. By default this is disabled. - " Only double click using the mouse will be processed. - if !exists('Tlist_Use_SingleClick') - let Tlist_Use_SingleClick = 0 - endif - - " Control whether additional help is displayed as part of the taglist or - " not. Also, controls whether empty lines are used to separate the tag - " tree. - if !exists('Tlist_Compact_Format') - let Tlist_Compact_Format = 0 - endif - - " Exit Vim if only the taglist window is currently open. By default, this is - " set to zero. - if !exists('Tlist_Exit_OnlyWindow') - let Tlist_Exit_OnlyWindow = 0 - endif - - " Automatically close the folds for the non-active files in the taglist - " window - if !exists('Tlist_File_Fold_Auto_Close') - let Tlist_File_Fold_Auto_Close = 0 - endif - - " Close the taglist window when a tag is selected - if !exists('Tlist_Close_On_Select') - let Tlist_Close_On_Select = 0 - endif - - " Automatically update the taglist window to display tags for newly - " edited files - if !exists('Tlist_Auto_Update') - let Tlist_Auto_Update = 1 - endif - - " Automatically highlight the current tag - if !exists('Tlist_Auto_Highlight_Tag') - let Tlist_Auto_Highlight_Tag = 1 - endif - - " Automatically highlight the current tag on entering a buffer - if !exists('Tlist_Highlight_Tag_On_BufEnter') - let Tlist_Highlight_Tag_On_BufEnter = 1 - endif - - " Enable fold column to display the folding for the tag tree - if !exists('Tlist_Enable_Fold_Column') - let Tlist_Enable_Fold_Column = 1 - endif - - " Display the tags for only one file in the taglist window - if !exists('Tlist_Show_One_File') - let Tlist_Show_One_File = 0 - endif - - if !exists('Tlist_Max_Submenu_Items') - let Tlist_Max_Submenu_Items = 20 - endif - - if !exists('Tlist_Max_Tag_Length') - let Tlist_Max_Tag_Length = 10 - endif - - " Do not change the name of the taglist title variable. The winmanager - " plugin relies on this name to determine the title for the taglist - " plugin. - let TagList_title = "__Tag_List__" - - " Taglist debug messages - let s:tlist_msg = '' - - " Define the taglist autocommand to automatically open the taglist window - " on Vim startup - if g:Tlist_Auto_Open - autocmd VimEnter * nested call s:Tlist_Window_Check_Auto_Open() - endif - - " Refresh the taglist - if g:Tlist_Process_File_Always - autocmd BufEnter * call s:Tlist_Refresh() - endif - - if g:Tlist_Show_Menu - autocmd GUIEnter * call s:Tlist_Menu_Init() - endif - - " When the taglist buffer is created when loading a Vim session file, - " the taglist buffer needs to be initialized. The BufFilePost event - " is used to handle this case. - autocmd BufFilePost __Tag_List__ call s:Tlist_Vim_Session_Load() - - " Define the user commands to manage the taglist window - command! -nargs=0 -bar TlistToggle call s:Tlist_Window_Toggle() - command! -nargs=0 -bar TlistOpen call s:Tlist_Window_Open() - " For backwards compatiblity define the Tlist command - command! -nargs=0 -bar Tlist TlistToggle - command! -nargs=+ -complete=file TlistAddFiles - \ call s:Tlist_Add_Files(<f-args>) - command! -nargs=+ -complete=dir TlistAddFilesRecursive - \ call s:Tlist_Add_Files_Recursive(<f-args>) - command! -nargs=0 -bar TlistClose call s:Tlist_Window_Close() - command! -nargs=0 -bar TlistUpdate call s:Tlist_Update_Current_File() - command! -nargs=0 -bar TlistHighlightTag call s:Tlist_Window_Highlight_Tag( - \ fnamemodify(bufname('%'), ':p'), line('.'), 2, 1) - " For backwards compatiblity define the TlistSync command - command! -nargs=0 -bar TlistSync TlistHighlightTag - command! -nargs=* -complete=buffer TlistShowPrototype - \ echo Tlist_Get_Tag_Prototype_By_Line(<f-args>) - command! -nargs=* -complete=buffer TlistShowTag - \ echo Tlist_Get_Tagname_By_Line(<f-args>) - command! -nargs=* -complete=file TlistSessionLoad - \ call s:Tlist_Session_Load(<q-args>) - command! -nargs=* -complete=file TlistSessionSave - \ call s:Tlist_Session_Save(<q-args>) - command! -bar TlistLock let Tlist_Auto_Update=0 - command! -bar TlistUnlock let Tlist_Auto_Update=1 - - " Commands for enabling/disabling debug and to display debug messages - command! -nargs=? -complete=file -bar TlistDebug - \ call s:Tlist_Debug_Enable(<q-args>) - command! -nargs=0 -bar TlistUndebug call s:Tlist_Debug_Disable() - command! -nargs=0 -bar TlistMessages call s:Tlist_Debug_Show() - - " Define autocommands to autoload the taglist plugin when needed. - - " Trick to get the current script ID - map <SID>xx <SID>xx - let s:tlist_sid = substitute(maparg('<SID>xx'), '<SNR>\(\d\+_\)xx$', - \ '\1', '') - unmap <SID>xx - - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_Window_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_Menu_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined Tlist_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined TagList_* source ' . - \ escape(expand('<sfile>'), ' ') - - let loaded_taglist = 'fast_load_done' - - if g:Tlist_Show_Menu && has('gui_running') - call s:Tlist_Menu_Init() - endif - - " restore 'cpo' - let &cpo = s:cpo_save - finish -endif - -if !exists('s:tlist_sid') - " Two or more versions of taglist plugin are installed. Don't - " load this version of the plugin. - finish -endif - -unlet! s:tlist_sid - -if loaded_taglist != 'fast_load_done' - " restore 'cpo' - let &cpo = s:cpo_save - finish -endif - -" Taglist plugin functionality is available -let loaded_taglist = 'available' - -"------------------- end of user configurable options -------------------- - -" Default language specific settings for supported file types and tag types -" -" Variable name format: -" -" s:tlist_def_{vim_ftype}_settings -" -" vim_ftype - Filetype detected by Vim -" -" Value format: -" -" <ctags_ftype>;<flag>:<name>;<flag>:<name>;... -" -" ctags_ftype - File type supported by exuberant ctags -" flag - Flag supported by exuberant ctags to generate a tag type -" name - Name of the tag type used in the taglist window to display the -" tags of this type -" - -" assembly language -let s:tlist_def_asm_settings = 'asm;d:define;l:label;m:macro;t:type' - -" aspperl language -let s:tlist_def_aspperl_settings = 'asp;f:function;s:sub;v:variable' - -" aspvbs language -let s:tlist_def_aspvbs_settings = 'asp;f:function;s:sub;v:variable' - -" awk language -let s:tlist_def_awk_settings = 'awk;f:function' - -" beta language -let s:tlist_def_beta_settings = 'beta;f:fragment;s:slot;v:pattern' - -" c language -let s:tlist_def_c_settings = 'c;d:macro;g:enum;s:struct;u:union;t:typedef;' . - \ 'v:variable;f:function' - -" c++ language -let s:tlist_def_cpp_settings = 'c++;n:namespace;v:variable;d:macro;t:typedef;' . - \ 'c:class;g:enum;s:struct;u:union;f:function' - -" c# language -let s:tlist_def_cs_settings = 'c#;d:macro;t:typedef;n:namespace;c:class;' . - \ 'E:event;g:enum;s:struct;i:interface;' . - \ 'p:properties;m:method' - -" cobol language -let s:tlist_def_cobol_settings = 'cobol;d:data;f:file;g:group;p:paragraph;' . - \ 'P:program;s:section' - -" eiffel language -let s:tlist_def_eiffel_settings = 'eiffel;c:class;f:feature' - -" erlang language -let s:tlist_def_erlang_settings = 'erlang;d:macro;r:record;m:module;f:function' - -" expect (same as tcl) language -let s:tlist_def_expect_settings = 'tcl;c:class;f:method;p:procedure' - -" fortran language -let s:tlist_def_fortran_settings = 'fortran;p:program;b:block data;' . - \ 'c:common;e:entry;i:interface;k:type;l:label;m:module;' . - \ 'n:namelist;t:derived;v:variable;f:function;s:subroutine' - -" HTML language -let s:tlist_def_html_settings = 'html;a:anchor;f:javascript function' - -" java language -let s:tlist_def_java_settings = 'java;p:package;c:class;i:interface;' . - \ 'f:field;m:method' - -" javascript language -let s:tlist_def_javascript_settings = 'javascript;f:function' - -" lisp language -let s:tlist_def_lisp_settings = 'lisp;f:function' - -" lua language -let s:tlist_def_lua_settings = 'lua;f:function' - -" makefiles -let s:tlist_def_make_settings = 'make;m:macro' - -" pascal language -let s:tlist_def_pascal_settings = 'pascal;f:function;p:procedure' - -" perl language -let s:tlist_def_perl_settings = 'perl;c:constant;l:label;p:package;s:subroutine' - -" php language -let s:tlist_def_php_settings = 'php;c:class;d:constant;v:variable;f:function' - -" python language -let s:tlist_def_python_settings = 'python;c:class;m:member;f:function' - -" rexx language -let s:tlist_def_rexx_settings = 'rexx;s:subroutine' - -" ruby language -let s:tlist_def_ruby_settings = 'ruby;c:class;f:method;F:function;' . - \ 'm:singleton method' - -" scheme language -let s:tlist_def_scheme_settings = 'scheme;s:set;f:function' - -" shell language -let s:tlist_def_sh_settings = 'sh;f:function' - -" C shell language -let s:tlist_def_csh_settings = 'sh;f:function' - -" Z shell language -let s:tlist_def_zsh_settings = 'sh;f:function' - -" slang language -let s:tlist_def_slang_settings = 'slang;n:namespace;f:function' - -" sml language -let s:tlist_def_sml_settings = 'sml;e:exception;c:functor;s:signature;' . - \ 'r:structure;t:type;v:value;f:function' - -" sql language -let s:tlist_def_sql_settings = 'sql;c:cursor;F:field;P:package;r:record;' . - \ 's:subtype;t:table;T:trigger;v:variable;f:function;p:procedure' - -" tcl language -let s:tlist_def_tcl_settings = 'tcl;c:class;f:method;m:method;p:procedure' - -" vera language -let s:tlist_def_vera_settings = 'vera;c:class;d:macro;e:enumerator;' . - \ 'f:function;g:enum;m:member;p:program;' . - \ 'P:prototype;t:task;T:typedef;v:variable;' . - \ 'x:externvar' - -"verilog language -let s:tlist_def_verilog_settings = 'verilog;m:module;c:constant;P:parameter;' . - \ 'e:event;r:register;t:task;w:write;p:port;v:variable;f:function' - -" vim language -let s:tlist_def_vim_settings = 'vim;a:autocmds;v:variable;f:function' - -" yacc language -let s:tlist_def_yacc_settings = 'yacc;l:label' - -"------------------- end of language specific options -------------------- - -" Vim window size is changed by the taglist plugin or not -let s:tlist_winsize_chgd = -1 -" Taglist window is maximized or not -let s:tlist_win_maximized = 0 -" Name of files in the taglist -let s:tlist_file_names='' -" Number of files in the taglist -let s:tlist_file_count = 0 -" Number of filetypes supported by taglist -let s:tlist_ftype_count = 0 -" Is taglist part of other plugins like winmanager or cream? -let s:tlist_app_name = "none" -" Are we displaying brief help text -let s:tlist_brief_help = 1 -" List of files removed on user request -let s:tlist_removed_flist = "" -" Index of current file displayed in the taglist window -let s:tlist_cur_file_idx = -1 -" Taglist menu is empty or not -let s:tlist_menu_empty = 1 - -" An autocommand is used to refresh the taglist window when entering any -" buffer. We don't want to refresh the taglist window if we are entering the -" file window from one of the taglist functions. The 'Tlist_Skip_Refresh' -" variable is used to skip the refresh of the taglist window and is set -" and cleared appropriately. -let s:Tlist_Skip_Refresh = 0 - -" Tlist_Window_Display_Help() -function! s:Tlist_Window_Display_Help() - if s:tlist_app_name == "winmanager" - " To handle a bug in the winmanager plugin, add a space at the - " last line - call setline('$', ' ') - endif - - if s:tlist_brief_help - " Add the brief help - call append(0, '" Press <F1> to display help text') - else - " Add the extensive help - call append(0, '" <enter> : Jump to tag definition') - call append(1, '" o : Jump to tag definition in new window') - call append(2, '" p : Preview the tag definition') - call append(3, '" <space> : Display tag prototype') - call append(4, '" u : Update tag list') - call append(5, '" s : Select sort field') - call append(6, '" d : Remove file from taglist') - call append(7, '" x : Zoom-out/Zoom-in taglist window') - call append(8, '" + : Open a fold') - call append(9, '" - : Close a fold') - call append(10, '" * : Open all folds') - call append(11, '" = : Close all folds') - call append(12, '" [[ : Move to the start of previous file') - call append(13, '" ]] : Move to the start of next file') - call append(14, '" q : Close the taglist window') - call append(15, '" <F1> : Remove help text') - endif -endfunction - -" Tlist_Window_Toggle_Help_Text() -" Toggle taglist plugin help text between the full version and the brief -" version -function! s:Tlist_Window_Toggle_Help_Text() - if g:Tlist_Compact_Format - " In compact display mode, do not display help - return - endif - - " Include the empty line displayed after the help text - let brief_help_size = 1 - let full_help_size = 16 - - setlocal modifiable - - " Set report option to a huge value to prevent informational messages - " while deleting the lines - let old_report = &report - set report=99999 - - " Remove the currently highlighted tag. Otherwise, the help text - " might be highlighted by mistake - match none - - " Toggle between brief and full help text - if s:tlist_brief_help - let s:tlist_brief_help = 0 - - " Remove the previous help - exe '1,' . brief_help_size . ' delete _' - - " Adjust the start/end line numbers for the files - call s:Tlist_Window_Update_Line_Offsets(0, 1, full_help_size - brief_help_size) - else - let s:tlist_brief_help = 1 - - " Remove the previous help - exe '1,' . full_help_size . ' delete _' - - " Adjust the start/end line numbers for the files - call s:Tlist_Window_Update_Line_Offsets(0, 0, full_help_size - brief_help_size) - endif - - call s:Tlist_Window_Display_Help() - - " Restore the report option - let &report = old_report - - setlocal nomodifiable -endfunction - -" Taglist debug support -let s:tlist_debug = 0 - -" File for storing the debug messages -let s:tlist_debug_file = '' - -" Tlist_Debug_Enable -" Enable logging of taglist debug messages. -function! s:Tlist_Debug_Enable(...) - let s:tlist_debug = 1 - - " Check whether a valid file name is supplied. - if a:1 != '' - let s:tlist_debug_file = fnamemodify(a:1, ':p') - - " Empty the log file - exe 'redir! > ' . s:tlist_debug_file - redir END - - " Check whether the log file is present/created - if !filewritable(s:tlist_debug_file) - call s:Tlist_Warning_Msg('Taglist: Unable to create log file ' - \ . s:tlist_debug_file) - let s:tlist_debug_file = '' - endif - endif -endfunction - -" Tlist_Debug_Disable -" Disable logging of taglist debug messages. -function! s:Tlist_Debug_Disable(...) - let s:tlist_debug = 0 - let s:tlist_debug_file = '' -endfunction - -" Tlist_Debug_Show -" Display the taglist debug messages in a new window -function! s:Tlist_Debug_Show() - if s:tlist_msg == '' - call s:Tlist_Warning_Msg('Taglist: No debug messages') - return - endif - - " Open a new window to display the taglist debug messages - new taglist_debug.txt - " Delete all the lines (if the buffer already exists) - silent! %delete _ - " Add the messages - silent! put =s:tlist_msg - " Move the cursor to the first line - normal! gg -endfunction - -" Tlist_Log_Msg -" Log the supplied debug message along with the time -function! s:Tlist_Log_Msg(msg) - if s:tlist_debug - if s:tlist_debug_file != '' - exe 'redir >> ' . s:tlist_debug_file - silent echon strftime('%H:%M:%S') . ': ' . a:msg . "\n" - redir END - else - " Log the message into a variable - " Retain only the last 3000 characters - let len = strlen(s:tlist_msg) - if len > 3000 - let s:tlist_msg = strpart(s:tlist_msg, len - 3000) - endif - let s:tlist_msg = s:tlist_msg . strftime('%H:%M:%S') . ': ' . - \ a:msg . "\n" - endif - endif -endfunction - -" Tlist_Warning_Msg() -" Display a message using WarningMsg highlight group -function! s:Tlist_Warning_Msg(msg) - echohl WarningMsg - echomsg a:msg - echohl None -endfunction - -" Last returned file index for file name lookup. -" Used to speed up file lookup -let s:tlist_file_name_idx_cache = -1 - -" Tlist_Get_File_Index() -" Return the index of the specified filename -function! s:Tlist_Get_File_Index(fname) - if s:tlist_file_count == 0 || a:fname == '' - return -1 - endif - - " If the new filename is same as the last accessed filename, then - " return that index - if s:tlist_file_name_idx_cache != -1 && - \ s:tlist_file_name_idx_cache < s:tlist_file_count - if s:tlist_{s:tlist_file_name_idx_cache}_filename == a:fname - " Same as the last accessed file - return s:tlist_file_name_idx_cache - endif - endif - - " First, check whether the filename is present - let s_fname = a:fname . "\n" - let i = stridx(s:tlist_file_names, s_fname) - if i == -1 - let s:tlist_file_name_idx_cache = -1 - return -1 - endif - - " Second, compute the file name index - let nl_txt = substitute(strpart(s:tlist_file_names, 0, i), "[^\n]", '', 'g') - let s:tlist_file_name_idx_cache = strlen(nl_txt) - return s:tlist_file_name_idx_cache -endfunction - -" Last returned file index for line number lookup. -" Used to speed up file lookup -let s:tlist_file_lnum_idx_cache = -1 - -" Tlist_Window_Get_File_Index_By_Linenum() -" Return the index of the filename present in the specified line number -" Line number refers to the line number in the taglist window -function! s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - call s:Tlist_Log_Msg('Tlist_Window_Get_File_Index_By_Linenum (' . a:lnum . ')') - - " First try to see whether the new line number is within the range - " of the last returned file - if s:tlist_file_lnum_idx_cache != -1 && - \ s:tlist_file_lnum_idx_cache < s:tlist_file_count - if a:lnum >= s:tlist_{s:tlist_file_lnum_idx_cache}_start && - \ a:lnum <= s:tlist_{s:tlist_file_lnum_idx_cache}_end - return s:tlist_file_lnum_idx_cache - endif - endif - - let fidx = -1 - - if g:Tlist_Show_One_File - " Displaying only one file in the taglist window. Check whether - " the line is within the tags displayed for that file - if s:tlist_cur_file_idx != -1 - if a:lnum >= s:tlist_{s:tlist_cur_file_idx}_start - \ && a:lnum <= s:tlist_{s:tlist_cur_file_idx}_end - let fidx = s:tlist_cur_file_idx - endif - - endif - else - " Do a binary search in the taglist - let left = 0 - let right = s:tlist_file_count - 1 - - while left < right - let mid = (left + right) / 2 - - if a:lnum >= s:tlist_{mid}_start && a:lnum <= s:tlist_{mid}_end - let s:tlist_file_lnum_idx_cache = mid - return mid - endif - - if a:lnum < s:tlist_{mid}_start - let right = mid - 1 - else - let left = mid + 1 - endif - endwhile - - if left >= 0 && left < s:tlist_file_count - \ && a:lnum >= s:tlist_{left}_start - \ && a:lnum <= s:tlist_{left}_end - let fidx = left - endif - endif - - let s:tlist_file_lnum_idx_cache = fidx - - return fidx -endfunction - -" Tlist_Exe_Cmd_No_Acmds -" Execute the specified Ex command after disabling autocommands -function! s:Tlist_Exe_Cmd_No_Acmds(cmd) - let old_eventignore = &eventignore - set eventignore=all - exe a:cmd - let &eventignore = old_eventignore -endfunction - -" Tlist_Skip_File() -" Check whether tag listing is supported for the specified file -function! s:Tlist_Skip_File(filename, ftype) - " Skip buffers with no names and buffers with filetype not set - if a:filename == '' || a:ftype == '' - return 1 - endif - - " Skip files which are not supported by exuberant ctags - " First check whether default settings for this filetype are available. - " If it is not available, then check whether user specified settings are - " available. If both are not available, then don't list the tags for this - " filetype - let var = 's:tlist_def_' . a:ftype . '_settings' - if !exists(var) - let var = 'g:tlist_' . a:ftype . '_settings' - if !exists(var) - return 1 - endif - endif - - " Skip files which are not readable or files which are not yet stored - " to the disk - if !filereadable(a:filename) - return 1 - endif - - return 0 -endfunction - -" Tlist_User_Removed_File -" Returns 1 if a file is removed by a user from the taglist -function! s:Tlist_User_Removed_File(filename) - return stridx(s:tlist_removed_flist, a:filename . "\n") != -1 -endfunction - -" Tlist_Update_Remove_List -" Update the list of user removed files from the taglist -" add == 1, add the file to the removed list -" add == 0, delete the file from the removed list -function! s:Tlist_Update_Remove_List(filename, add) - if a:add - let s:tlist_removed_flist = s:tlist_removed_flist . a:filename . "\n" - else - let idx = stridx(s:tlist_removed_flist, a:filename . "\n") - let text_before = strpart(s:tlist_removed_flist, 0, idx) - let rem_text = strpart(s:tlist_removed_flist, idx) - let next_idx = stridx(rem_text, "\n") - let text_after = strpart(rem_text, next_idx + 1) - - let s:tlist_removed_flist = text_before . text_after - endif -endfunction - -" Tlist_FileType_Init -" Initialize the ctags arguments and tag variable for the specified -" file type -function! s:Tlist_FileType_Init(ftype) - call s:Tlist_Log_Msg('Tlist_FileType_Init (' . a:ftype . ')') - " If the user didn't specify any settings, then use the default - " ctags args. Otherwise, use the settings specified by the user - let var = 'g:tlist_' . a:ftype . '_settings' - if exists(var) - " User specified ctags arguments - let settings = {var} . ';' - else - " Default ctags arguments - let var = 's:tlist_def_' . a:ftype . '_settings' - if !exists(var) - " No default settings for this file type. This filetype is - " not supported - return 0 - endif - let settings = s:tlist_def_{a:ftype}_settings . ';' - endif - - let msg = 'Taglist: Invalid ctags option setting - ' . settings - - " Format of the option that specifies the filetype and ctags arugments: - " - " <language_name>;flag1:name1;flag2:name2;flag3:name3 - " - - " Extract the file type to pass to ctags. This may be different from the - " file type detected by Vim - let pos = stridx(settings, ';') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let ctags_ftype = strpart(settings, 0, pos) - if ctags_ftype == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - " Make sure a valid filetype is supplied. If the user didn't specify a - " valid filetype, then the ctags option settings may be treated as the - " filetype - if ctags_ftype =~ ':' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - - " Remove the file type from settings - let settings = strpart(settings, pos + 1) - if settings == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - - " Process all the specified ctags flags. The format is - " flag1:name1;flag2:name2;flag3:name3 - let ctags_flags = '' - let cnt = 0 - while settings != '' - " Extract the flag - let pos = stridx(settings, ':') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let flag = strpart(settings, 0, pos) - if flag == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - " Remove the flag from settings - let settings = strpart(settings, pos + 1) - - " Extract the tag type name - let pos = stridx(settings, ';') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let name = strpart(settings, 0, pos) - if name == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let settings = strpart(settings, pos + 1) - - let cnt = cnt + 1 - - let s:tlist_{a:ftype}_{cnt}_name = flag - let s:tlist_{a:ftype}_{cnt}_fullname = name - let ctags_flags = ctags_flags . flag - endwhile - - let s:tlist_{a:ftype}_ctags_args = '--language-force=' . ctags_ftype . - \ ' --' . ctags_ftype . '-types=' . ctags_flags - let s:tlist_{a:ftype}_count = cnt - let s:tlist_{a:ftype}_ctags_flags = ctags_flags - - " Save the filetype name - let s:tlist_ftype_{s:tlist_ftype_count}_name = a:ftype - let s:tlist_ftype_count = s:tlist_ftype_count + 1 - - return 1 -endfunction - -" Tlist_Detect_Filetype -" Determine the filetype for the specified file using the filetypedetect -" autocmd. -function! s:Tlist_Detect_Filetype(fname) - " Ignore the filetype autocommands - let old_eventignore = &eventignore - set eventignore=FileType - - " Save the 'filetype', as this will be changed temporarily - let old_filetype = &filetype - - " Run the filetypedetect group of autocommands to determine - " the filetype - exe 'doautocmd filetypedetect BufRead ' . a:fname - - " Save the detected filetype - let ftype = &filetype - - " Restore the previous state - let &filetype = old_filetype - let &eventignore = old_eventignore - - return ftype -endfunction - -" Tlist_Get_Buffer_Filetype -" Get the filetype for the specified buffer -function! s:Tlist_Get_Buffer_Filetype(bnum) - let buf_ft = getbufvar(a:bnum, '&filetype') - - if bufloaded(a:bnum) - " For loaded buffers, the 'filetype' is already determined - return buf_ft - endif - - " For unloaded buffers, if the 'filetype' option is set, return it - if buf_ft != '' - return buf_ft - endif - - " Skip non-existent buffers - if !bufexists(a:bnum) - return '' - endif - - " For buffers whose filetype is not yet determined, try to determine - " the filetype - let bname = bufname(a:bnum) - - return s:Tlist_Detect_Filetype(bname) -endfunction - -" Tlist_Discard_TagInfo -" Discard the stored tag information for a file -function! s:Tlist_Discard_TagInfo(fidx) - call s:Tlist_Log_Msg('Tlist_Discard_TagInfo (' . - \ s:tlist_{a:fidx}_filename . ')') - let ftype = s:tlist_{a:fidx}_filetype - - " Discard information about the tags defined in the file - let i = 1 - while i <= s:tlist_{a:fidx}_tag_count - let fidx_i = 's:tlist_' . a:fidx . '_' . i - unlet! {fidx_i}_tag - unlet! {fidx_i}_tag_name - unlet! {fidx_i}_tag_type - unlet! {fidx_i}_ttype_idx - unlet! {fidx_i}_tag_proto - unlet! {fidx_i}_tag_searchpat - unlet! {fidx_i}_tag_linenum - let i = i + 1 - endwhile - - let s:tlist_{a:fidx}_tag_count = 0 - - " Discard information about tag type groups - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - if s:tlist_{a:fidx}_{ttype} != '' - let fidx_ttype = 's:tlist_' . a:fidx . '_' . ttype - let {fidx_ttype} = '' - let {fidx_ttype}_offset = 0 - let cnt = {fidx_ttype}_count - let {fidx_ttype}_count = 0 - let j = 1 - while j <= cnt - unlet! {fidx_ttype}_{j} - let j = j + 1 - endwhile - endif - let i = i + 1 - endwhile - - " Discard the stored menu command also - let s:tlist_{a:fidx}_menu_cmd = '' -endfunction - -" Tlist_Window_Update_Line_Offsets -" Update the line offsets for tags for files starting from start_idx -" and displayed in the taglist window by the specified offset -function! s:Tlist_Window_Update_Line_Offsets(start_idx, increment, offset) - let i = a:start_idx - - while i < s:tlist_file_count - if s:tlist_{i}_visible - " Update the start/end line number only if the file is visible - if a:increment - let s:tlist_{i}_start = s:tlist_{i}_start + a:offset - let s:tlist_{i}_end = s:tlist_{i}_end + a:offset - else - let s:tlist_{i}_start = s:tlist_{i}_start - a:offset - let s:tlist_{i}_end = s:tlist_{i}_end - a:offset - endif - endif - let i = i + 1 - endwhile -endfunction - -" Tlist_Discard_FileInfo -" Discard the stored information for a file -function! s:Tlist_Discard_FileInfo(fidx) - call s:Tlist_Log_Msg('Tlist_Discard_FileInfo (' . - \ s:tlist_{a:fidx}_filename . ')') - call s:Tlist_Discard_TagInfo(a:fidx) - - let ftype = s:tlist_{a:fidx}_filetype - - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - unlet! s:tlist_{a:fidx}_{ttype} - unlet! s:tlist_{a:fidx}_{ttype}_offset - unlet! s:tlist_{a:fidx}_{ttype}_count - let i = i + 1 - endwhile - - unlet! s:tlist_{a:fidx}_filename - unlet! s:tlist_{a:fidx}_sort_type - unlet! s:tlist_{a:fidx}_filetype - unlet! s:tlist_{a:fidx}_mtime - unlet! s:tlist_{a:fidx}_start - unlet! s:tlist_{a:fidx}_end - unlet! s:tlist_{a:fidx}_valid - unlet! s:tlist_{a:fidx}_visible - unlet! s:tlist_{a:fidx}_tag_count - unlet! s:tlist_{a:fidx}_menu_cmd -endfunction - -" Tlist_Window_Remove_File_From_Display -" Remove the specified file from display -function! s:Tlist_Window_Remove_File_From_Display(fidx) - call s:Tlist_Log_Msg('Tlist_Window_Remove_File_From_Display (' . - \ s:tlist_{a:fidx}_filename . ')') - " If the file is not visible then no need to remove it - if !s:tlist_{a:fidx}_visible - return - endif - - " Remove the tags displayed for the specified file from the window - let start = s:tlist_{a:fidx}_start - " Include the empty line after the last line also - if g:Tlist_Compact_Format - let end = s:tlist_{a:fidx}_end - else - let end = s:tlist_{a:fidx}_end + 1 - endif - - setlocal modifiable - exe 'silent! ' . start . ',' . end . 'delete _' - setlocal nomodifiable - - " Correct the start and end line offsets for all the files following - " this file, as the tags for this file are removed - call s:Tlist_Window_Update_Line_Offsets(a:fidx + 1, 0, end - start + 1) -endfunction - -" Tlist_Remove_File -" Remove the file under the cursor or the specified file index -" user_request - User requested to remove the file from taglist -function! s:Tlist_Remove_File(file_idx, user_request) - let fidx = a:file_idx - - if fidx == -1 - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - endif - call s:Tlist_Log_Msg('Tlist_Remove_File (' . - \ s:tlist_{fidx}_filename . ', ' . a:user_request . ')') - - let save_winnr = winnr() - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Taglist window is open, remove the file from display - - if save_winnr != winnum - let old_eventignore = &eventignore - set eventignore=all - exe winnum . 'wincmd w' - endif - - call s:Tlist_Window_Remove_File_From_Display(fidx) - - if save_winnr != winnum - exe save_winnr . 'wincmd w' - let &eventignore = old_eventignore - endif - endif - - let fname = s:tlist_{fidx}_filename - - if a:user_request - " As the user requested to remove the file from taglist, - " add it to the removed list - call s:Tlist_Update_Remove_List(fname, 1) - endif - - " Remove the file name from the taglist list of filenames - let idx = stridx(s:tlist_file_names, fname . "\n") - let text_before = strpart(s:tlist_file_names, 0, idx) - let rem_text = strpart(s:tlist_file_names, idx) - let next_idx = stridx(rem_text, "\n") - let text_after = strpart(rem_text, next_idx + 1) - let s:tlist_file_names = text_before . text_after - - call s:Tlist_Discard_FileInfo(fidx) - - " Shift all the file variables by one index - let i = fidx + 1 - - while i < s:tlist_file_count - let j = i - 1 - - let s:tlist_{j}_filename = s:tlist_{i}_filename - let s:tlist_{j}_sort_type = s:tlist_{i}_sort_type - let s:tlist_{j}_filetype = s:tlist_{i}_filetype - let s:tlist_{j}_mtime = s:tlist_{i}_mtime - let s:tlist_{j}_start = s:tlist_{i}_start - let s:tlist_{j}_end = s:tlist_{i}_end - let s:tlist_{j}_valid = s:tlist_{i}_valid - let s:tlist_{j}_visible = s:tlist_{i}_visible - let s:tlist_{j}_tag_count = s:tlist_{i}_tag_count - let s:tlist_{j}_menu_cmd = s:tlist_{i}_menu_cmd - - let k = 1 - while k <= s:tlist_{j}_tag_count - let s:tlist_{j}_{k}_tag = s:tlist_{i}_{k}_tag - let s:tlist_{j}_{k}_tag_name = s:tlist_{i}_{k}_tag_name - let s:tlist_{j}_{k}_tag_type = s:Tlist_Get_Tag_Type_By_Tag(i, k) - let s:tlist_{j}_{k}_ttype_idx = s:tlist_{i}_{k}_ttype_idx - let s:tlist_{j}_{k}_tag_proto = s:Tlist_Get_Tag_Prototype(i, k) - let s:tlist_{j}_{k}_tag_searchpat = s:Tlist_Get_Tag_SearchPat(i, k) - let s:tlist_{j}_{k}_tag_linenum = s:Tlist_Get_Tag_Linenum(i, k) - let k = k + 1 - endwhile - - let ftype = s:tlist_{i}_filetype - - let k = 1 - while k <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{k}_name - let s:tlist_{j}_{ttype} = s:tlist_{i}_{ttype} - let s:tlist_{j}_{ttype}_offset = s:tlist_{i}_{ttype}_offset - let s:tlist_{j}_{ttype}_count = s:tlist_{i}_{ttype}_count - if s:tlist_{j}_{ttype} != '' - let l = 1 - while l <= s:tlist_{j}_{ttype}_count - let s:tlist_{j}_{ttype}_{l} = s:tlist_{i}_{ttype}_{l} - let l = l + 1 - endwhile - endif - let k = k + 1 - endwhile - - " As the file and tag information is copied to the new index, - " discard the previous information - call s:Tlist_Discard_FileInfo(i) - - let i = i + 1 - endwhile - - " Reduce the number of files displayed - let s:tlist_file_count = s:tlist_file_count - 1 - - if g:Tlist_Show_One_File - " If the tags for only one file is displayed and if we just - " now removed that file, then invalidate the current file idx - if s:tlist_cur_file_idx == fidx - let s:tlist_cur_file_idx = -1 - endif - endif -endfunction - -" Tlist_Window_Goto_Window -" Goto the taglist window -function! s:Tlist_Window_Goto_Window() - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - if winnr() != winnum - call s:Tlist_Exe_Cmd_No_Acmds(winnum . 'wincmd w') - endif - endif -endfunction - -" Tlist_Window_Create -" Create a new taglist window. If it is already open, jump to it -function! s:Tlist_Window_Create() - call s:Tlist_Log_Msg('Tlist_Window_Create()') - " If the window is open, jump to it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Jump to the existing window - if winnr() != winnum - exe winnum . 'wincmd w' - endif - return - endif - - " If used with winmanager don't open windows. Winmanager will handle - " the window/buffer management - if s:tlist_app_name == "winmanager" - return - endif - - " Create a new window. If user prefers a horizontal window, then open - " a horizontally split window. Otherwise open a vertically split - " window - if g:Tlist_Use_Horiz_Window - " Open a horizontally split window - let win_dir = 'botright' - " Horizontal window height - let win_size = g:Tlist_WinHeight - else - if s:tlist_winsize_chgd == -1 - " Open a vertically split window. Increase the window size, if - " needed, to accomodate the new window - if g:Tlist_Inc_Winwidth && - \ &columns < (80 + g:Tlist_WinWidth) - " Save the original window position - let s:tlist_pre_winx = getwinposx() - let s:tlist_pre_winy = getwinposy() - - " one extra column is needed to include the vertical split - let &columns= &columns + g:Tlist_WinWidth + 1 - - let s:tlist_winsize_chgd = 1 - else - let s:tlist_winsize_chgd = 0 - endif - endif - - if g:Tlist_Use_Right_Window - " Open the window at the rightmost place - let win_dir = 'botright vertical' - else - " Open the window at the leftmost place - let win_dir = 'topleft vertical' - endif - let win_size = g:Tlist_WinWidth - endif - - " If the tag listing temporary buffer already exists, then reuse it. - " Otherwise create a new buffer - let bufnum = bufnr(g:TagList_title) - if bufnum == -1 - " Create a new buffer - let wcmd = g:TagList_title - else - " Edit the existing buffer - let wcmd = '+buffer' . bufnum - endif - - " Create the taglist window - exe 'silent! ' . win_dir . ' ' . win_size . 'split ' . wcmd - - " Save the new window position - let s:tlist_winx = getwinposx() - let s:tlist_winy = getwinposy() - - " Initialize the taglist window - call s:Tlist_Window_Init() -endfunction - -" Tlist_Window_Zoom -" Zoom (maximize/minimize) the taglist window -function! s:Tlist_Window_Zoom() - if s:tlist_win_maximized - " Restore the window back to the previous size - if g:Tlist_Use_Horiz_Window - exe 'resize ' . g:Tlist_WinHeight - else - exe 'vert resize ' . g:Tlist_WinWidth - endif - let s:tlist_win_maximized = 0 - else - " Set the window size to the maximum possible without closing other - " windows - if g:Tlist_Use_Horiz_Window - resize - else - vert resize - endif - let s:tlist_win_maximized = 1 - endif -endfunction - -" Tlist_Ballon_Expr -" When the mouse cursor is over a tag in the taglist window, display the -" tag prototype (balloon) -function! Tlist_Ballon_Expr() - " Get the file index - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(v:beval_lnum) - if fidx == -1 - return '' - endif - - " Get the tag output line for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, v:beval_lnum) - if tidx == 0 - return '' - endif - - " Get the tag search pattern and display it - return s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Window_Check_Width -" Check the width of the taglist window. For horizontally split windows, the -" 'winfixheight' option is used to fix the height of the window. For -" vertically split windows, Vim doesn't support the 'winfixwidth' option. So -" need to handle window width changes from this function. -function! s:Tlist_Window_Check_Width() - let tlist_winnr = bufwinnr(g:TagList_title) - if tlist_winnr == -1 - return - endif - - let width = winwidth(tlist_winnr) - if width != g:Tlist_WinWidth - call s:Tlist_Log_Msg("Tlist_Window_Check_Width: Changing window " . - \ "width from " . width . " to " . g:Tlist_WinWidth) - let save_winnr = winnr() - if save_winnr != tlist_winnr - call s:Tlist_Exe_Cmd_No_Acmds(tlist_winnr . 'wincmd w') - endif - exe 'vert resize ' . g:Tlist_WinWidth - if save_winnr != tlist_winnr - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - endif -endfunction - -" Tlist_Window_Exit_Only_Window -" If the 'Tlist_Exit_OnlyWindow' option is set, then exit Vim if only the -" taglist window is present. -function! s:Tlist_Window_Exit_Only_Window() - " Before quitting Vim, delete the taglist buffer so that - " the '0 mark is correctly set to the previous buffer. - if v:version < 700 - if winbufnr(2) == -1 - bdelete - quit - endif - else - if winbufnr(2) == -1 - if tabpagenr('$') == 1 - " Only one tag page is present - bdelete - quit - else - " More than one tab page is present. Close only the current - " tab page - close - endif - endif - endif -endfunction - -" Tlist_Window_Init -" Set the default options for the taglist window -function! s:Tlist_Window_Init() - call s:Tlist_Log_Msg('Tlist_Window_Init()') - - " The 'readonly' option should not be set for the taglist buffer. - " If Vim is started as "view/gview" or if the ":view" command is - " used, then the 'readonly' option is set for all the buffers. - " Unset it for the taglist buffer - setlocal noreadonly - - " Set the taglist buffer filetype to taglist - setlocal filetype=taglist - - " Define taglist window element highlighting - syntax match TagListComment '^" .*' - syntax match TagListFileName '^[^" ].*$' - syntax match TagListTitle '^ \S.*$' - syntax match TagListTagScope '\s\[.\{-\}\]$' - - " Define the highlighting only if colors are supported - if has('gui_running') || &t_Co > 2 - " Colors to highlight various taglist window elements - " If user defined highlighting group exists, then use them. - " Otherwise, use default highlight groups. - if hlexists('MyTagListTagName') - highlight link TagListTagName MyTagListTagName - else - highlight default link TagListTagName Search - endif - " Colors to highlight comments and titles - if hlexists('MyTagListComment') - highlight link TagListComment MyTagListComment - else - highlight clear TagListComment - highlight default link TagListComment Comment - endif - if hlexists('MyTagListTitle') - highlight link TagListTitle MyTagListTitle - else - highlight clear TagListTitle - highlight default link TagListTitle Title - endif - if hlexists('MyTagListFileName') - highlight link TagListFileName MyTagListFileName - else - highlight clear TagListFileName - highlight default TagListFileName guibg=Grey ctermbg=darkgray - \ guifg=white ctermfg=white - endif - if hlexists('MyTagListTagScope') - highlight link TagListTagScope MyTagListTagScope - else - highlight clear TagListTagScope - highlight default link TagListTagScope Identifier - endif - else - highlight default TagListTagName term=reverse cterm=reverse - endif - - " Folding related settings - setlocal foldenable - setlocal foldminlines=0 - setlocal foldmethod=manual - setlocal foldlevel=9999 - if g:Tlist_Enable_Fold_Column - setlocal foldcolumn=3 - else - setlocal foldcolumn=0 - endif - setlocal foldtext=v:folddashes.getline(v:foldstart) - - if s:tlist_app_name != "winmanager" - " Mark buffer as scratch - silent! setlocal buftype=nofile - if s:tlist_app_name == "none" - silent! setlocal bufhidden=delete - endif - silent! setlocal noswapfile - " Due to a bug in Vim 6.0, the winbufnr() function fails for unlisted - " buffers. So if the taglist buffer is unlisted, multiple taglist - " windows will be opened. This bug is fixed in Vim 6.1 and above - if v:version >= 601 - silent! setlocal nobuflisted - endif - endif - - silent! setlocal nowrap - - " If the 'number' option is set in the source window, it will affect the - " taglist window. So forcefully disable 'number' option for the taglist - " window - silent! setlocal nonumber - - " Use fixed height when horizontally split window is used - if g:Tlist_Use_Horiz_Window - if v:version >= 602 - set winfixheight - endif - endif - if !g:Tlist_Use_Horiz_Window && v:version >= 700 - set winfixwidth - endif - - " Setup balloon evaluation to display tag prototype - if v:version >= 700 && has('balloon_eval') - setlocal balloonexpr=Tlist_Ballon_Expr() - set ballooneval - endif - - " Setup the cpoptions properly for the maps to work - let old_cpoptions = &cpoptions - set cpoptions&vim - - " Create buffer local mappings for jumping to the tags and sorting the list - nnoremap <buffer> <silent> <CR> - \ :call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - nnoremap <buffer> <silent> o - \ :call <SID>Tlist_Window_Jump_To_Tag('newwin')<CR> - nnoremap <buffer> <silent> p - \ :call <SID>Tlist_Window_Jump_To_Tag('preview')<CR> - nnoremap <buffer> <silent> P - \ :call <SID>Tlist_Window_Jump_To_Tag('prevwin')<CR> - if v:version >= 700 - nnoremap <buffer> <silent> t - \ :call <SID>Tlist_Window_Jump_To_Tag('checktab')<CR> - nnoremap <buffer> <silent> <C-t> - \ :call <SID>Tlist_Window_Jump_To_Tag('newtab')<CR> - endif - nnoremap <buffer> <silent> <2-LeftMouse> - \ :call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - nnoremap <buffer> <silent> s - \ :call <SID>Tlist_Change_Sort('cmd', 'toggle', '')<CR> - nnoremap <buffer> <silent> + :silent! foldopen<CR> - nnoremap <buffer> <silent> - :silent! foldclose<CR> - nnoremap <buffer> <silent> * :silent! %foldopen!<CR> - nnoremap <buffer> <silent> = :silent! %foldclose<CR> - nnoremap <buffer> <silent> <kPlus> :silent! foldopen<CR> - nnoremap <buffer> <silent> <kMinus> :silent! foldclose<CR> - nnoremap <buffer> <silent> <kMultiply> :silent! %foldopen!<CR> - nnoremap <buffer> <silent> <Space> :call <SID>Tlist_Window_Show_Info()<CR> - nnoremap <buffer> <silent> u :call <SID>Tlist_Window_Update_File()<CR> - nnoremap <buffer> <silent> d :call <SID>Tlist_Remove_File(-1, 1)<CR> - nnoremap <buffer> <silent> x :call <SID>Tlist_Window_Zoom()<CR> - nnoremap <buffer> <silent> [[ :call <SID>Tlist_Window_Move_To_File(-1)<CR> - nnoremap <buffer> <silent> <BS> :call <SID>Tlist_Window_Move_To_File(-1)<CR> - nnoremap <buffer> <silent> ]] :call <SID>Tlist_Window_Move_To_File(1)<CR> - nnoremap <buffer> <silent> <Tab> :call <SID>Tlist_Window_Move_To_File(1)<CR> - nnoremap <buffer> <silent> <F1> :call <SID>Tlist_Window_Toggle_Help_Text()<CR> - nnoremap <buffer> <silent> q :close<CR> - - " Insert mode mappings - inoremap <buffer> <silent> <CR> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - " Windows needs return - inoremap <buffer> <silent> <Return> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - inoremap <buffer> <silent> o - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('newwin')<CR> - inoremap <buffer> <silent> p - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('preview')<CR> - inoremap <buffer> <silent> P - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('prevwin')<CR> - if v:version >= 700 - inoremap <buffer> <silent> t - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('checktab')<CR> - inoremap <buffer> <silent> <C-t> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('newtab')<CR> - endif - inoremap <buffer> <silent> <2-LeftMouse> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - inoremap <buffer> <silent> s - \ <C-o>:call <SID>Tlist_Change_Sort('cmd', 'toggle', '')<CR> - inoremap <buffer> <silent> + <C-o>:silent! foldopen<CR> - inoremap <buffer> <silent> - <C-o>:silent! foldclose<CR> - inoremap <buffer> <silent> * <C-o>:silent! %foldopen!<CR> - inoremap <buffer> <silent> = <C-o>:silent! %foldclose<CR> - inoremap <buffer> <silent> <kPlus> <C-o>:silent! foldopen<CR> - inoremap <buffer> <silent> <kMinus> <C-o>:silent! foldclose<CR> - inoremap <buffer> <silent> <kMultiply> <C-o>:silent! %foldopen!<CR> - inoremap <buffer> <silent> <Space> <C-o>:call - \ <SID>Tlist_Window_Show_Info()<CR> - inoremap <buffer> <silent> u - \ <C-o>:call <SID>Tlist_Window_Update_File()<CR> - inoremap <buffer> <silent> d <C-o>:call <SID>Tlist_Remove_File(-1, 1)<CR> - inoremap <buffer> <silent> x <C-o>:call <SID>Tlist_Window_Zoom()<CR> - inoremap <buffer> <silent> [[ <C-o>:call <SID>Tlist_Window_Move_To_File(-1)<CR> - inoremap <buffer> <silent> <BS> <C-o>:call <SID>Tlist_Window_Move_To_File(-1)<CR> - inoremap <buffer> <silent> ]] <C-o>:call <SID>Tlist_Window_Move_To_File(1)<CR> - inoremap <buffer> <silent> <Tab> <C-o>:call <SID>Tlist_Window_Move_To_File(1)<CR> - inoremap <buffer> <silent> <F1> <C-o>:call <SID>Tlist_Window_Toggle_Help_Text()<CR> - inoremap <buffer> <silent> q <C-o>:close<CR> - - " Map single left mouse click if the user wants this functionality - if g:Tlist_Use_SingleClick == 1 - " Contributed by Bindu Wavell - " attempt to perform single click mapping, it would be much - " nicer if we could nnoremap <buffer> ... however vim does - " not fire the <buffer> <leftmouse> when you use the mouse - " to enter a buffer. - let clickmap = ':if bufname("%") =~ "__Tag_List__" <bar> ' . - \ 'call <SID>Tlist_Window_Jump_To_Tag("useopen") ' . - \ '<bar> endif <CR>' - if maparg('<leftmouse>', 'n') == '' - " no mapping for leftmouse - exe ':nnoremap <silent> <leftmouse> <leftmouse>' . clickmap - else - " we have a mapping - let mapcmd = ':nnoremap <silent> <leftmouse> <leftmouse>' - let mapcmd = mapcmd . substitute(substitute( - \ maparg('<leftmouse>', 'n'), '|', '<bar>', 'g'), - \ '\c^<leftmouse>', '', '') - let mapcmd = mapcmd . clickmap - exe mapcmd - endif - endif - - " Define the taglist autocommands - augroup TagListAutoCmds - autocmd! - " Display the tag prototype for the tag under the cursor. - autocmd CursorHold __Tag_List__ call s:Tlist_Window_Show_Info() - " Highlight the current tag periodically - autocmd CursorHold * silent call s:Tlist_Window_Highlight_Tag( - \ fnamemodify(bufname('%'), ':p'), line('.'), 1, 0) - - " Adjust the Vim window width when taglist window is closed - autocmd BufUnload __Tag_List__ call s:Tlist_Post_Close_Cleanup() - " Close the fold for this buffer when leaving the buffer - if g:Tlist_File_Fold_Auto_Close - autocmd BufEnter * silent - \ call s:Tlist_Window_Open_File_Fold(expand('<abuf>')) - endif - " Exit Vim itself if only the taglist window is present (optional) - if g:Tlist_Exit_OnlyWindow - autocmd BufEnter __Tag_List__ nested - \ call s:Tlist_Window_Exit_Only_Window() - endif - if s:tlist_app_name != "winmanager" && - \ !g:Tlist_Process_File_Always && - \ (!has('gui_running') || !g:Tlist_Show_Menu) - " Auto refresh the taglist window - autocmd BufEnter * call s:Tlist_Refresh() - endif - - if !g:Tlist_Use_Horiz_Window - if v:version < 700 - autocmd WinEnter * call s:Tlist_Window_Check_Width() - endif - endif - if v:version >= 700 - autocmd TabEnter * silent call s:Tlist_Refresh_Folds() - endif - augroup end - - " Restore the previous cpoptions settings - let &cpoptions = old_cpoptions -endfunction - -" Tlist_Window_Refresh -" Display the tags for all the files in the taglist window -function! s:Tlist_Window_Refresh() - call s:Tlist_Log_Msg('Tlist_Window_Refresh()') - " Set report option to a huge value to prevent informational messages - " while deleting the lines - let old_report = &report - set report=99999 - - " Mark the buffer as modifiable - setlocal modifiable - - " Delete the contents of the buffer to the black-hole register - silent! %delete _ - - " As we have cleared the taglist window, mark all the files - " as not visible - let i = 0 - while i < s:tlist_file_count - let s:tlist_{i}_visible = 0 - let i = i + 1 - endwhile - - if g:Tlist_Compact_Format == 0 - " Display help in non-compact mode - call s:Tlist_Window_Display_Help() - endif - - " Mark the buffer as not modifiable - setlocal nomodifiable - - " Restore the report option - let &report = old_report - - " If the tags for only one file should be displayed in the taglist - " window, then no need to add the tags here. The bufenter autocommand - " will add the tags for that file. - if g:Tlist_Show_One_File - return - endif - - " List all the tags for the previously processed files - " Do this only if taglist is configured to display tags for more than - " one file. Otherwise, when Tlist_Show_One_File is configured, - " tags for the wrong file will be displayed. - let i = 0 - while i < s:tlist_file_count - call s:Tlist_Window_Refresh_File(s:tlist_{i}_filename, - \ s:tlist_{i}_filetype) - let i = i + 1 - endwhile - - if g:Tlist_Auto_Update - " Add and list the tags for all buffers in the Vim buffer list - let i = 1 - let last_bufnum = bufnr('$') - while i <= last_bufnum - if buflisted(i) - let fname = fnamemodify(bufname(i), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype(i) - " If the file doesn't support tag listing, skip it - if !s:Tlist_Skip_File(fname, ftype) - call s:Tlist_Window_Refresh_File(fname, ftype) - endif - endif - let i = i + 1 - endwhile - endif - - " If Tlist_File_Fold_Auto_Close option is set, then close all the folds - if g:Tlist_File_Fold_Auto_Close - " Close all the folds - silent! %foldclose - endif - - " Move the cursor to the top of the taglist window - normal! gg -endfunction - -" Tlist_Post_Close_Cleanup() -" Close the taglist window and adjust the Vim window width -function! s:Tlist_Post_Close_Cleanup() - call s:Tlist_Log_Msg('Tlist_Post_Close_Cleanup()') - " Mark all the files as not visible - let i = 0 - while i < s:tlist_file_count - let s:tlist_{i}_visible = 0 - let i = i + 1 - endwhile - - " Remove the taglist autocommands - silent! autocmd! TagListAutoCmds - - " Clear all the highlights - match none - - silent! syntax clear TagListTitle - silent! syntax clear TagListComment - silent! syntax clear TagListTagScope - - " Remove the left mouse click mapping if it was setup initially - if g:Tlist_Use_SingleClick - if hasmapto('<LeftMouse>') - nunmap <LeftMouse> - endif - endif - - if s:tlist_app_name != "winmanager" - if g:Tlist_Use_Horiz_Window || g:Tlist_Inc_Winwidth == 0 || - \ s:tlist_winsize_chgd != 1 || - \ &columns < (80 + g:Tlist_WinWidth) - " No need to adjust window width if using horizontally split taglist - " window or if columns is less than 101 or if the user chose not to - " adjust the window width - else - " If the user didn't manually move the window, then restore the window - " position to the pre-taglist position - if s:tlist_pre_winx != -1 && s:tlist_pre_winy != -1 && - \ getwinposx() == s:tlist_winx && - \ getwinposy() == s:tlist_winy - exe 'winpos ' . s:tlist_pre_winx . ' ' . s:tlist_pre_winy - endif - - " Adjust the Vim window width - let &columns= &columns - (g:Tlist_WinWidth + 1) - endif - endif - - let s:tlist_winsize_chgd = -1 - - " Reset taglist state variables - if s:tlist_app_name == "winmanager" - let s:tlist_app_name = "none" - endif - let s:tlist_window_initialized = 0 -endfunction - -" Tlist_Window_Refresh_File() -" List the tags defined in the specified file in a Vim window -function! s:Tlist_Window_Refresh_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Window_Refresh_File (' . a:filename . ')') - " First check whether the file already exists - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx != -1 - let file_listed = 1 - else - let file_listed = 0 - endif - - if !file_listed - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(a:filename) - return - endif - endif - - if file_listed && s:tlist_{fidx}_visible - " Check whether the file tags are currently valid - if s:tlist_{fidx}_valid - " Goto the first line in the file - exe s:tlist_{fidx}_start - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - endif - return - endif - - " Discard and remove the tags for this file from display - call s:Tlist_Discard_TagInfo(fidx) - call s:Tlist_Window_Remove_File_From_Display(fidx) - endif - - " Process and generate a list of tags defined in the file - if !file_listed || !s:tlist_{fidx}_valid - let ret_fidx = s:Tlist_Process_File(a:filename, a:ftype) - if ret_fidx == -1 - return - endif - let fidx = ret_fidx - endif - - " Set report option to a huge value to prevent informational messages - " while adding lines to the taglist window - let old_report = &report - set report=99999 - - if g:Tlist_Show_One_File - " Remove the previous file - if s:tlist_cur_file_idx != -1 - call s:Tlist_Window_Remove_File_From_Display(s:tlist_cur_file_idx) - let s:tlist_{s:tlist_cur_file_idx}_visible = 0 - let s:tlist_{s:tlist_cur_file_idx}_start = 0 - let s:tlist_{s:tlist_cur_file_idx}_end = 0 - endif - let s:tlist_cur_file_idx = fidx - endif - - " Mark the buffer as modifiable - setlocal modifiable - - " Add new files to the end of the window. For existing files, add them at - " the same line where they were previously present. If the file is not - " visible, then add it at the end - if s:tlist_{fidx}_start == 0 || !s:tlist_{fidx}_visible - if g:Tlist_Compact_Format - let s:tlist_{fidx}_start = line('$') - else - let s:tlist_{fidx}_start = line('$') + 1 - endif - endif - - let s:tlist_{fidx}_visible = 1 - - " Goto the line where this file should be placed - if g:Tlist_Compact_Format - exe s:tlist_{fidx}_start - else - exe s:tlist_{fidx}_start - 1 - endif - - let txt = fnamemodify(s:tlist_{fidx}_filename, ':t') . ' (' . - \ fnamemodify(s:tlist_{fidx}_filename, ':p:h') . ')' - if g:Tlist_Compact_Format == 0 - silent! put =txt - else - silent! put! =txt - " Move to the next line - exe line('.') + 1 - endif - let file_start = s:tlist_{fidx}_start - - " Add the tag names grouped by tag type to the buffer with a title - let i = 1 - let ttype_cnt = s:tlist_{a:ftype}_count - while i <= ttype_cnt - let ttype = s:tlist_{a:ftype}_{i}_name - " Add the tag type only if there are tags for that type - let fidx_ttype = 's:tlist_' . fidx . '_' . ttype - let ttype_txt = {fidx_ttype} - if ttype_txt != '' - let txt = ' ' . s:tlist_{a:ftype}_{i}_fullname - if g:Tlist_Compact_Format == 0 - let ttype_start_lnum = line('.') + 1 - silent! put =txt - else - let ttype_start_lnum = line('.') - silent! put! =txt - endif - silent! put =ttype_txt - - let {fidx_ttype}_offset = ttype_start_lnum - file_start - - " create a fold for this tag type - let fold_start = ttype_start_lnum - let fold_end = fold_start + {fidx_ttype}_count - exe fold_start . ',' . fold_end . 'fold' - - " Adjust the cursor position - if g:Tlist_Compact_Format == 0 - exe ttype_start_lnum + {fidx_ttype}_count - else - exe ttype_start_lnum + {fidx_ttype}_count + 1 - endif - - if g:Tlist_Compact_Format == 0 - " Separate the tag types by a empty line - silent! put ='' - endif - endif - let i = i + 1 - endwhile - - if s:tlist_{fidx}_tag_count == 0 - if g:Tlist_Compact_Format == 0 - silent! put ='' - endif - endif - - let s:tlist_{fidx}_end = line('.') - 1 - - " Create a fold for the entire file - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'fold' - exe 'silent! ' . s:tlist_{fidx}_start . ',' . - \ s:tlist_{fidx}_end . 'foldopen!' - - " Goto the starting line for this file, - exe s:tlist_{fidx}_start - - if s:tlist_app_name == "winmanager" - " To handle a bug in the winmanager plugin, add a space at the - " last line - call setline('$', ' ') - endif - - " Mark the buffer as not modifiable - setlocal nomodifiable - - " Restore the report option - let &report = old_report - - " Update the start and end line numbers for all the files following this - " file - let start = s:tlist_{fidx}_start - " include the empty line after the last line - if g:Tlist_Compact_Format - let end = s:tlist_{fidx}_end - else - let end = s:tlist_{fidx}_end + 1 - endif - call s:Tlist_Window_Update_Line_Offsets(fidx + 1, 1, end - start + 1) - - " Now that we have updated the taglist window, update the tags - " menu (if present) - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(1) - endif -endfunction - -" Tlist_Init_File -" Initialize the variables for a new file -function! s:Tlist_Init_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Init_File (' . a:filename . ')') - " Add new files at the end of the list - let fidx = s:tlist_file_count - let s:tlist_file_count = s:tlist_file_count + 1 - " Add the new file name to the taglist list of file names - let s:tlist_file_names = s:tlist_file_names . a:filename . "\n" - - " Initialize the file variables - let s:tlist_{fidx}_filename = a:filename - let s:tlist_{fidx}_sort_type = g:Tlist_Sort_Type - let s:tlist_{fidx}_filetype = a:ftype - let s:tlist_{fidx}_mtime = -1 - let s:tlist_{fidx}_start = 0 - let s:tlist_{fidx}_end = 0 - let s:tlist_{fidx}_valid = 0 - let s:tlist_{fidx}_visible = 0 - let s:tlist_{fidx}_tag_count = 0 - let s:tlist_{fidx}_menu_cmd = '' - - " Initialize the tag type variables - let i = 1 - while i <= s:tlist_{a:ftype}_count - let ttype = s:tlist_{a:ftype}_{i}_name - let s:tlist_{fidx}_{ttype} = '' - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = 0 - let i = i + 1 - endwhile - - return fidx -endfunction - -" Tlist_Get_Tag_Type_By_Tag -" Return the tag type for the specified tag index -function! s:Tlist_Get_Tag_Type_By_Tag(fidx, tidx) - let ttype_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_type' - - " Already parsed and have the tag name - if exists(ttype_var) - return {ttype_var} - endif - - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let {ttype_var} = s:Tlist_Extract_Tagtype(tag_line) - - return {ttype_var} -endfunction - -" Tlist_Get_Tag_Prototype -function! s:Tlist_Get_Tag_Prototype(fidx, tidx) - let tproto_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_proto' - - " Already parsed and have the tag prototype - if exists(tproto_var) - return {tproto_var} - endif - - " Parse and extract the tag prototype - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = stridx(tag_line, '/^') + 2 - let end = stridx(tag_line, '/;"' . "\t") - if tag_line[end - 1] == '$' - let end = end -1 - endif - let tag_proto = strpart(tag_line, start, end - start) - let {tproto_var} = substitute(tag_proto, '\s*', '', '') - - return {tproto_var} -endfunction - -" Tlist_Get_Tag_SearchPat -function! s:Tlist_Get_Tag_SearchPat(fidx, tidx) - let tpat_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_searchpat' - - " Already parsed and have the tag search pattern - if exists(tpat_var) - return {tpat_var} - endif - - " Parse and extract the tag search pattern - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = stridx(tag_line, '/^') + 2 - let end = stridx(tag_line, '/;"' . "\t") - if tag_line[end - 1] == '$' - let end = end -1 - endif - let {tpat_var} = '\V\^' . strpart(tag_line, start, end - start) . - \ (tag_line[end] == '$' ? '\$' : '') - - return {tpat_var} -endfunction - -" Tlist_Get_Tag_Linenum -" Return the tag line number, given the tag index -function! s:Tlist_Get_Tag_Linenum(fidx, tidx) - let tline_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_linenum' - - " Already parsed and have the tag line number - if exists(tline_var) - return {tline_var} - endif - - " Parse and extract the tag line number - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = strridx(tag_line, 'line:') + 5 - let end = strridx(tag_line, "\t") - if end < start - let {tline_var} = strpart(tag_line, start) + 0 - else - let {tline_var} = strpart(tag_line, start, end - start) + 0 - endif - - return {tline_var} -endfunction - -" Tlist_Parse_Tagline -" Parse a tag line from the ctags output. Separate the tag output based on the -" tag type and store it in the tag type variable. -" The format of each line in the ctags output is: -" -" tag_name<TAB>file_name<TAB>ex_cmd;"<TAB>extension_fields -" -function! s:Tlist_Parse_Tagline(tag_line) - if a:tag_line == '' - " Skip empty lines - return - endif - - " Extract the tag type - let ttype = s:Tlist_Extract_Tagtype(a:tag_line) - - " Make sure the tag type is a valid and supported one - if ttype == '' || stridx(s:ctags_flags, ttype) == -1 - " Line is not in proper tags format or Tag type is not supported - return - endif - - " Update the total tag count - let s:tidx = s:tidx + 1 - - " The following variables are used to optimize this code. Vim is slow in - " using curly brace names. To reduce the amount of processing needed, the - " curly brace variables are pre-processed here - let fidx_tidx = 's:tlist_' . s:fidx . '_' . s:tidx - let fidx_ttype = 's:tlist_' . s:fidx . '_' . ttype - - " Update the count of this tag type - let ttype_idx = {fidx_ttype}_count + 1 - let {fidx_ttype}_count = ttype_idx - - " Store the ctags output for this tag - let {fidx_tidx}_tag = a:tag_line - - " Store the tag index and the tag type index (back pointers) - let {fidx_ttype}_{ttype_idx} = s:tidx - let {fidx_tidx}_ttype_idx = ttype_idx - - " Extract the tag name - let tag_name = strpart(a:tag_line, 0, stridx(a:tag_line, "\t")) - - " Extract the tag scope/prototype - if g:Tlist_Display_Prototype - let ttxt = ' ' . s:Tlist_Get_Tag_Prototype(s:fidx, s:tidx) - else - let ttxt = ' ' . tag_name - - " Add the tag scope, if it is available and is configured. Tag - " scope is the last field after the 'line:<num>\t' field - if g:Tlist_Display_Tag_Scope - let tag_scope = s:Tlist_Extract_Tag_Scope(a:tag_line) - if tag_scope != '' - let ttxt = ttxt . ' [' . tag_scope . ']' - endif - endif - endif - - " Add this tag to the tag type variable - let {fidx_ttype} = {fidx_ttype} . ttxt . "\n" - - " Save the tag name - let {fidx_tidx}_tag_name = tag_name -endfunction - -" Tlist_Process_File -" Get the list of tags defined in the specified file and store them -" in Vim variables. Returns the file index where the tags are stored. -function! s:Tlist_Process_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Process_File (' . a:filename . ', ' . - \ a:ftype . ')') - " Check whether this file is supported - if s:Tlist_Skip_File(a:filename, a:ftype) - return -1 - endif - - " If the tag types for this filetype are not yet created, then create - " them now - let var = 's:tlist_' . a:ftype . '_count' - if !exists(var) - if s:Tlist_FileType_Init(a:ftype) == 0 - return -1 - endif - endif - - " If this file is already processed, then use the cached values - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - " First time, this file is loaded - let fidx = s:Tlist_Init_File(a:filename, a:ftype) - else - " File was previously processed. Discard the tag information - call s:Tlist_Discard_TagInfo(fidx) - endif - - let s:tlist_{fidx}_valid = 1 - - " Exuberant ctags arguments to generate a tag list - let ctags_args = ' -f - --format=2 --excmd=pattern --fields=nks ' - - " Form the ctags argument depending on the sort type - if s:tlist_{fidx}_sort_type == 'name' - let ctags_args = ctags_args . '--sort=yes' - else - let ctags_args = ctags_args . '--sort=no' - endif - - " Add the filetype specific arguments - let ctags_args = ctags_args . ' ' . s:tlist_{a:ftype}_ctags_args - - " Ctags command to produce output with regexp for locating the tags - let ctags_cmd = g:Tlist_Ctags_Cmd . ctags_args - let ctags_cmd = ctags_cmd . ' "' . a:filename . '"' - - if &shellxquote == '"' - " Double-quotes within double-quotes will not work in the - " command-line.If the 'shellxquote' option is set to double-quotes, - " then escape the double-quotes in the ctags command-line. - let ctags_cmd = escape(ctags_cmd, '"') - endif - - " In Windows 95, if not using cygwin, disable the 'shellslash' - " option. Otherwise, this will cause problems when running the - " ctags command. - if has('win95') && !has('win32unix') - let old_shellslash = &shellslash - set noshellslash - endif - - if has('win32') && !has('win32unix') && !has('win95') - \ && (&shell =~ 'cmd.exe') - " Windows does not correctly deal with commands that have more than 1 - " set of double quotes. It will strip them all resulting in: - " 'C:\Program' is not recognized as an internal or external command - " operable program or batch file. To work around this, place the - " command inside a batch file and call the batch file. - " Do this only on Win2K, WinXP and above. - " Contributed by: David Fishburn. - let s:taglist_tempfile = fnamemodify(tempname(), ':h') . - \ '\taglist.cmd' - exe 'redir! > ' . s:taglist_tempfile - silent echo ctags_cmd - redir END - - call s:Tlist_Log_Msg('Cmd inside batch file: ' . ctags_cmd) - let ctags_cmd = '"' . s:taglist_tempfile . '"' - endif - - call s:Tlist_Log_Msg('Cmd: ' . ctags_cmd) - - " Run ctags and get the tag list - let cmd_output = system(ctags_cmd) - - " Restore the value of the 'shellslash' option. - if has('win95') && !has('win32unix') - let &shellslash = old_shellslash - endif - - if exists('s:taglist_tempfile') - " Delete the temporary cmd file created on MS-Windows - call delete(s:taglist_tempfile) - endif - - " Handle errors - if v:shell_error - let msg = "Taglist: Failed to generate tags for " . a:filename - call s:Tlist_Warning_Msg(msg) - if cmd_output != '' - call s:Tlist_Warning_Msg(cmd_output) - endif - return fidx - endif - - " Store the modification time for the file - let s:tlist_{fidx}_mtime = getftime(a:filename) - - " No tags for current file - if cmd_output == '' - call s:Tlist_Log_Msg('No tags defined in ' . a:filename) - return fidx - endif - - call s:Tlist_Log_Msg('Generated tags information for ' . a:filename) - - if v:version > 601 - " The following script local variables are used by the - " Tlist_Parse_Tagline() function. - let s:ctags_flags = s:tlist_{a:ftype}_ctags_flags - let s:fidx = fidx - let s:tidx = 0 - - " Process the ctags output one line at a time. The substitute() - " command is used to parse the tag lines instead of using the - " matchstr()/stridx()/strpart() functions for performance reason - call substitute(cmd_output, "\\([^\n]\\+\\)\n", - \ '\=s:Tlist_Parse_Tagline(submatch(1))', 'g') - - " Save the number of tags for this file - let s:tlist_{fidx}_tag_count = s:tidx - - " The following script local variables are no longer needed - unlet! s:ctags_flags - unlet! s:tidx - unlet! s:fidx - else - " Due to a bug in Vim earlier than version 6.1, - " we cannot use substitute() to parse the ctags output. - " Instead the slow str*() functions are used - let ctags_flags = s:tlist_{a:ftype}_ctags_flags - let tidx = 0 - - while cmd_output != '' - " Extract one line at a time - let idx = stridx(cmd_output, "\n") - let one_line = strpart(cmd_output, 0, idx) - " Remove the line from the tags output - let cmd_output = strpart(cmd_output, idx + 1) - - if one_line == '' - " Line is not in proper tags format - continue - endif - - " Extract the tag type - let ttype = s:Tlist_Extract_Tagtype(one_line) - - " Make sure the tag type is a valid and supported one - if ttype == '' || stridx(ctags_flags, ttype) == -1 - " Line is not in proper tags format or Tag type is not - " supported - continue - endif - - " Update the total tag count - let tidx = tidx + 1 - - " The following variables are used to optimize this code. Vim is - " slow in using curly brace names. To reduce the amount of - " processing needed, the curly brace variables are pre-processed - " here - let fidx_tidx = 's:tlist_' . fidx . '_' . tidx - let fidx_ttype = 's:tlist_' . fidx . '_' . ttype - - " Update the count of this tag type - let ttype_idx = {fidx_ttype}_count + 1 - let {fidx_ttype}_count = ttype_idx - - " Store the ctags output for this tag - let {fidx_tidx}_tag = one_line - - " Store the tag index and the tag type index (back pointers) - let {fidx_ttype}_{ttype_idx} = tidx - let {fidx_tidx}_ttype_idx = ttype_idx - - " Extract the tag name - let tag_name = strpart(one_line, 0, stridx(one_line, "\t")) - - " Extract the tag scope/prototype - if g:Tlist_Display_Prototype - let ttxt = ' ' . s:Tlist_Get_Tag_Prototype(fidx, tidx) - else - let ttxt = ' ' . tag_name - - " Add the tag scope, if it is available and is configured. Tag - " scope is the last field after the 'line:<num>\t' field - if g:Tlist_Display_Tag_Scope - let tag_scope = s:Tlist_Extract_Tag_Scope(one_line) - if tag_scope != '' - let ttxt = ttxt . ' [' . tag_scope . ']' - endif - endif - endif - - " Add this tag to the tag type variable - let {fidx_ttype} = {fidx_ttype} . ttxt . "\n" - - " Save the tag name - let {fidx_tidx}_tag_name = tag_name - endwhile - - " Save the number of tags for this file - let s:tlist_{fidx}_tag_count = tidx - endif - - call s:Tlist_Log_Msg('Processed ' . s:tlist_{fidx}_tag_count . - \ ' tags in ' . a:filename) - - return fidx -endfunction - -" Tlist_Update_File -" Update the tags for a file (if needed) -function! Tlist_Update_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Update_File (' . a:filename . ')') - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(a:filename, a:ftype) - return - endif - - " Convert the file name to a full path - let fname = fnamemodify(a:filename, ':p') - - " First check whether the file already exists - let fidx = s:Tlist_Get_File_Index(fname) - - if fidx != -1 && s:tlist_{fidx}_valid - " File exists and the tags are valid - " Check whether the file was modified after the last tags update - " If it is modified, then update the tags - if s:tlist_{fidx}_mtime == getftime(fname) - return - endif - else - " If the tags were removed previously based on a user request, - " as we are going to update the tags (based on the user request), - " remove the filename from the deleted list - call s:Tlist_Update_Remove_List(fname, 0) - endif - - " If the taglist window is opened, update it - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - " Taglist window is not present. Just update the taglist - " and return - call s:Tlist_Process_File(fname, a:ftype) - else - if g:Tlist_Show_One_File && s:tlist_cur_file_idx != -1 - " If tags for only one file are displayed and we are not - " updating the tags for that file, then no need to - " refresh the taglist window. Otherwise, the taglist - " window should be updated. - if s:tlist_{s:tlist_cur_file_idx}_filename != fname - call s:Tlist_Process_File(fname, a:ftype) - return - endif - endif - - " Save the current window number - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - " Save the cursor position - let save_line = line('.') - let save_col = col('.') - - " Update the taglist window - call s:Tlist_Window_Refresh_File(fname, a:ftype) - - " Restore the cursor position - if v:version >= 601 - call cursor(save_line, save_col) - else - exe save_line - exe 'normal! ' . save_col . '|' - endif - - if winnr() != save_winnr - " Go back to the original window - call s:Tlist_Exe_Cmd_No_Acmds(save_winnr . 'wincmd w') - endif - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(1) - endif -endfunction - -" Tlist_Window_Close -" Close the taglist window -function! s:Tlist_Window_Close() - call s:Tlist_Log_Msg('Tlist_Window_Close()') - " Make sure the taglist window exists - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Error: Taglist window is not open') - return - endif - - if winnr() == winnum - " Already in the taglist window. Close it and return - if winbufnr(2) != -1 - " If a window other than the taglist window is open, - " then only close the taglist window. - close - endif - else - " Goto the taglist window, close it and then come back to the - " original window - let curbufnr = bufnr('%') - exe winnum . 'wincmd w' - close - " Need to jump back to the original window only if we are not - " already in that window - let winnum = bufwinnr(curbufnr) - if winnr() != winnum - exe winnum . 'wincmd w' - endif - endif -endfunction - -" Tlist_Window_Mark_File_Window -" Mark the current window as the file window to use when jumping to a tag. -" Only if the current window is a non-plugin, non-preview and non-taglist -" window -function! s:Tlist_Window_Mark_File_Window() - if getbufvar('%', '&buftype') == '' && !&previewwindow - let w:tlist_file_window = "yes" - endif -endfunction - -" Tlist_Window_Open -" Open and refresh the taglist window -function! s:Tlist_Window_Open() - call s:Tlist_Log_Msg('Tlist_Window_Open()') - " If the window is open, jump to it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Jump to the existing window - if winnr() != winnum - exe winnum . 'wincmd w' - endif - return - endif - - if s:tlist_app_name == "winmanager" - " Taglist plugin is no longer part of the winmanager app - let s:tlist_app_name = "none" - endif - - " Get the filename and filetype for the specified buffer - let curbuf_name = fnamemodify(bufname('%'), ':p') - let curbuf_ftype = s:Tlist_Get_Buffer_Filetype('%') - let cur_lnum = line('.') - - " Mark the current window as the desired window to open a file when a tag - " is selected. - call s:Tlist_Window_Mark_File_Window() - - " Open the taglist window - call s:Tlist_Window_Create() - - call s:Tlist_Window_Refresh() - - if g:Tlist_Show_One_File - " Add only the current buffer and file - " - " If the file doesn't support tag listing, skip it - if !s:Tlist_Skip_File(curbuf_name, curbuf_ftype) - call s:Tlist_Window_Refresh_File(curbuf_name, curbuf_ftype) - endif - endif - - if g:Tlist_File_Fold_Auto_Close - " Open the fold for the current file, as all the folds in - " the taglist window are closed - let fidx = s:Tlist_Get_File_Index(curbuf_name) - if fidx != -1 - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - endif - endif - - " Highlight the current tag - call s:Tlist_Window_Highlight_Tag(curbuf_name, cur_lnum, 1, 1) -endfunction - -" Tlist_Window_Toggle() -" Open or close a taglist window -function! s:Tlist_Window_Toggle() - call s:Tlist_Log_Msg('Tlist_Window_Toggle()') - " If taglist window is open then close it. - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - call s:Tlist_Window_Close() - return - endif - - call s:Tlist_Window_Open() - - " Go back to the original window, if Tlist_GainFocus_On_ToggleOpen is not - " set - if !g:Tlist_GainFocus_On_ToggleOpen - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif -endfunction - -" Tlist_Process_Filelist -" Process multiple files. Each filename is separated by "\n" -" Returns the number of processed files -function! s:Tlist_Process_Filelist(file_names) - let flist = a:file_names - - " Enable lazy screen updates - let old_lazyredraw = &lazyredraw - set lazyredraw - - " Keep track of the number of processed files - let fcnt = 0 - - " Process one file at a time - while flist != '' - let nl_idx = stridx(flist, "\n") - let one_file = strpart(flist, 0, nl_idx) - - " Remove the filename from the list - let flist = strpart(flist, nl_idx + 1) - - if one_file == '' - continue - endif - - " Skip directories - if isdirectory(one_file) - continue - endif - - let ftype = s:Tlist_Detect_Filetype(one_file) - - echon "\r " - echon "\rProcessing tags for " . fnamemodify(one_file, ':p:t') - - let fcnt = fcnt + 1 - - call Tlist_Update_File(one_file, ftype) - endwhile - - " Clear the displayed informational messages - echon "\r " - - " Restore the previous state - let &lazyredraw = old_lazyredraw - - return fcnt -endfunction - -" Tlist_Process_Dir -" Process the files in a directory matching the specified pattern -function! s:Tlist_Process_Dir(dir_name, pat) - let flist = glob(a:dir_name . '/' . a:pat) . "\n" - - let fcnt = s:Tlist_Process_Filelist(flist) - - let len = strlen(a:dir_name) - if a:dir_name[len - 1] == '\' || a:dir_name[len - 1] == '/' - let glob_expr = a:dir_name . '*' - else - let glob_expr = a:dir_name . '/*' - endif - let all_files = glob(glob_expr) . "\n" - - while all_files != '' - let nl_idx = stridx(all_files, "\n") - let one_file = strpart(all_files, 0, nl_idx) - - let all_files = strpart(all_files, nl_idx + 1) - if one_file == '' - continue - endif - - " Skip non-directory names - if !isdirectory(one_file) - continue - endif - - echon "\r " - echon "\rProcessing files in directory " . fnamemodify(one_file, ':t') - let fcnt = fcnt + s:Tlist_Process_Dir(one_file, a:pat) - endwhile - - return fcnt -endfunction - -" Tlist_Add_Files_Recursive -" Add files recursively from a directory -function! s:Tlist_Add_Files_Recursive(dir, ...) - let dir_name = fnamemodify(a:dir, ':p') - if !isdirectory(dir_name) - call s:Tlist_Warning_Msg('Error: ' . dir_name . ' is not a directory') - return - endif - - if a:0 == 1 - " User specified file pattern - let pat = a:1 - else - " Default file pattern - let pat = '*' - endif - - echon "\r " - echon "\rProcessing files in directory " . fnamemodify(dir_name, ':t') - let fcnt = s:Tlist_Process_Dir(dir_name, pat) - - echon "\rAdded " . fcnt . " files to the taglist" -endfunction - -" Tlist_Add_Files -" Add the specified list of files to the taglist -function! s:Tlist_Add_Files(...) - let flist = '' - let i = 1 - - " Get all the files matching the file patterns supplied as argument - while i <= a:0 - let flist = flist . glob(a:{i}) . "\n" - let i = i + 1 - endwhile - - if flist == '' - call s:Tlist_Warning_Msg('Error: No matching files are found') - return - endif - - let fcnt = s:Tlist_Process_Filelist(flist) - echon "\rAdded " . fcnt . " files to the taglist" -endfunction - -" Tlist_Extract_Tagtype -" Extract the tag type from the tag text -function! s:Tlist_Extract_Tagtype(tag_line) - " The tag type is after the tag prototype field. The prototype field - " ends with the /;"\t string. We add 4 at the end to skip the characters - " in this special string.. - let start = strridx(a:tag_line, '/;"' . "\t") + 4 - let end = strridx(a:tag_line, 'line:') - 1 - let ttype = strpart(a:tag_line, start, end - start) - - return ttype -endfunction - -" Tlist_Extract_Tag_Scope -" Extract the tag scope from the tag text -function! s:Tlist_Extract_Tag_Scope(tag_line) - let start = strridx(a:tag_line, 'line:') - let end = strridx(a:tag_line, "\t") - if end <= start - return '' - endif - - let tag_scope = strpart(a:tag_line, end + 1) - let tag_scope = strpart(tag_scope, stridx(tag_scope, ':') + 1) - - return tag_scope -endfunction - -" Tlist_Refresh() -" Refresh the taglist -function! s:Tlist_Refresh() - call s:Tlist_Log_Msg('Tlist_Refresh (Skip_Refresh = ' . - \ s:Tlist_Skip_Refresh . ', ' . bufname('%') . ')') - " If we are entering the buffer from one of the taglist functions, then - " no need to refresh the taglist window again. - if s:Tlist_Skip_Refresh - " We still need to update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif - return - endif - - " If part of the winmanager plugin and not configured to process - " tags always and not configured to display the tags menu, then return - if (s:tlist_app_name == 'winmanager') && !g:Tlist_Process_File_Always - \ && !g:Tlist_Show_Menu - return - endif - - " Skip buffers with 'buftype' set to nofile, nowrite, quickfix or help - if &buftype != '' - return - endif - - let filename = fnamemodify(bufname('%'), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype('%') - - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(filename, ftype) - return - endif - - let tlist_win = bufwinnr(g:TagList_title) - - " If the taglist window is not opened and not configured to process - " tags always and not displaying the tags menu, then return - if tlist_win == -1 && !g:Tlist_Process_File_Always && !g:Tlist_Show_Menu - return - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(filename) - return - endif - - " If the taglist should not be auto updated, then return - if !g:Tlist_Auto_Update - return - endif - endif - - let cur_lnum = line('.') - - if fidx == -1 - " Update the tags for the file - let fidx = s:Tlist_Process_File(filename, ftype) - else - let mtime = getftime(filename) - if s:tlist_{fidx}_mtime != mtime - " Invalidate the tags listed for this file - let s:tlist_{fidx}_valid = 0 - - " Update the taglist and the window - call Tlist_Update_File(filename, ftype) - - " Store the new file modification time - let s:tlist_{fidx}_mtime = mtime - endif - endif - - " Update the taglist window - if tlist_win != -1 - " Disable screen updates - let old_lazyredraw = &lazyredraw - set nolazyredraw - - " Save the current window number - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - if !g:Tlist_Auto_Highlight_Tag || !g:Tlist_Highlight_Tag_On_BufEnter - " Save the cursor position - let save_line = line('.') - let save_col = col('.') - endif - - " Update the taglist window - call s:Tlist_Window_Refresh_File(filename, ftype) - - " Open the fold for the file - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - - if g:Tlist_Highlight_Tag_On_BufEnter && g:Tlist_Auto_Highlight_Tag - if g:Tlist_Show_One_File && s:tlist_cur_file_idx != fidx - " If displaying tags for only one file in the taglist - " window and about to display the tags for a new file, - " then center the current tag line for the new file - let center_tag_line = 1 - else - let center_tag_line = 0 - endif - - " Highlight the current tag - call s:Tlist_Window_Highlight_Tag(filename, cur_lnum, 1, center_tag_line) - else - " Restore the cursor position - if v:version >= 601 - call cursor(save_line, save_col) - else - exe save_line - exe 'normal! ' . save_col . '|' - endif - endif - - " Jump back to the original window - if save_winnr != winnr() - call s:Tlist_Exe_Cmd_No_Acmds(save_winnr . 'wincmd w') - endif - - " Restore screen updates - let &lazyredraw = old_lazyredraw - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif -endfunction - -" Tlist_Change_Sort() -" Change the sort order of the tag listing -" caller == 'cmd', command used in the taglist window -" caller == 'menu', taglist menu -" action == 'toggle', toggle sort from name to order and vice versa -" action == 'set', set the sort order to sort_type -function! s:Tlist_Change_Sort(caller, action, sort_type) - call s:Tlist_Log_Msg('Tlist_Change_Sort (caller = ' . a:caller . - \ ', action = ' . a:action . ', sort_type = ' . a:sort_type . ')') - if a:caller == 'cmd' - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - " Remove the previous highlighting - match none - elseif a:caller == 'menu' - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx == -1 - return - endif - endif - - if a:action == 'toggle' - let sort_type = s:tlist_{fidx}_sort_type - - " Toggle the sort order from 'name' to 'order' and vice versa - if sort_type == 'name' - let s:tlist_{fidx}_sort_type = 'order' - else - let s:tlist_{fidx}_sort_type = 'name' - endif - else - let s:tlist_{fidx}_sort_type = a:sort_type - endif - - " Invalidate the tags listed for this file - let s:tlist_{fidx}_valid = 0 - - if a:caller == 'cmd' - " Save the current line for later restoration - let curline = '\V\^' . getline('.') . '\$' - - call s:Tlist_Window_Refresh_File(s:tlist_{fidx}_filename, - \ s:tlist_{fidx}_filetype) - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'foldopen!' - - " Go back to the cursor line before the tag list is sorted - call search(curline, 'w') - - call s:Tlist_Menu_Update_File(1) - else - call s:Tlist_Menu_Remove_File() - - call s:Tlist_Refresh() - endif -endfunction - -" Tlist_Update_Current_File() -" Update taglist for the current buffer by regenerating the tag list -" Contributed by WEN Guopeng. -function! s:Tlist_Update_Current_File() - call s:Tlist_Log_Msg('Tlist_Update_Current_File()') - if winnr() == bufwinnr(g:TagList_title) - " In the taglist window. Update the current file - call s:Tlist_Window_Update_File() - else - " Not in the taglist window. Update the current buffer - let filename = fnamemodify(bufname('%'), ':p') - let fidx = s:Tlist_Get_File_Index(filename) - if fidx != -1 - let s:tlist_{fidx}_valid = 0 - endif - let ft = s:Tlist_Get_Buffer_Filetype('%') - call Tlist_Update_File(filename, ft) - endif -endfunction - -" Tlist_Window_Update_File() -" Update the tags displayed in the taglist window -function! s:Tlist_Window_Update_File() - call s:Tlist_Log_Msg('Tlist_Window_Update_File()') - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - " Remove the previous highlighting - match none - - " Save the current line for later restoration - let curline = '\V\^' . getline('.') . '\$' - - let s:tlist_{fidx}_valid = 0 - - " Update the taglist window - call s:Tlist_Window_Refresh_File(s:tlist_{fidx}_filename, - \ s:tlist_{fidx}_filetype) - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'foldopen!' - - " Go back to the tag line before the list is updated - call search(curline, 'w') -endfunction - -" Tlist_Window_Get_Tag_Type_By_Linenum() -" Return the tag type index for the specified line in the taglist window -function! s:Tlist_Window_Get_Tag_Type_By_Linenum(fidx, lnum) - let ftype = s:tlist_{a:fidx}_filetype - - " Determine to which tag type the current line number belongs to using the - " tag type start line number and the number of tags in a tag type - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - let start_lnum = - \ s:tlist_{a:fidx}_start + s:tlist_{a:fidx}_{ttype}_offset - let end = start_lnum + s:tlist_{a:fidx}_{ttype}_count - if a:lnum >= start_lnum && a:lnum <= end - break - endif - let i = i + 1 - endwhile - - " Current line doesn't belong to any of the displayed tag types - if i > s:tlist_{ftype}_count - return '' - endif - - return ttype -endfunction - -" Tlist_Window_Get_Tag_Index() -" Return the tag index for the specified line in the taglist window -function! s:Tlist_Window_Get_Tag_Index(fidx, lnum) - let ttype = s:Tlist_Window_Get_Tag_Type_By_Linenum(a:fidx, a:lnum) - - " Current line doesn't belong to any of the displayed tag types - if ttype == '' - return 0 - endif - - " Compute the index into the displayed tags for the tag type - let ttype_lnum = s:tlist_{a:fidx}_start + s:tlist_{a:fidx}_{ttype}_offset - let tidx = a:lnum - ttype_lnum - if tidx == 0 - return 0 - endif - - " Get the corresponding tag line and return it - return s:tlist_{a:fidx}_{ttype}_{tidx} -endfunction - -" Tlist_Window_Highlight_Line -" Highlight the current line -function! s:Tlist_Window_Highlight_Line() - " Clear previously selected name - match none - - " Highlight the current line - if g:Tlist_Display_Prototype == 0 - let pat = '/\%' . line('.') . 'l\s\+\zs.*/' - else - let pat = '/\%' . line('.') . 'l.*/' - endif - - exe 'match TagListTagName ' . pat -endfunction - -" Tlist_Window_Open_File -" Open the specified file in either a new window or an existing window -" and place the cursor at the specified tag pattern -function! s:Tlist_Window_Open_File(win_ctrl, filename, tagpat) - call s:Tlist_Log_Msg('Tlist_Window_Open_File (' . a:filename . ',' . - \ a:win_ctrl . ')') - let prev_Tlist_Skip_Refresh = s:Tlist_Skip_Refresh - let s:Tlist_Skip_Refresh = 1 - - if s:tlist_app_name == "winmanager" - " Let the winmanager edit the file - call WinManagerFileEdit(a:filename, a:win_ctrl == 'newwin') - else - - if a:win_ctrl == 'newtab' - " Create a new tab - exe 'tabnew ' . escape(a:filename, ' ') - " Open the taglist window in the new tab - call s:Tlist_Window_Open() - endif - - if a:win_ctrl == 'checktab' - " Check whether the file is present in any of the tabs. - " If the file is present in the current tab, then use the - " current tab. - if bufwinnr(a:filename) != -1 - let file_present_in_tab = 1 - let i = tabpagenr() - else - let i = 1 - let bnum = bufnr(a:filename) - let file_present_in_tab = 0 - while i <= tabpagenr('$') - if index(tabpagebuflist(i), bnum) != -1 - let file_present_in_tab = 1 - break - endif - let i += 1 - endwhile - endif - - if file_present_in_tab - " Goto the tab containing the file - exe 'tabnext ' . i - else - " Open a new tab - exe 'tabnew ' . escape(a:filename, ' ') - - " Open the taglist window - call s:Tlist_Window_Open() - endif - endif - - let winnum = -1 - if a:win_ctrl == 'prevwin' - " Open the file in the previous window, if it is usable - let cur_win = winnr() - wincmd p - if &buftype == '' && !&previewwindow - exe "edit " . escape(a:filename, ' ') - let winnum = winnr() - else - " Previous window is not usable - exe cur_win . 'wincmd w' - endif - endif - - " Goto the window containing the file. If the window is not there, open a - " new window - if winnum == -1 - let winnum = bufwinnr(a:filename) - endif - - if winnum == -1 - " Locate the previously used window for opening a file - let fwin_num = 0 - let first_usable_win = 0 - - let i = 1 - let bnum = winbufnr(i) - while bnum != -1 - if getwinvar(i, 'tlist_file_window') == 'yes' - let fwin_num = i - break - endif - if first_usable_win == 0 && - \ getbufvar(bnum, '&buftype') == '' && - \ !getwinvar(i, '&previewwindow') - " First non-taglist, non-plugin and non-preview window - let first_usable_win = i - endif - let i = i + 1 - let bnum = winbufnr(i) - endwhile - - " If a previously used window is not found, then use the first - " non-taglist window - if fwin_num == 0 - let fwin_num = first_usable_win - endif - - if fwin_num != 0 - " Jump to the file window - exe fwin_num . "wincmd w" - - " If the user asked to jump to the tag in a new window, then split - " the existing window into two. - if a:win_ctrl == 'newwin' - split - endif - exe "edit " . escape(a:filename, ' ') - else - " Open a new window - if g:Tlist_Use_Horiz_Window - exe 'leftabove split ' . escape(a:filename, ' ') - else - if winbufnr(2) == -1 - " Only the taglist window is present - if g:Tlist_Use_Right_Window - exe 'leftabove vertical split ' . - \ escape(a:filename, ' ') - else - exe 'rightbelow vertical split ' . - \ escape(a:filename, ' ') - endif - - " Go to the taglist window to change the window size to - " the user configured value - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - if g:Tlist_Use_Horiz_Window - exe 'resize ' . g:Tlist_WinHeight - else - exe 'vertical resize ' . g:Tlist_WinWidth - endif - " Go back to the file window - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - else - " A plugin or help window is also present - wincmd w - exe 'leftabove split ' . escape(a:filename, ' ') - endif - endif - endif - " Mark the window, so that it can be reused. - call s:Tlist_Window_Mark_File_Window() - else - if v:version >= 700 - " If the file is opened in more than one window, then check - " whether the last accessed window has the selected file. - " If it does, then use that window. - let lastwin_bufnum = winbufnr(winnr('#')) - if bufnr(a:filename) == lastwin_bufnum - let winnum = winnr('#') - endif - endif - exe winnum . 'wincmd w' - - " If the user asked to jump to the tag in a new window, then split the - " existing window into two. - if a:win_ctrl == 'newwin' - split - endif - endif - endif - - " Jump to the tag - if a:tagpat != '' - " Add the current cursor position to the jump list, so that user can - " jump back using the ' and ` marks. - mark ' - silent call search(a:tagpat, 'w') - - " Bring the line to the middle of the window - normal! z. - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - .foldopen - endif - endif - - " If the user selects to preview the tag then jump back to the - " taglist window - if a:win_ctrl == 'preview' - " Go back to the taglist window - let winnum = bufwinnr(g:TagList_title) - exe winnum . 'wincmd w' - else - " If the user has selected to close the taglist window, when a - " tag is selected, close the taglist window - if g:Tlist_Close_On_Select - call s:Tlist_Window_Goto_Window() - close - - " Go back to the window displaying the selected file - let wnum = bufwinnr(a:filename) - if wnum != -1 && wnum != winnr() - call s:Tlist_Exe_Cmd_No_Acmds(wnum . 'wincmd w') - endif - endif - endif - - let s:Tlist_Skip_Refresh = prev_Tlist_Skip_Refresh -endfunction - -" Tlist_Window_Jump_To_Tag() -" Jump to the location of the current tag -" win_ctrl == useopen - Reuse the existing file window -" win_ctrl == newwin - Open a new window -" win_ctrl == preview - Preview the tag -" win_ctrl == prevwin - Open in previous window -" win_ctrl == newtab - Open in new tab -function! s:Tlist_Window_Jump_To_Tag(win_ctrl) - call s:Tlist_Log_Msg('Tlist_Window_Jump_To_Tag(' . a:win_ctrl . ')') - " Do not process comment lines and empty lines - let curline = getline('.') - if curline =~ '^\s*$' || curline[0] == '"' - return - endif - - " If inside a closed fold, then use the first line of the fold - " and jump to the file. - let lnum = foldclosed('.') - if lnum == -1 - " Jump to the selected tag or file - let lnum = line('.') - else - " Open the closed fold - .foldopen! - endif - - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - if fidx == -1 - return - endif - - " Get the tag output for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, lnum) - if tidx != 0 - let tagpat = s:Tlist_Get_Tag_SearchPat(fidx, tidx) - - " Highlight the tagline - call s:Tlist_Window_Highlight_Line() - else - " Selected a line which is not a tag name. Just edit the file - let tagpat = '' - endif - - call s:Tlist_Window_Open_File(a:win_ctrl, s:tlist_{fidx}_filename, tagpat) -endfunction - -" Tlist_Window_Show_Info() -" Display information about the entry under the cursor -function! s:Tlist_Window_Show_Info() - call s:Tlist_Log_Msg('Tlist_Window_Show_Info()') - - " Clear the previously displayed line - echo - - " Do not process comment lines and empty lines - let curline = getline('.') - if curline =~ '^\s*$' || curline[0] == '"' - return - endif - - " If inside a fold, then don't display the prototype - if foldclosed('.') != -1 - return - endif - - let lnum = line('.') - - " Get the file index - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - if fidx == -1 - return - endif - - if lnum == s:tlist_{fidx}_start - " Cursor is on a file name - let fname = s:tlist_{fidx}_filename - if strlen(fname) > 50 - let fname = fnamemodify(fname, ':t') - endif - echo fname . ', Filetype=' . s:tlist_{fidx}_filetype . - \ ', Tag count=' . s:tlist_{fidx}_tag_count - return - endif - - " Get the tag output line for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, lnum) - if tidx == 0 - " Cursor is on a tag type - let ttype = s:Tlist_Window_Get_Tag_Type_By_Linenum(fidx, lnum) - if ttype == '' - return - endif - - let ttype_name = '' - - let ftype = s:tlist_{fidx}_filetype - let i = 1 - while i <= s:tlist_{ftype}_count - if ttype == s:tlist_{ftype}_{i}_name - let ttype_name = s:tlist_{ftype}_{i}_fullname - break - endif - let i = i + 1 - endwhile - - echo 'Tag type=' . ttype_name . - \ ', Tag count=' . s:tlist_{fidx}_{ttype}_count - return - endif - - " Get the tag search pattern and display it - echo s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Find_Nearest_Tag_Idx -" Find the tag idx nearest to the supplied line number -" Returns -1, if a tag couldn't be found for the specified line number -function! s:Tlist_Find_Nearest_Tag_Idx(fidx, linenum) - let sort_type = s:tlist_{a:fidx}_sort_type - - let left = 1 - let right = s:tlist_{a:fidx}_tag_count - - if sort_type == 'order' - " Tags sorted by order, use a binary search. - " The idea behind this function is taken from the ctags.vim script (by - " Alexey Marinichev) available at the Vim online website. - - " If the current line is the less than the first tag, then no need to - " search - let first_lnum = s:Tlist_Get_Tag_Linenum(a:fidx, 1) - - if a:linenum < first_lnum - return -1 - endif - - while left < right - let middle = (right + left + 1) / 2 - let middle_lnum = s:Tlist_Get_Tag_Linenum(a:fidx, middle) - - if middle_lnum == a:linenum - let left = middle - break - endif - - if middle_lnum > a:linenum - let right = middle - 1 - else - let left = middle - endif - endwhile - else - " Tags sorted by name, use a linear search. (contributed by Dave - " Eggum). - " Look for a tag with a line number less than or equal to the supplied - " line number. If multiple tags are found, then use the tag with the - " line number closest to the supplied line number. IOW, use the tag - " with the highest line number. - let closest_lnum = 0 - let final_left = 0 - while left <= right - let lnum = s:Tlist_Get_Tag_Linenum(a:fidx, left) - - if lnum < a:linenum && lnum > closest_lnum - let closest_lnum = lnum - let final_left = left - elseif lnum == a:linenum - let closest_lnum = lnum - let final_left = left - break - else - let left = left + 1 - endif - endwhile - if closest_lnum == 0 - return -1 - endif - if left >= right - let left = final_left - endif - endif - - return left -endfunction - -" Tlist_Window_Highlight_Tag() -" Highlight the current tag -" cntx == 1, Called by the taglist plugin itself -" cntx == 2, Forced by the user through the TlistHighlightTag command -" center = 1, move the tag line to the center of the taglist window -function! s:Tlist_Window_Highlight_Tag(filename, cur_lnum, cntx, center) - " Highlight the current tag only if the user configured the - " taglist plugin to do so or if the user explictly invoked the - " command to highlight the current tag. - if !g:Tlist_Auto_Highlight_Tag && a:cntx == 1 - return - endif - - if a:filename == '' - return - endif - - " Make sure the taglist window is present - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Error: Taglist window is not open') - return - endif - - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - return - endif - - " If the file is currently not displayed in the taglist window, then retrn - if !s:tlist_{fidx}_visible - return - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return - endif - - " Ignore all autocommands - let old_ei = &eventignore - set eventignore=all - - " Save the original window number - let org_winnr = winnr() - - if org_winnr == winnum - let in_taglist_window = 1 - else - let in_taglist_window = 0 - endif - - " Go to the taglist window - if !in_taglist_window - exe winnum . 'wincmd w' - endif - - " Clear previously selected name - match none - - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, a:cur_lnum) - if tidx == -1 - " Make sure the current tag line is visible in the taglist window. - " Calling the winline() function makes the line visible. Don't know - " of a better way to achieve this. - let lnum = line('.') - - if lnum < s:tlist_{fidx}_start || lnum > s:tlist_{fidx}_end - " Move the cursor to the beginning of the file - exe s:tlist_{fidx}_start - endif - - if foldclosed('.') != -1 - .foldopen - endif - - call winline() - - if !in_taglist_window - exe org_winnr . 'wincmd w' - endif - - " Restore the autocommands - let &eventignore = old_ei - return - endif - - " Extract the tag type - let ttype = s:Tlist_Get_Tag_Type_By_Tag(fidx, tidx) - - " Compute the line number - " Start of file + Start of tag type + offset - let lnum = s:tlist_{fidx}_start + s:tlist_{fidx}_{ttype}_offset + - \ s:tlist_{fidx}_{tidx}_ttype_idx - - " Goto the line containing the tag - exe lnum - - " Open the fold - if foldclosed('.') != -1 - .foldopen - endif - - if a:center - " Move the tag line to the center of the taglist window - normal! z. - else - " Make sure the current tag line is visible in the taglist window. - " Calling the winline() function makes the line visible. Don't know - " of a better way to achieve this. - call winline() - endif - - " Highlight the tag name - call s:Tlist_Window_Highlight_Line() - - " Go back to the original window - if !in_taglist_window - exe org_winnr . 'wincmd w' - endif - - " Restore the autocommands - let &eventignore = old_ei - return -endfunction - -" Tlist_Get_Tag_Prototype_By_Line -" Get the prototype for the tag on or before the specified line number in the -" current buffer -function! Tlist_Get_Tag_Prototype_By_Line(...) - if a:0 == 0 - " Arguments are not supplied. Use the current buffer name - " and line number - let filename = bufname('%') - let linenr = line('.') - elseif a:0 == 2 - " Filename and line number are specified - let filename = a:1 - let linenr = a:2 - if linenr !~ '\d\+' - " Invalid line number - return "" - endif - else - " Sufficient arguments are not supplied - let msg = 'Usage: Tlist_Get_Tag_Prototype_By_Line <filename> ' . - \ '<line_number>' - call s:Tlist_Warning_Msg(msg) - return "" - endif - - " Expand the file to a fully qualified name - let filename = fnamemodify(filename, ':p') - if filename == '' - return "" - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - return "" - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return "" - endif - - " Get the tag text using the line number - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, linenr) - if tidx == -1 - return "" - endif - - return s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Get_Tagname_By_Line -" Get the tag name on or before the specified line number in the -" current buffer -function! Tlist_Get_Tagname_By_Line(...) - if a:0 == 0 - " Arguments are not supplied. Use the current buffer name - " and line number - let filename = bufname('%') - let linenr = line('.') - elseif a:0 == 2 - " Filename and line number are specified - let filename = a:1 - let linenr = a:2 - if linenr !~ '\d\+' - " Invalid line number - return "" - endif - else - " Sufficient arguments are not supplied - let msg = 'Usage: Tlist_Get_Tagname_By_Line <filename> <line_number>' - call s:Tlist_Warning_Msg(msg) - return "" - endif - - " Make sure the current file has a name - let filename = fnamemodify(filename, ':p') - if filename == '' - return "" - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - return "" - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return "" - endif - - " Get the tag name using the line number - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, linenr) - if tidx == -1 - return "" - endif - - return s:tlist_{fidx}_{tidx}_tag_name -endfunction - -" Tlist_Window_Move_To_File -" Move the cursor to the beginning of the current file or the next file -" or the previous file in the taglist window -" dir == -1, move to start of current or previous function -" dir == 1, move to start of next function -function! s:Tlist_Window_Move_To_File(dir) - if foldlevel('.') == 0 - " Cursor is on a non-folded line (it is not in any of the files) - " Move it to a folded line - if a:dir == -1 - normal! zk - else - " While moving down to the start of the next fold, - " no need to do go to the start of the next file. - normal! zj - return - endif - endif - - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - let cur_lnum = line('.') - - if a:dir == -1 - if cur_lnum > s:tlist_{fidx}_start - " Move to the beginning of the current file - exe s:tlist_{fidx}_start - return - endif - - if fidx != 0 - " Move to the beginning of the previous file - let fidx = fidx - 1 - else - " Cursor is at the first file, wrap around to the last file - let fidx = s:tlist_file_count - 1 - endif - - exe s:tlist_{fidx}_start - return - else - " Move to the beginning of the next file - let fidx = fidx + 1 - - if fidx >= s:tlist_file_count - " Cursor is at the last file, wrap around to the first file - let fidx = 0 - endif - - if s:tlist_{fidx}_start != 0 - exe s:tlist_{fidx}_start - endif - return - endif -endfunction - -" Tlist_Session_Load -" Load a taglist session (information about all the displayed files -" and the tags) from the specified file -function! s:Tlist_Session_Load(...) - if a:0 == 0 || a:1 == '' - call s:Tlist_Warning_Msg('Usage: TlistSessionLoad <filename>') - return - endif - - let sessionfile = a:1 - - if !filereadable(sessionfile) - let msg = 'Taglist: Error - Unable to open file ' . sessionfile - call s:Tlist_Warning_Msg(msg) - return - endif - - " Mark the current window as the file window - call s:Tlist_Window_Mark_File_Window() - - " Source the session file - exe 'source ' . sessionfile - - let new_file_count = g:tlist_file_count - unlet! g:tlist_file_count - - let i = 0 - while i < new_file_count - let ftype = g:tlist_{i}_filetype - unlet! g:tlist_{i}_filetype - - if !exists('s:tlist_' . ftype . '_count') - if s:Tlist_FileType_Init(ftype) == 0 - let i = i + 1 - continue - endif - endif - - let fname = g:tlist_{i}_filename - unlet! g:tlist_{i}_filename - - let fidx = s:Tlist_Get_File_Index(fname) - if fidx != -1 - let s:tlist_{fidx}_visible = 0 - let i = i + 1 - continue - else - " As we are loading the tags from the session file, if this - " file was previously deleted by the user, now we need to - " add it back. So remove the file from the deleted list. - call s:Tlist_Update_Remove_List(fname, 0) - endif - - let fidx = s:Tlist_Init_File(fname, ftype) - - let s:tlist_{fidx}_filename = fname - - let s:tlist_{fidx}_sort_type = g:tlist_{i}_sort_type - unlet! g:tlist_{i}_sort_type - - let s:tlist_{fidx}_filetype = ftype - let s:tlist_{fidx}_mtime = getftime(fname) - - let s:tlist_{fidx}_start = 0 - let s:tlist_{fidx}_end = 0 - - let s:tlist_{fidx}_valid = 1 - - let s:tlist_{fidx}_tag_count = g:tlist_{i}_tag_count - unlet! g:tlist_{i}_tag_count - - let j = 1 - while j <= s:tlist_{fidx}_tag_count - let s:tlist_{fidx}_{j}_tag = g:tlist_{i}_{j}_tag - let s:tlist_{fidx}_{j}_tag_name = g:tlist_{i}_{j}_tag_name - let s:tlist_{fidx}_{j}_ttype_idx = g:tlist_{i}_{j}_ttype_idx - unlet! g:tlist_{i}_{j}_tag - unlet! g:tlist_{i}_{j}_tag_name - unlet! g:tlist_{i}_{j}_ttype_idx - let j = j + 1 - endwhile - - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - - if exists('g:tlist_' . i . '_' . ttype) - let s:tlist_{fidx}_{ttype} = g:tlist_{i}_{ttype} - unlet! g:tlist_{i}_{ttype} - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = g:tlist_{i}_{ttype}_count - unlet! g:tlist_{i}_{ttype}_count - - let k = 1 - while k <= s:tlist_{fidx}_{ttype}_count - let s:tlist_{fidx}_{ttype}_{k} = g:tlist_{i}_{ttype}_{k} - unlet! g:tlist_{i}_{ttype}_{k} - let k = k + 1 - endwhile - else - let s:tlist_{fidx}_{ttype} = '' - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = 0 - endif - - let j = j + 1 - endwhile - - let i = i + 1 - endwhile - - " If the taglist window is open, then update it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - " Refresh the taglist window - call s:Tlist_Window_Refresh() - - " Go back to the original window - if save_winnr != winnr() - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - endif -endfunction - -" Tlist_Session_Save -" Save a taglist session (information about all the displayed files -" and the tags) into the specified file -function! s:Tlist_Session_Save(...) - if a:0 == 0 || a:1 == '' - call s:Tlist_Warning_Msg('Usage: TlistSessionSave <filename>') - return - endif - - let sessionfile = a:1 - - if s:tlist_file_count == 0 - " There is nothing to save - call s:Tlist_Warning_Msg('Warning: Taglist is empty. Nothing to save.') - return - endif - - if filereadable(sessionfile) - let ans = input('Do you want to overwrite ' . sessionfile . ' (Y/N)?') - if ans !=? 'y' - return - endif - - echo "\n" - endif - - let old_verbose = &verbose - set verbose&vim - - exe 'redir! > ' . sessionfile - - silent! echo '" Taglist session file. This file is auto-generated.' - silent! echo '" File information' - silent! echo 'let tlist_file_count = ' . s:tlist_file_count - - let i = 0 - - while i < s:tlist_file_count - " Store information about the file - silent! echo 'let tlist_' . i . "_filename = '" . - \ s:tlist_{i}_filename . "'" - silent! echo 'let tlist_' . i . '_sort_type = "' . - \ s:tlist_{i}_sort_type . '"' - silent! echo 'let tlist_' . i . '_filetype = "' . - \ s:tlist_{i}_filetype . '"' - silent! echo 'let tlist_' . i . '_tag_count = ' . - \ s:tlist_{i}_tag_count - " Store information about all the tags - let j = 1 - while j <= s:tlist_{i}_tag_count - let txt = escape(s:tlist_{i}_{j}_tag, '"\\') - silent! echo 'let tlist_' . i . '_' . j . '_tag = "' . txt . '"' - silent! echo 'let tlist_' . i . '_' . j . '_tag_name = "' . - \ s:tlist_{i}_{j}_tag_name . '"' - silent! echo 'let tlist_' . i . '_' . j . '_ttype_idx' . ' = ' . - \ s:tlist_{i}_{j}_ttype_idx - let j = j + 1 - endwhile - - " Store information about all the tags grouped by their type - let ftype = s:tlist_{i}_filetype - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - if s:tlist_{i}_{ttype}_count != 0 - let txt = escape(s:tlist_{i}_{ttype}, '"\') - let txt = substitute(txt, "\n", "\\\\n", 'g') - silent! echo 'let tlist_' . i . '_' . ttype . ' = "' . - \ txt . '"' - silent! echo 'let tlist_' . i . '_' . ttype . '_count = ' . - \ s:tlist_{i}_{ttype}_count - let k = 1 - while k <= s:tlist_{i}_{ttype}_count - silent! echo 'let tlist_' . i . '_' . ttype . '_' . k . - \ ' = ' . s:tlist_{i}_{ttype}_{k} - let k = k + 1 - endwhile - endif - let j = j + 1 - endwhile - - silent! echo - - let i = i + 1 - endwhile - - redir END - - let &verbose = old_verbose -endfunction - -" Tlist_Buffer_Removed -" A buffer is removed from the Vim buffer list. Remove the tags defined -" for that file -function! s:Tlist_Buffer_Removed(filename) - call s:Tlist_Log_Msg('Tlist_Buffer_Removed (' . a:filename . ')') - - " Make sure a valid filename is supplied - if a:filename == '' - return - endif - - " Get tag list index of the specified file - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - " File not present in the taglist - return - endif - - " Remove the file from the list - call s:Tlist_Remove_File(fidx, 0) -endfunction - -" When a buffer is deleted, remove the file from the taglist -autocmd BufDelete * silent call s:Tlist_Buffer_Removed(expand('<afile>:p')) - -" Tlist_Window_Open_File_Fold -" Open the fold for the specified file and close the fold for all the -" other files -function! s:Tlist_Window_Open_File_Fold(acmd_bufnr) - call s:Tlist_Log_Msg('Tlist_Window_Open_File_Fold (' . a:acmd_bufnr . ')') - - " Make sure the taglist window is present - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Taglist: Error - Taglist window is not open') - return - endif - - " Save the original window number - let org_winnr = winnr() - if org_winnr == winnum - let in_taglist_window = 1 - else - let in_taglist_window = 0 - endif - - if in_taglist_window - " When entering the taglist window, no need to update the folds - return - endif - - " Go to the taglist window - if !in_taglist_window - call s:Tlist_Exe_Cmd_No_Acmds(winnum . 'wincmd w') - endif - - " Close all the folds - silent! %foldclose - - " Get tag list index of the specified file - let fname = fnamemodify(bufname(a:acmd_bufnr + 0), ':p') - if filereadable(fname) - let fidx = s:Tlist_Get_File_Index(fname) - if fidx != -1 - " Open the fold for the file - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen" - endif - endif - - " Go back to the original window - if !in_taglist_window - call s:Tlist_Exe_Cmd_No_Acmds(org_winnr . 'wincmd w') - endif -endfunction - -" Tlist_Window_Check_Auto_Open -" Open the taglist window automatically on Vim startup. -" Open the window only when files present in any of the Vim windows support -" tags. -function! s:Tlist_Window_Check_Auto_Open() - let open_window = 0 - - let i = 1 - let buf_num = winbufnr(i) - while buf_num != -1 - let filename = fnamemodify(bufname(buf_num), ':p') - let ft = s:Tlist_Get_Buffer_Filetype(buf_num) - if !s:Tlist_Skip_File(filename, ft) - let open_window = 1 - break - endif - let i = i + 1 - let buf_num = winbufnr(i) - endwhile - - if open_window - call s:Tlist_Window_Toggle() - endif -endfunction - -" Tlist_Refresh_Folds -" Remove and create the folds for all the files displayed in the taglist -" window. Used after entering a tab. If this is not done, then the folds -" are not properly created for taglist windows displayed in multiple tabs. -function! s:Tlist_Refresh_Folds() - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - return - endif - - let save_wnum = winnr() - exe winnum . 'wincmd w' - - " First remove all the existing folds - normal! zE - - " Create the folds for each in the tag list - let fidx = 0 - while fidx < s:tlist_file_count - let ftype = s:tlist_{fidx}_filetype - - " Create the folds for each tag type in a file - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - if s:tlist_{fidx}_{ttype}_count - let s = s:tlist_{fidx}_start + s:tlist_{fidx}_{ttype}_offset - let e = s + s:tlist_{fidx}_{ttype}_count - exe s . ',' . e . 'fold' - endif - let j = j + 1 - endwhile - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'fold' - exe 'silent! ' . s:tlist_{fidx}_start . ',' . - \ s:tlist_{fidx}_end . 'foldopen!' - let fidx = fidx + 1 - endwhile - - exe save_wnum . 'wincmd w' -endfunction - -function! s:Tlist_Menu_Add_Base_Menu() - call s:Tlist_Log_Msg('Adding the base menu') - - " Add the menu - anoremenu <silent> T&ags.Refresh\ menu :call <SID>Tlist_Menu_Refresh()<CR> - anoremenu <silent> T&ags.Sort\ menu\ by.Name - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'name')<CR> - anoremenu <silent> T&ags.Sort\ menu\ by.Order - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'order')<CR> - anoremenu T&ags.-SEP1- : - - if &mousemodel =~ 'popup' - anoremenu <silent> PopUp.T&ags.Refresh\ menu - \ :call <SID>Tlist_Menu_Refresh()<CR> - anoremenu <silent> PopUp.T&ags.Sort\ menu\ by.Name - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'name')<CR> - anoremenu <silent> PopUp.T&ags.Sort\ menu\ by.Order - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'order')<CR> - anoremenu PopUp.T&ags.-SEP1- : - endif -endfunction - -let s:menu_char_prefix = - \ '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' - -" Tlist_Menu_Get_Tag_Type_Cmd -" Get the menu command for the specified tag type -" fidx - File type index -" ftype - File Type -" add_ttype_name - To add or not to add the tag type name to the menu entries -" ttype_idx - Tag type index -function! s:Tlist_Menu_Get_Tag_Type_Cmd(fidx, ftype, add_ttype_name, ttype_idx) - " Curly brace variable name optimization - let ftype_ttype_idx = a:ftype . '_' . a:ttype_idx - - let ttype = s:tlist_{ftype_ttype_idx}_name - if a:add_ttype_name - " If the tag type name contains space characters, escape it. This - " will be used to create the menu entries. - let ttype_fullname = escape(s:tlist_{ftype_ttype_idx}_fullname, ' ') - endif - - " Curly brace variable name optimization - let fidx_ttype = a:fidx . '_' . ttype - - " Number of tag entries for this tag type - let tcnt = s:tlist_{fidx_ttype}_count - if tcnt == 0 " No entries for this tag type - return '' - endif - - let mcmd = '' - - " Create the menu items for the tags. - " Depending on the number of tags of this type, split the menu into - " multiple sub-menus, if needed. - if tcnt > g:Tlist_Max_Submenu_Items - let j = 1 - while j <= tcnt - let final_index = j + g:Tlist_Max_Submenu_Items - 1 - if final_index > tcnt - let final_index = tcnt - endif - - " Extract the first and last tag name and form the - " sub-menu name - let tidx = s:tlist_{fidx_ttype}_{j} - let first_tag = s:tlist_{a:fidx}_{tidx}_tag_name - - let tidx = s:tlist_{fidx_ttype}_{final_index} - let last_tag = s:tlist_{a:fidx}_{tidx}_tag_name - - " Truncate the names, if they are greater than the - " max length - let first_tag = strpart(first_tag, 0, g:Tlist_Max_Tag_Length) - let last_tag = strpart(last_tag, 0, g:Tlist_Max_Tag_Length) - - " Form the menu command prefix - let m_prefix = 'anoremenu <silent> T\&ags.' - if a:add_ttype_name - let m_prefix = m_prefix . ttype_fullname . '.' - endif - let m_prefix = m_prefix . first_tag . '\.\.\.' . last_tag . '.' - - " Character prefix used to number the menu items (hotkey) - let m_prefix_idx = 0 - - while j <= final_index - let tidx = s:tlist_{fidx_ttype}_{j} - - let tname = s:tlist_{a:fidx}_{tidx}_tag_name - - let mcmd = mcmd . m_prefix . '\&' . - \ s:menu_char_prefix[m_prefix_idx] . '\.' . - \ tname . ' :call <SID>Tlist_Menu_Jump_To_Tag(' . - \ tidx . ')<CR>|' - - let m_prefix_idx = m_prefix_idx + 1 - let j = j + 1 - endwhile - endwhile - else - " Character prefix used to number the menu items (hotkey) - let m_prefix_idx = 0 - - let m_prefix = 'anoremenu <silent> T\&ags.' - if a:add_ttype_name - let m_prefix = m_prefix . ttype_fullname . '.' - endif - let j = 1 - while j <= tcnt - let tidx = s:tlist_{fidx_ttype}_{j} - - let tname = s:tlist_{a:fidx}_{tidx}_tag_name - - let mcmd = mcmd . m_prefix . '\&' . - \ s:menu_char_prefix[m_prefix_idx] . '\.' . - \ tname . ' :call <SID>Tlist_Menu_Jump_To_Tag(' . tidx - \ . ')<CR>|' - - let m_prefix_idx = m_prefix_idx + 1 - let j = j + 1 - endwhile - endif - - return mcmd -endfunction - -" Update the taglist menu with the tags for the specified file -function! s:Tlist_Menu_File_Refresh(fidx) - call s:Tlist_Log_Msg('Refreshing the tag menu for ' . s:tlist_{a:fidx}_filename) - " The 'B' flag is needed in the 'cpoptions' option - let old_cpoptions = &cpoptions - set cpoptions&vim - - exe s:tlist_{a:fidx}_menu_cmd - - " Update the popup menu (if enabled) - if &mousemodel =~ 'popup' - let cmd = substitute(s:tlist_{a:fidx}_menu_cmd, ' T\\&ags\.', - \ ' PopUp.T\\\&ags.', "g") - exe cmd - endif - - " The taglist menu is not empty now - let s:tlist_menu_empty = 0 - - " Restore the 'cpoptions' settings - let &cpoptions = old_cpoptions -endfunction - -" Tlist_Menu_Update_File -" Add the taglist menu -function! s:Tlist_Menu_Update_File(clear_menu) - if !has('gui_running') - " Not running in GUI mode - return - endif - - call s:Tlist_Log_Msg('Updating the tag menu, clear_menu = ' . a:clear_menu) - - " Remove the tags menu - if a:clear_menu - call s:Tlist_Menu_Remove_File() - - endif - - " Skip buffers with 'buftype' set to nofile, nowrite, quickfix or help - if &buftype != '' - return - endif - - let filename = fnamemodify(bufname('%'), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype('%') - - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(filename, ftype) - return - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 || !s:tlist_{fidx}_valid - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(filename) - return - endif - - " Process the tags for the file - let fidx = s:Tlist_Process_File(filename, ftype) - if fidx == -1 - return - endif - endif - - let fname = escape(fnamemodify(bufname('%'), ':t'), '.') - if fname != '' - exe 'anoremenu T&ags.' . fname . ' <Nop>' - anoremenu T&ags.-SEP2- : - endif - - if !s:tlist_{fidx}_tag_count - return - endif - - if s:tlist_{fidx}_menu_cmd != '' - " Update the menu with the cached command - call s:Tlist_Menu_File_Refresh(fidx) - - return - endif - - " We are going to add entries to the tags menu, so the menu won't be - " empty - let s:tlist_menu_empty = 0 - - let cmd = '' - - " Determine whether the tag type name needs to be added to the menu - " If more than one tag type is present in the taglisting for a file, - " then the tag type name needs to be present - let add_ttype_name = -1 - let i = 1 - while i <= s:tlist_{ftype}_count && add_ttype_name < 1 - let ttype = s:tlist_{ftype}_{i}_name - if s:tlist_{fidx}_{ttype}_count - let add_ttype_name = add_ttype_name + 1 - endif - let i = i + 1 - endwhile - - " Process the tags by the tag type and get the menu command - let i = 1 - while i <= s:tlist_{ftype}_count - let mcmd = s:Tlist_Menu_Get_Tag_Type_Cmd(fidx, ftype, add_ttype_name, i) - if mcmd != '' - let cmd = cmd . mcmd - endif - - let i = i + 1 - endwhile - - " Cache the menu command for reuse - let s:tlist_{fidx}_menu_cmd = cmd - - " Update the menu - call s:Tlist_Menu_File_Refresh(fidx) -endfunction - -" Tlist_Menu_Remove_File -" Remove the tags displayed in the tags menu -function! s:Tlist_Menu_Remove_File() - if !has('gui_running') || s:tlist_menu_empty - return - endif - - call s:Tlist_Log_Msg('Removing the tags menu for a file') - - " Cleanup the Tags menu - silent! unmenu T&ags - if &mousemodel =~ 'popup' - silent! unmenu PopUp.T&ags - endif - - " Add a dummy menu item to retain teared off menu - noremenu T&ags.Dummy l - - silent! unmenu! T&ags - if &mousemodel =~ 'popup' - silent! unmenu! PopUp.T&ags - endif - - call s:Tlist_Menu_Add_Base_Menu() - - " Remove the dummy menu item - unmenu T&ags.Dummy - - let s:tlist_menu_empty = 1 -endfunction - -" Tlist_Menu_Refresh -" Refresh the taglist menu -function! s:Tlist_Menu_Refresh() - call s:Tlist_Log_Msg('Refreshing the tags menu') - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx != -1 - " Invalidate the cached menu command - let s:tlist_{fidx}_menu_cmd = '' - endif - - " Update the taglist, menu and window - call s:Tlist_Update_Current_File() -endfunction - -" Tlist_Menu_Jump_To_Tag -" Jump to the selected tag -function! s:Tlist_Menu_Jump_To_Tag(tidx) - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx == -1 - return - endif - - let tagpat = s:Tlist_Get_Tag_SearchPat(fidx, a:tidx) - if tagpat == '' - return - endif - - " Add the current cursor position to the jump list, so that user can - " jump back using the ' and ` marks. - mark ' - - silent call search(tagpat, 'w') - - " Bring the line to the middle of the window - normal! z. - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - .foldopen - endif -endfunction - -" Tlist_Menu_Init -" Initialize the taglist menu -function! s:Tlist_Menu_Init() - call s:Tlist_Menu_Add_Base_Menu() - - " Automatically add the tags defined in the current file to the menu - augroup TagListMenuCmds - autocmd! - - if !g:Tlist_Process_File_Always - autocmd BufEnter * call s:Tlist_Refresh() - endif - autocmd BufLeave * call s:Tlist_Menu_Remove_File() - augroup end - - call s:Tlist_Menu_Update_File(0) -endfunction - -" Tlist_Vim_Session_Load -" Initialize the taglist window/buffer, which is created when loading -" a Vim session file. -function! s:Tlist_Vim_Session_Load() - call s:Tlist_Log_Msg('Tlist_Vim_Session_Load') - - " Initialize the taglist window - call s:Tlist_Window_Init() - - " Refresh the taglist window - call s:Tlist_Window_Refresh() -endfunction - -" Tlist_Set_App -" Set the name of the external plugin/application to which taglist -" belongs. -" Taglist plugin is part of another plugin like cream or winmanager. -function! Tlist_Set_App(name) - if a:name == "" - return - endif - - let s:tlist_app_name = a:name -endfunction - -" Winmanager integration - -" Initialization required for integration with winmanager -function! TagList_Start() - " If current buffer is not taglist buffer, then don't proceed - if bufname('%') != '__Tag_List__' - return - endif - - call Tlist_Set_App('winmanager') - - " Get the current filename from the winmanager plugin - let bufnum = WinManagerGetLastEditedFile() - if bufnum != -1 - let filename = fnamemodify(bufname(bufnum), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype(bufnum) - endif - - " Initialize the taglist window, if it is not already initialized - if !exists('s:tlist_window_initialized') || !s:tlist_window_initialized - call s:Tlist_Window_Init() - call s:Tlist_Window_Refresh() - let s:tlist_window_initialized = 1 - endif - - " Update the taglist window - if bufnum != -1 - if !s:Tlist_Skip_File(filename, ftype) && g:Tlist_Auto_Update - call s:Tlist_Window_Refresh_File(filename, ftype) - endif - endif -endfunction - -function! TagList_IsValid() - return 0 -endfunction - -function! TagList_WrapUp() - return 0 -endfunction - -" restore 'cpo' -let &cpo = s:cpo_save -unlet s:cpo_save - diff --git a/vim/plugin/unimpaired.vim b/vim/plugin/unimpaired.vim deleted file mode 100644 index 60b6c02..0000000 --- a/vim/plugin/unimpaired.vim +++ /dev/null @@ -1,315 +0,0 @@ -" unimpaired.vim - Pairs of handy bracket mappings -" Maintainer: Tim Pope <http://tpo.pe/> -" Version: 1.1 -" GetLatestVimScripts: 1590 1 :AutoInstall: unimpaired.vim - -if exists("g:loaded_unimpaired") || &cp || v:version < 700 - finish -endif -let g:loaded_unimpaired = 1 - -" Next and previous {{{1 - -function! s:MapNextFamily(map,cmd) - let map = '<Plug>unimpaired'.toupper(a:map) - let end = ' ".(v:count ? v:count : "")<CR>' - execute 'nmap <silent> '.map.'Previous :<C-U>exe "'.a:cmd.'previous'.end - execute 'nmap <silent> '.map.'Next :<C-U>exe "'.a:cmd.'next'.end - execute 'nmap <silent> '.map.'First :<C-U>exe "'.a:cmd.'first'.end - execute 'nmap <silent> '.map.'Last :<C-U>exe "'.a:cmd.'last'.end - execute 'nmap <silent> ['. a:map .' '.map.'Previous' - execute 'nmap <silent> ]'. a:map .' '.map.'Next' - execute 'nmap <silent> ['.toupper(a:map).' '.map.'First' - execute 'nmap <silent> ]'.toupper(a:map).' '.map.'Last' -endfunction - -call s:MapNextFamily('a','') -call s:MapNextFamily('b','b') -call s:MapNextFamily('l','l') -call s:MapNextFamily('q','c') -call s:MapNextFamily('t','t') - -function! s:entries(path) - let path = substitute(a:path,'[\\/]$','','') - let files = split(glob(path."/.*"),"\n") - let files += split(glob(path."/*"),"\n") - call map(files,'substitute(v:val,"[\\/]$","","")') - call filter(files,'v:val !~# "[\\\\/]\\.\\.\\=$"') - call filter(files,'v:val[-4:-1] !=# ".swp" && v:val[-1:-1] !=# "~"') - return files -endfunction - -function! s:FileByOffset(num) - let file = expand('%:p') - let num = a:num - while num - let files = s:entries(fnamemodify(file,':h')) - if a:num < 0 - call reverse(sort(filter(files,'v:val < file'))) - else - call sort(filter(files,'v:val > file')) - endif - let temp = get(files,0,'') - if temp == '' - let file = fnamemodify(file,':h') - else - let file = temp - while isdirectory(file) - let files = s:entries(file) - if files == [] - " TODO: walk back up the tree and continue - break - endif - let file = files[num > 0 ? 0 : -1] - endwhile - let num += num > 0 ? -1 : 1 - endif - endwhile - return file -endfunction - -nnoremap <silent> <Plug>unimpairedONext :<C-U>edit `=<SID>FileByOffset(v:count1)`<CR> -nnoremap <silent> <Plug>unimpairedOPrevious :<C-U>edit `=<SID>FileByOffset(-v:count1)`<CR> - -nmap ]o <Plug>unimpairedONext -nmap [o <Plug>unimpairedOPrevious - -nmap [, :call search('^[<=>]\{7\}','bW')<CR> -nmap ], :call search('^[<=>]\{7\}','W')<CR> -omap [, V:call search('^[<=>]\{7\}','bW')<CR> -omap ], V:call search('^[<=>]\{7\}','W')<CR> -xmap [, :<C-U>exe 'norm! gv'<Bar>call search('^[<=>]\{7\}','bW')<CR> -xmap ], :<C-U>exe 'norm! gv'<Bar>call search('^[<=>]\{7\}','W')<CR> -nmap [< :call search('^<<<<<<<','bW')<CR> -nmap [= :call search('^=======','bW')<CR> -nmap [> :call search('^>>>>>>>','bW')<CR> -nmap ]< :call search('^<<<<<<<','W')<CR> -nmap ]= :call search('^=======','W')<CR> -nmap ]> :call search('^>>>>>>>','W')<CR> -xmap [< :<C-U>exe 'norm! gv'<Bar>call search('^<<<<<<<','bW')<CR> -xmap [= :<C-U>exe 'norm! gv'<Bar>call search('^=======','bW')<CR> -xmap [> :<C-U>exe 'norm! gv'<Bar>call search('^>>>>>>>','bW')<CR> -xmap ]< :<C-U>exe 'norm! gv'<Bar>call search('^<<<<<<<','W')<CR> -xmap ]= :<C-U>exe 'norm! gv'<Bar>call search('^=======','W')<CR> -xmap ]> :<C-U>exe 'norm! gv'<Bar>call search('^>>>>>>>','W')<CR> -omap [< V:call search('^<<<<<<<','bW')<CR> -omap [= V:call search('^=======','bW')<CR> -omap [> V:call search('^>>>>>>>','bW')<CR> -omap ]< V:call search('^<<<<<<<','W')<CR> -omap ]= V:call search('^=======','W')<CR> -omap ]> V:call search('^>>>>>>>','W')<CR> - -" }}}1 -" Line operations {{{1 - -function! s:BlankUp(count) abort - put!=repeat(nr2char(10), a:count) - ']+1 - silent! call repeat#set("\<Plug>unimpairedBlankUp", a:count) -endfunction - -function! s:BlankDown(count) abort - put =repeat(nr2char(10), a:count) - '[-1 - silent! call repeat#set("\<Plug>unimpairedBlankDown", a:count) -endfunction - -nnoremap <silent> <Plug>unimpairedBlankUp :<C-U>call <SID>BlankUp(v:count1)<CR> -nnoremap <silent> <Plug>unimpairedBlankDown :<C-U>call <SID>BlankDown(v:count1)<CR> - -nmap [<Space> <Plug>unimpairedBlankUp -nmap ]<Space> <Plug>unimpairedBlankDown - -function! s:Move(cmd, count, map) abort - normal! m` - exe 'move'.a:cmd.a:count - norm! `` - call repeat#set("\<Plug>unimpairedMove".a:map, a:count) -endfunction - -nnoremap <silent> <Plug>unimpairedMoveUp :<C-U>call <SID>Move('--',v:count1,'Up')<CR> -nnoremap <silent> <Plug>unimpairedMoveDown :<C-U>call <SID>Move('+',v:count1,'Down')<CR> -xnoremap <silent> <Plug>unimpairedMoveUp :<C-U>exe 'normal! m`'<Bar>exe '''<,''>move--'.v:count1<CR>`` -xnoremap <silent> <Plug>unimpairedMoveDown :<C-U>exe 'normal! m`'<Bar>exe '''<,''>move''>+'.v:count1<CR>`` - -nmap [e <Plug>unimpairedMoveUp -nmap ]e <Plug>unimpairedMoveDown -xmap [e <Plug>unimpairedMoveUp -xmap ]e <Plug>unimpairedMoveDown - -" }}}1 -" Encoding and decoding {{{1 - -function! s:StringEncode(str) - let map = {"\n": 'n', "\r": 'r', "\t": 't', "\b": 'b', "\f": '\f', '"': '"', '\': '\'} - return substitute(a:str,"[\001-\033\\\\\"]",'\="\\".get(map,submatch(0),printf("%03o",char2nr(submatch(0))))','g') -endfunction - -function! s:StringDecode(str) - let map = {'n': "\n", 'r': "\r", 't': "\t", 'b': "\b", 'f': "\f", 'e': "\e", 'a': "\001", 'v': "\013"} - let str = a:str - if str =~ '^\s*".\{-\}\\\@<!\%(\\\\\)*"\s*\n\=$' - let str = substitute(substitute(str,'^\s*\zs"','',''),'"\ze\s*\n\=$','','') - endif - let str = substitute(str,'\\n\%(\n$\)\=','\n','g') - return substitute(str,'\\\(\o\{1,3\}\|x\x\{1,2\}\|u\x\{1,4\}\|.\)','\=get(map,submatch(1),submatch(1) =~? "^[0-9xu]" ? nr2char("0".substitute(submatch(1),"^[Uu]","x","")) : submatch(1))','g') -endfunction - -function! s:UrlEncode(str) - return substitute(a:str,'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g') -endfunction - -function! s:UrlDecode(str) - let str = substitute(substitute(substitute(a:str,'%0[Aa]\n$','%0A',''),'%0[Aa]','\n','g'),'+',' ','g') - return substitute(str,'%\(\x\x\)','\=nr2char("0x".submatch(1))','g') -endfunction - -" HTML entities {{{2 - -let g:unimpaired_html_entities = { - \ 'nbsp': 160, 'iexcl': 161, 'cent': 162, 'pound': 163, - \ 'curren': 164, 'yen': 165, 'brvbar': 166, 'sect': 167, - \ 'uml': 168, 'copy': 169, 'ordf': 170, 'laquo': 171, - \ 'not': 172, 'shy': 173, 'reg': 174, 'macr': 175, - \ 'deg': 176, 'plusmn': 177, 'sup2': 178, 'sup3': 179, - \ 'acute': 180, 'micro': 181, 'para': 182, 'middot': 183, - \ 'cedil': 184, 'sup1': 185, 'ordm': 186, 'raquo': 187, - \ 'frac14': 188, 'frac12': 189, 'frac34': 190, 'iquest': 191, - \ 'Agrave': 192, 'Aacute': 193, 'Acirc': 194, 'Atilde': 195, - \ 'Auml': 196, 'Aring': 197, 'AElig': 198, 'Ccedil': 199, - \ 'Egrave': 200, 'Eacute': 201, 'Ecirc': 202, 'Euml': 203, - \ 'Igrave': 204, 'Iacute': 205, 'Icirc': 206, 'Iuml': 207, - \ 'ETH': 208, 'Ntilde': 209, 'Ograve': 210, 'Oacute': 211, - \ 'Ocirc': 212, 'Otilde': 213, 'Ouml': 214, 'times': 215, - \ 'Oslash': 216, 'Ugrave': 217, 'Uacute': 218, 'Ucirc': 219, - \ 'Uuml': 220, 'Yacute': 221, 'THORN': 222, 'szlig': 223, - \ 'agrave': 224, 'aacute': 225, 'acirc': 226, 'atilde': 227, - \ 'auml': 228, 'aring': 229, 'aelig': 230, 'ccedil': 231, - \ 'egrave': 232, 'eacute': 233, 'ecirc': 234, 'euml': 235, - \ 'igrave': 236, 'iacute': 237, 'icirc': 238, 'iuml': 239, - \ 'eth': 240, 'ntilde': 241, 'ograve': 242, 'oacute': 243, - \ 'ocirc': 244, 'otilde': 245, 'ouml': 246, 'divide': 247, - \ 'oslash': 248, 'ugrave': 249, 'uacute': 250, 'ucirc': 251, - \ 'uuml': 252, 'yacute': 253, 'thorn': 254, 'yuml': 255, - \ 'OElig': 338, 'oelig': 339, 'Scaron': 352, 'scaron': 353, - \ 'Yuml': 376, 'circ': 710, 'tilde': 732, 'ensp': 8194, - \ 'emsp': 8195, 'thinsp': 8201, 'zwnj': 8204, 'zwj': 8205, - \ 'lrm': 8206, 'rlm': 8207, 'ndash': 8211, 'mdash': 8212, - \ 'lsquo': 8216, 'rsquo': 8217, 'sbquo': 8218, 'ldquo': 8220, - \ 'rdquo': 8221, 'bdquo': 8222, 'dagger': 8224, 'Dagger': 8225, - \ 'permil': 8240, 'lsaquo': 8249, 'rsaquo': 8250, 'euro': 8364, - \ 'fnof': 402, 'Alpha': 913, 'Beta': 914, 'Gamma': 915, - \ 'Delta': 916, 'Epsilon': 917, 'Zeta': 918, 'Eta': 919, - \ 'Theta': 920, 'Iota': 921, 'Kappa': 922, 'Lambda': 923, - \ 'Mu': 924, 'Nu': 925, 'Xi': 926, 'Omicron': 927, - \ 'Pi': 928, 'Rho': 929, 'Sigma': 931, 'Tau': 932, - \ 'Upsilon': 933, 'Phi': 934, 'Chi': 935, 'Psi': 936, - \ 'Omega': 937, 'alpha': 945, 'beta': 946, 'gamma': 947, - \ 'delta': 948, 'epsilon': 949, 'zeta': 950, 'eta': 951, - \ 'theta': 952, 'iota': 953, 'kappa': 954, 'lambda': 955, - \ 'mu': 956, 'nu': 957, 'xi': 958, 'omicron': 959, - \ 'pi': 960, 'rho': 961, 'sigmaf': 962, 'sigma': 963, - \ 'tau': 964, 'upsilon': 965, 'phi': 966, 'chi': 967, - \ 'psi': 968, 'omega': 969, 'thetasym': 977, 'upsih': 978, - \ 'piv': 982, 'bull': 8226, 'hellip': 8230, 'prime': 8242, - \ 'Prime': 8243, 'oline': 8254, 'frasl': 8260, 'weierp': 8472, - \ 'image': 8465, 'real': 8476, 'trade': 8482, 'alefsym': 8501, - \ 'larr': 8592, 'uarr': 8593, 'rarr': 8594, 'darr': 8595, - \ 'harr': 8596, 'crarr': 8629, 'lArr': 8656, 'uArr': 8657, - \ 'rArr': 8658, 'dArr': 8659, 'hArr': 8660, 'forall': 8704, - \ 'part': 8706, 'exist': 8707, 'empty': 8709, 'nabla': 8711, - \ 'isin': 8712, 'notin': 8713, 'ni': 8715, 'prod': 8719, - \ 'sum': 8721, 'minus': 8722, 'lowast': 8727, 'radic': 8730, - \ 'prop': 8733, 'infin': 8734, 'ang': 8736, 'and': 8743, - \ 'or': 8744, 'cap': 8745, 'cup': 8746, 'int': 8747, - \ 'there4': 8756, 'sim': 8764, 'cong': 8773, 'asymp': 8776, - \ 'ne': 8800, 'equiv': 8801, 'le': 8804, 'ge': 8805, - \ 'sub': 8834, 'sup': 8835, 'nsub': 8836, 'sube': 8838, - \ 'supe': 8839, 'oplus': 8853, 'otimes': 8855, 'perp': 8869, - \ 'sdot': 8901, 'lceil': 8968, 'rceil': 8969, 'lfloor': 8970, - \ 'rfloor': 8971, 'lang': 9001, 'rang': 9002, 'loz': 9674, - \ 'spades': 9824, 'clubs': 9827, 'hearts': 9829, 'diams': 9830, - \ 'apos': 39} - -" }}}2 - -function! s:XmlEncode(str) - let str = a:str - let str = substitute(str,'&','\&','g') - let str = substitute(str,'<','\<','g') - let str = substitute(str,'>','\>','g') - let str = substitute(str,'"','\"','g') - return str -endfunction - -function! s:XmlEntityDecode(str) - let str = substitute(a:str,'\c&#\%(0*38\|x0*26\);','&','g') - let str = substitute(str,'\c&#\(\d\+\);','\=nr2char(submatch(1))','g') - let str = substitute(str,'\c&#\(x\x\+\);','\=nr2char("0".submatch(1))','g') - let str = substitute(str,'\c'',"'",'g') - let str = substitute(str,'\c"','"','g') - let str = substitute(str,'\c>','>','g') - let str = substitute(str,'\c<','<','g') - let str = substitute(str,'\C&\(\%(amp;\)\@!\w*\);','\=nr2char(get(g:unimpaired_html_entities,submatch(1),63))','g') - return substitute(str,'\c&','\&','g') -endfunction - -function! s:XmlDecode(str) - let str = substitute(a:str,'<\%([[:alnum:]-]\+=\%("[^"]*"\|''[^'']*''\)\|.\)\{-\}>','','g') - return s:XmlEntityDecode(str) -endfunction - -function! s:Transform(algorithm,type) - let sel_save = &selection - let cb_save = &clipboard - set selection=inclusive clipboard-=unnamed clipboard-=unnamedplus - let reg_save = @@ - if a:type =~ '^\d\+$' - silent exe 'norm! ^v'.a:type.'$hy' - elseif a:type =~ '^.$' - silent exe "normal! `<" . a:type . "`>y" - elseif a:type == 'line' - silent exe "normal! '[V']y" - elseif a:type == 'block' - silent exe "normal! `[\<C-V>`]y" - else - silent exe "normal! `[v`]y" - endif - let @@ = s:{a:algorithm}(@@) - norm! gvp - let @@ = reg_save - let &selection = sel_save - let &clipboard = cb_save - if a:type =~ '^\d\+$' - silent! call repeat#set("\<Plug>unimpairedLine".a:algorithm,a:type) - endif -endfunction - -function! s:TransformOpfunc(type) - return s:Transform(s:encode_algorithm, a:type) -endfunction - -function! s:TransformSetup(algorithm) - let s:encode_algorithm = a:algorithm - let &opfunc = matchstr(expand('<sfile>'), '<SNR>\d\+_').'TransformOpfunc' -endfunction - -function! s:MapTransform(algorithm, key) - exe 'nnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>TransformSetup("'.a:algorithm.'")<CR>g@' - exe 'xnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",visualmode())<CR>' - exe 'nnoremap <silent> <Plug>unimpairedLine'.a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",v:count1)<CR>' - exe 'nmap '.a:key.' <Plug>unimpaired'.a:algorithm - exe 'xmap '.a:key.' <Plug>unimpaired'.a:algorithm - exe 'nmap '.a:key.a:key[strlen(a:key)-1].' <Plug>unimpairedLine'.a:algorithm -endfunction - -call s:MapTransform('StringEncode','[y') -call s:MapTransform('StringDecode',']y') -call s:MapTransform('UrlEncode','[u') -call s:MapTransform('UrlDecode',']u') -call s:MapTransform('XmlEncode','[x') -call s:MapTransform('XmlDecode',']x') - -" }}}1 - -" vim:set sw=2 sts=2: diff --git a/vim/plugin/vim-rspec.rb b/vim/plugin/vim-rspec.rb deleted file mode 100644 index 4d7f4c3..0000000 --- a/vim/plugin/vim-rspec.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "rubygems" -require "hpricot" - -doc = Hpricot(STDIN.read) -h1 = (doc/"h1") -classes = {"spec passed"=>"+","spec failed"=>"-","spec not_implemented"=>"#"} - -puts "* #{h1.inner_html}" - -stats = (doc/"script").select {|script| script.innerHTML =~ /duration|totals/ }.map {|script| script.inner_html.scan(/".*"/).first.gsub(/<\/?strong>/,"") } -stats.each do |stat| - puts "* #{stat.gsub(/\"/,'')}" -end -puts "* Parsed with Hpricot (http://wiki.github.com/why/hpricot)" -puts " " - -(doc/"div[@class='example_group']").each do |example| - puts "[#{(example/"dl/dt").inner_html}]" - (example/"dd").each do |dd| - txt = (dd/"span:first").inner_html - puts "#{classes[dd[:class]]} #{txt}" - next if dd[:class]!="spec failed" - failure = (dd/"div[@class='failure']") - msg = (failure/"div[@class='message']/pre").inner_html - back = (failure/"div[@class='backtrace']/pre").inner_html - ruby = (failure/"pre[@class='ruby']/code").inner_html.scan(/(<span class="linenum">)(\d+)(<\/span>)([^<]+)/).map {|elem| " "+elem[1]+": "+elem[3].chomp+"\n"}.join - puts " #{msg}" - puts " #{back}" - puts ruby - end - puts " " -end diff --git a/vim/plugin/vim-rspec.vim b/vim/plugin/vim-rspec.vim deleted file mode 100644 index edc7145..0000000 --- a/vim/plugin/vim-rspec.vim +++ /dev/null @@ -1,174 +0,0 @@ -" -" Vim Rspec -" Last change: March 5 2009 -" Version> 0.0.5 -" Maintainer: Eustáquio 'TaQ' Rangel -" License: GPL -" URL: git://github.com/taq/vim-rspec -" -" Script to run the spec command inside Vim -" To install, unpack the files on your ~/.vim directory and source it -" -" The following options can be set/overridden in your .vimrc -" * g:RspecXSLPath :: Path to xsl file -" * g:RspecRBFilePath :: Path to vim-rspec.rb -" * g:RspecBin :: Rspec binary command (in rspec 2 this is 'rspec') -" * g:RspecOpts :: Opts to send to rspec call - -let s:xsltproc_cmd = "" -let s:grep_cmd = "" -let s:hpricot_cmd = "" -let s:xslt = 0 -let s:hpricot = 0 -let s:helper_dir = expand("<sfile>:h") - -function! s:find_xslt() - return system("xsltproc --version | head -n1") -endfunction - -function! s:find_grep() - return system("grep --version | head -n1") -endfunction - -function! s:find_hpricot() - return system("gem search -i hpricot") -endfunction - -function! s:error_msg(msg) - echohl ErrorMsg - echo a:msg - echohl None -endfunction - -function! s:notice_msg(msg) - echohl MoreMsg - echo a:msg - echohl None -endfunction - -function! s:fetch(varname, default) - if exists("g:".a:varname) - return eval("g:".a:varname) - else - return a:default - endif -endfunction - -function! s:RunSpecMain(type) - if len(s:xsltproc_cmd)<1 - let s:xsltproc_cmd = s:find_xslt() - let s:xslt = match(s:xsltproc_cmd,'\d')>=0 - end - if len(s:hpricot_cmd)<1 - let s:hpricot_cmd = s:find_hpricot() - let s:hpricot = match(s:hpricot_cmd,'true')>=0 - end - if !s:hpricot && !s:xslt - call s:error_msg("You need the hpricot gem or xsltproc to run this script.") - return - end - if len(s:grep_cmd)<1 - let s:grep_cmd = s:find_grep() - if match(s:grep_cmd,'\d')<0 - call s:error_msg("You need grep to run this script.") - return - end - end - let l:bufn = bufname("%") - - " find the installed rspec command - let l:default_cmd = "" - if executable("spec")==1 - let l:default_cmd = "spec" - elseif executable("rspec")==1 - let l:default_cmd = "rspec" - end - - " filters - let l:xsl = s:fetch("RspecXSLPath", s:helper_dir."/vim-rspec.xsl") - let l:rubys = s:fetch("RspecRBPath", s:helper_dir."/vim-rspec.rb") - - " hpricot gets the priority - let l:type = s:hpricot ? "hpricot" : "xsltproc" - let l:filter = s:hpricot ? "ruby ".l:rubys : "xsltproc --novalid --html ".l:xsl." - " - - " run just the current file - if a:type=="file" - if match(l:bufn,'_spec.rb')>=0 - call s:notice_msg("Running spec on the current file with ".l:type." ...") - let l:spec_bin = s:fetch("RspecBin",l:default_cmd) - let l:spec_opts = s:fetch("RspecOpts", "") - let l:spec = l:spec_bin . " " . l:spec_opts . " -f h " . l:bufn - else - call s:error_msg("Seems ".l:bufn." is not a *_spec.rb file") - return - end - else - let l:dir = expand("%:p:h") - if isdirectory(l:dir."/spec")>0 - call s:notice_msg("Running spec on the spec directory with ".l:type." ...") - else - " try to find a spec directory on the current path - let l:tokens = split(l:dir,"/") - let l:dir = "" - for l:item in l:tokens - call remove(l:tokens,-1) - let l:path = "/".join(l:tokens,"/")."/spec" - if isdirectory(l:path) - let l:dir = l:path - break - end - endfor - if len(l:dir)>0 - call s:notice_msg("Running spec with ".l:type." on the spec directory found (".l:dir.") ...") - else - call s:error_msg("No ".l:dir."/spec directory found") - return - end - end - if isdirectory(l:dir)<0 - call s:error_msg("Could not find the ".l:dir." directory.") - return - end - let l:spec = s:fetch("RspecBin", "spec") . s:fetch("RspecOpts", "") - let l:spec = l:spec . " -f h " . l:dir . " -p **/*_spec.rb" - end - - " run the spec command - let s:cmd = l:spec." | ".l:filter." 2> /dev/null | grep \"^[-\+\[\\#\\* ]\"" - echo - - " put the result on a new buffer - silent exec "new" - setl buftype=nofile - silent exec "r! ".s:cmd - setl syntax=vim-rspec - silent exec "nnoremap <buffer> <cr> :call <SID>TryToOpen()<cr>" - silent exec "nnoremap <buffer> q :q<CR>" - setl foldmethod=expr - setl foldexpr=getline(v:lnum)=~'^\+' - setl foldtext=\"+--\ \".string(v:foldend-v:foldstart+1).\"\ passed\ \" - call cursor(1,1) -endfunction - -function! s:TryToOpen() - let l:line = getline(".") - if match(l:line,'^ [\/\.]')<0 - call s:error_msg("No file found.") - return - end - let l:tokens = split(l:line,":") - silent exec "sp ".substitute(l:tokens[0],'/^\s\+',"","") - call cursor(l:tokens[1],1) -endfunction - -function! RunSpec() - call s:RunSpecMain("file") -endfunction - -function! RunSpecs() - call s:RunSpecMain("dir") -endfunction - -command! RunSpec call RunSpec() -command! RunSpecs call RunSpecs() diff --git a/vim/plugin/vim-rspec.xsl b/vim/plugin/vim-rspec.xsl deleted file mode 100644 index 432dc51..0000000 --- a/vim/plugin/vim-rspec.xsl +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0"?> -<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> -<xsl:output method="text"/> - -<xsl:template match="/"> - <xsl:text>* Rspec Results </xsl:text> - <xsl:text>* Parsed with xsltproc (http://www.xmlsoft.org/XSLT/xsltproc2.html) </xsl:text> - <xsl:text> </xsl:text> - <xsl:apply-templates select="html/body/div[@class='rspec-report']/div[@class='results']"/> -</xsl:template> - -<xsl:template match="div[@class='rspec-report']"> - <xsl:apply-templates/> -</xsl:template> - -<xsl:template match="div[@class='example_group']"> - <xsl:text>[</xsl:text><xsl:value-of select="dl/dt"/><xsl:text>]</xsl:text> - <xsl:text> </xsl:text> - <xsl:apply-templates select="dl/dd"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec passed']"> - <xsl:text>+ </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec failed']"> - <xsl:text>- </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> - <xsl:apply-templates select="div"/> -</xsl:template> - -<xsl:template match="dd[@class='spec not_implemented']"> - <xsl:text># </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec failed']/div[@class='failure']"> - <xsl:text> </xsl:text><xsl:value-of select="div[@class='message']/pre"/> - <xsl:text> </xsl:text> - <xsl:text> </xsl:text><xsl:value-of select="div[@class='backtrace']/pre"/> - <xsl:text> </xsl:text> - <xsl:apply-templates select="pre[@class='ruby']/code"/> -</xsl:template> - -<xsl:template match="code"> - <xsl:value-of select="text()"/> - <xsl:text> </xsl:text> -</xsl:template> - -</xsl:stylesheet> |