diff --git a/.vim/after/plugin/TabularMaps.vim b/.vim/after/plugin/TabularMaps.vim deleted file mode 100644 index 20f7141..0000000 --- a/.vim/after/plugin/TabularMaps.vim +++ /dev/null @@ -1,48 +0,0 @@ -if !exists(':Tabularize') - finish " Tabular.vim wasn't loaded -endif - -let s:save_cpo = &cpo -set cpo&vim - -AddTabularPattern! assignment /[|&+*/%<>=!~-]\@!=]=\|=\~\)\@![|&+*/%<>=!~-]*=/l1r1 -AddTabularPattern! two_spaces / /l0 - -AddTabularPipeline! multiple_spaces / / map(a:lines, "substitute(v:val, ' *', ' ', 'g')") | tabular#TabularizeStrings(a:lines, ' ', 'l0') - -AddTabularPipeline! argument_list /(.*)/ map(a:lines, 'substitute(v:val, ''\s*\([(,)]\)\s*'', ''\1'', ''g'')') - \ | tabular#TabularizeStrings(a:lines, '[(,)]', 'l0') - \ | map(a:lines, 'substitute(v:val, ''\(\s*\),'', '',\1 '', "g")') - \ | map(a:lines, 'substitute(v:val, ''\s*)'', ")", "g")') - -function! SplitCDeclarations(lines) - let rv = [] - for line in a:lines - " split the line into declaractions - let split = split(line, '\s*[,;]\s*') - " separate the type from the first declaration - let type = substitute(split[0], '\%(\%([&*]\s*\)*\)\=\k\+$', '', '') - " add the ; back on every declaration - call map(split, 'v:val . ";"') - " add the first element to the return as-is, and remove it from the list - let rv += [ remove(split, 0) ] - " transform the other elements by adding the type on at the beginning - call map(split, 'type . v:val') - " and add them all to the return - let rv += split - endfor - return rv -endfunction - -AddTabularPipeline! split_declarations /,.*;/ SplitCDeclarations(a:lines) - -AddTabularPattern! ternary_operator /^.\{-}\zs?\|:/l1 - -AddTabularPattern! cpp_io /<<\|>>/l1 - -AddTabularPattern! pascal_assign /:=/l1 - -AddTabularPattern! trailing_c_comments /\/\*\|\*\/\|\/\//l1 - -let &cpo = s:save_cpo -unlet s:save_cpo diff --git a/.vim/autoload/ctrlp.vim b/.vim/autoload/ctrlp.vim deleted file mode 100644 index 5cbed86..0000000 --- a/.vim/autoload/ctrlp.vim +++ /dev/null @@ -1,1323 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp.vim -" Description: Fuzzy file, buffer, mru and tag finder. -" Author: Kien Nguyen -" Version: 1.6.4 -" ============================================================================= - -" Static variables {{{1 -fu! s:opts() - let hst = exists('+hi') ? &hi : 20 - let opts = { - \ 'g:ctrlp_by_filename': ['s:byfname', 0], - \ 'g:ctrlp_clear_cache_on_exit': ['s:clrex', 1], - \ 'g:ctrlp_dont_split': ['s:nosplit', ''], - \ 'g:ctrlp_dotfiles': ['s:dotfiles', 1], - \ 'g:ctrlp_extensions': ['s:extensions', []], - \ 'g:ctrlp_follow_symlinks': ['s:folsym', 0], - \ 'g:ctrlp_highlight_match': ['s:mathi', [1, 'Identifier']], - \ 'g:ctrlp_lazy_update': ['s:lazy', 0], - \ 'g:ctrlp_jump_to_buffer': ['s:jmptobuf', 1], - \ 'g:ctrlp_match_window_bottom': ['s:mwbottom', 1], - \ 'g:ctrlp_match_window_reversed': ['s:mwreverse', 1], - \ 'g:ctrlp_max_depth': ['s:maxdepth', 40], - \ 'g:ctrlp_max_files': ['s:maxfiles', 20000], - \ 'g:ctrlp_max_height': ['s:mxheight', 10], - \ 'g:ctrlp_max_history': ['s:maxhst', hst], - \ 'g:ctrlp_open_multi': ['s:opmul', '1v'], - \ 'g:ctrlp_open_new_file': ['s:newfop', 3], - \ 'g:ctrlp_prompt_mappings': ['s:urprtmaps', 0], - \ 'g:ctrlp_regexp_search': ['s:regexp', 0], - \ 'g:ctrlp_root_markers': ['s:rmarkers', []], - \ 'g:ctrlp_split_window': ['s:splitwin', 0], - \ 'g:ctrlp_use_caching': ['s:caching', 1], - \ 'g:ctrlp_use_migemo': ['s:migemo', 0], - \ 'g:ctrlp_user_command': ['s:usrcmd', ''], - \ 'g:ctrlp_working_path_mode': ['s:pathmode', 2], - \ } - for [ke, va] in items(opts) - exe 'let' va[0] '=' string(exists(ke) ? eval(ke) : va[1]) - endfo - if !exists('g:ctrlp_newcache') | let g:ctrlp_newcache = 0 | en - let s:glob = s:dotfiles ? '.*\|*' : '*' - let s:maxdepth = min([s:maxdepth, 100]) - let g:ctrlp_builtins = 2 - if !empty(s:extensions) | for each in s:extensions - exe 'ru autoload/ctrlp/'.each.'.vim' - endfo | en -endf -cal s:opts() - -let s:lash = ctrlp#utils#lash() - -" Global options -let s:glbs = { 'magic': 1, 'to': 1, 'tm': 0, 'sb': 1, 'hls': 0, 'im': 0, - \ 'report': 9999, 'sc': 0, 'ss': 0, 'siso': 0, 'mfd': 200, 'mouse': 'n', - \ 'gcr': 'a:block-PmenuSel-blinkon0' } - -if s:lazy - cal extend(s:glbs, { 'ut': ( s:lazy > 1 ? s:lazy : 250 ) }) -en - -" Limiters -let [s:compare_lim, s:nocache_lim, s:mltipats_lim] = [3000, 4000, 2000] -" * Open & Close {{{1 -fu! s:Open() - let [s:cwd, s:winres] = [getcwd(), winrestcmd()] - let [s:crfile, s:crfpath] = [expand('%:p', 1), expand('%:p:h', 1)] - let [s:crword, s:crline] = [expand(''), getline('.')] - let [s:tagfiles, s:crcursor] = [s:tagfiles(), getpos('.')] - let [s:crbufnr, s:crvisual] = [bufnr('%'), s:lastvisual()] - let s:currwin = s:mwbottom ? winnr() : winnr() + has('autocmd') - sil! exe s:mwbottom ? 'bo' : 'to' '1new ControlP' - let [s:bufnr, s:prompt] = [bufnr('%'), ['', '', '']] - abc - if !exists('s:hstry') - let hst = filereadable(s:gethistloc()[1]) ? s:gethistdata() : [''] - let s:hstry = empty(hst) || !s:maxhst ? [''] : hst - en - for [ke, va] in items(s:glbs) - sil! exe 'let s:glb_'.ke.' = &'.ke.' | let &'.ke.' = '.string(va) - endfo - if s:opmul && has('signs') - sign define ctrlpmark text=+> texthl=Search - en - cal s:setupblank() -endf - -fu! s:Close() - try | bun! | cat | clo! | endt - cal s:unmarksigns() - for key in keys(s:glbs) - sil! exe 'let &'.key.' = s:glb_'.key - endfo - if exists('s:glb_acd') | let &acd = s:glb_acd | en - let [g:ctrlp_lines, g:ctrlp_allfiles] = [[], []] - exe s:winres - unl! s:focus s:hisidx s:hstgot s:marked s:statypes s:cline s:init s:savestr - \ s:crfile s:crfpath s:crword s:crvisual s:tagfiles s:crline s:crcursor - \ g:ctrlp_nolimit s:crbufnr - cal ctrlp#recordhist() - ec -endf -" * Clear caches {{{1 -fu! ctrlp#clr(...) - exe 'let g:ctrlp_new'.( exists('a:1') ? a:1 : 'cache' ).' = 1' -endf - -fu! ctrlp#clra(...) - if !exists('a:1') && ( has('dialog_gui') || has('dialog_con') ) && - \ confirm("Delete all cache files?", "&OK\n&Cancel") != 1 | retu | en - let cache_dir = ctrlp#utils#cachedir() - if isdirectory(cache_dir) - let cache_files = split(s:glbpath(cache_dir, '**', 1), "\n") - cal filter(cache_files, '!isdirectory(v:val) && v:val !~ ''\ 2 && len(items) < 30000 && !a:ispathitem ? 's:matchtab' - \ : 'match' - for item in items - if call(mfunc, [item, pat]) >= 0 | cal add(newitems, item) | en - if limit > 0 && len(newitems) >= limit | brea | en - endfo - retu newitems -endf - -fu! s:MatchedItems(items, pats, limit) - let [items, pats, limit, ipt] = [a:items, a:pats, a:limit, s:ispathitem()] - " If items is longer than s:mltipats_lim, use only the last pattern - if len(items) >= s:mltipats_lim | let pats = [pats[-1]] | en - cal map(pats, 'substitute(v:val, "\\\~", "\\\\\\~", "g")') - if !s:regexp | cal map(pats, 'escape(v:val, ".")') | en - " Loop through the patterns - for each in pats - " If newitems is small, set it as items to search in - if exists('newitems') && len(newitems) < limit - let items = copy(newitems) - en - if empty(items) " End here - retu exists('newitems') ? newitems : [] - el " Start here, go back up if have 2 or more in pats - " Loop through the items - let newitems = s:MatchIt(items, each, limit, ipt) - en - endfo - let s:matches = len(newitems) - retu newitems -endf -fu! s:SplitPattern(str, ...) "{{{1 - let str = s:sanstail(a:str) - if s:migemo && s:regexp && len(str) > 0 && executable('cmigemo') - let dict = s:glbpath(&rtp, printf("dict/%s/migemo-dict", &encoding), 1) - if !len(dict) - let dict = s:glbpath(&rtp, "dict/migemo-dict", 1) - en - if len(dict) - let [tokens, str, cmd] = [split(str, '\s'), '', 'cmigemo -v -w %s -d %s'] - for token in tokens - let rtn = system(printf(cmd, shellescape(token), shellescape(dict))) - let str .= !v:shell_error && len(rtn) > 0 ? '.*'.rtn : token - endfo - en - en - let s:savestr = str - if s:regexp || match(str, '\\\(zs\|ze\|<\|>\)\|[*|]') >= 0 - let array = [s:regexfilter(str)] - el - let array = split(str, '\zs') - if exists('+ssl') && !&ssl - cal map(array, 'substitute(v:val, "\\", "\\\\\\", "g")') - en - " Literal ^ and $ - for each in ['^', '$'] - cal map(array, 'substitute(v:val, "\\\'.each.'", "\\\\\\'.each.'", "g")') - endfo - en - " Build the new pattern - let nitem = !empty(array) ? array[0] : '' - let newpats = [nitem] - if len(array) > 1 - for item in range(1, len(array) - 1) - " Separator - let sep = exists('a:1') ? a:1 : '[^'.array[item-1].']\{-}' - let nitem .= sep.array[item] - cal add(newpats, nitem) - endfo - en - retu newpats -endf -" * BuildPrompt() {{{1 -fu! s:Render(lines, pat) - let lines = a:lines - " Setup the match window - let s:height = min([len(lines), s:mxheight]) - sil! exe '%d _ | res' s:height - " Print the new items - if empty(lines) - setl nocul - cal setline(1, ' == NO ENTRIES ==') - cal s:unmarksigns() - if s:dohighlight() | cal clearmatches() | en - retu - en - setl cul - " Sort if not MRU - if ( s:itemtype != 2 && !exists('g:ctrlp_nolimit') ) - \ || !empty(join(s:prompt, '')) - let s:compat = a:pat - cal sort(lines, 's:mixedsort') - unl s:compat - en - if s:mwreverse | cal reverse(lines) | en - let s:matched = copy(lines) - cal map(lines, 'substitute(v:val, "^", "> ", "")') - cal setline(1, lines) - exe 'keepj norm!' s:mwreverse ? 'G' : 'gg' - keepj norm! 1| - cal s:unmarksigns() - cal s:remarksigns() - if exists('s:cline') | cal cursor(s:cline, 1) | en - " Highlighting - if s:dohighlight() - cal s:highlight(a:pat, empty(s:mathi[1]) ? 'Identifier' : s:mathi[1]) - en -endf - -fu! s:Update(str) - " Get the previous string if existed - let oldstr = exists('s:savestr') ? s:savestr : '' - let pats = s:SplitPattern(a:str) - " Get the new string sans tail - let notail = substitute(a:str, ':\([^:]\|\\:\)*$', '', 'g') - " Stop if the string's unchanged - if notail == oldstr && !empty(notail) && !exists('s:force') - retu - en - let lines = exists('g:ctrlp_nolimit') && empty(notail) ? copy(g:ctrlp_lines) - \ : s:MatchedItems(g:ctrlp_lines, pats, s:mxheight) - cal s:Render(lines, pats[-1]) -endf - -fu! s:ForceUpdate() - let [estr, prt] = ['"\', copy(s:prompt)] - cal map(prt, 'escape(v:val, estr)') - cal s:Update(join(prt, '')) -endf - -fu! s:BuildPrompt(upd, ...) - let base = ( s:regexp ? 'r' : '>' ).( s:byfname ? 'd' : '>' ).'> ' - let [estr, prt] = ['"\', copy(s:prompt)] - cal map(prt, 'escape(v:val, estr)') - let str = join(prt, '') - let lazy = empty(str) || exists('s:force') || !has('autocmd') ? 0 : s:lazy - if a:upd && ( s:matches || s:regexp || match(str, '[*|]') >= 0 ) && !lazy - sil! cal s:Update(str) - en - sil! cal ctrlp#statusline() - " Toggling - let [hiactive, hicursor, base] = exists('a:1') && !a:1 - \ ? ['Comment', 'Comment', tr(base, '>', '-')] - \ : ['Normal', 'Constant', base] - let hibase = 'Comment' - " Build it - redr - exe 'echoh' hibase '| echon "'.base.'" - \ | echoh' hiactive '| echon "'.prt[0].'" - \ | echoh' hicursor '| echon "'.prt[1].'" - \ | echoh' hiactive '| echon "'.prt[2].'" | echoh None' - " Append the cursor at the end - if empty(prt[1]) && ( !exists('a:1') || ( exists('a:1') && a:1 ) ) - exe 'echoh' hibase '| echon "_" | echoh None' - en -endf -" ** Prt Actions {{{1 -" Editing {{{2 -fu! s:PrtClear() - unl! s:hstgot - let [s:prompt, s:matches] = [['', '', ''], 1] - cal s:BuildPrompt(1) -endf - -fu! s:PrtAdd(char) - unl! s:hstgot - let s:prompt[0] = s:prompt[0] . a:char - cal s:BuildPrompt(1) -endf - -fu! s:PrtBS() - unl! s:hstgot - let [prt, s:matches] = [s:prompt, 1] - let prt[0] = strpart(prt[0], -1, strlen(prt[0])) - cal s:BuildPrompt(1) -endf - -fu! s:PrtDelete() - unl! s:hstgot - let [prt, s:matches] = [s:prompt, 1] - let prt[1] = strpart(prt[2], 0, 1) - let prt[2] = strpart(prt[2], 1) - cal s:BuildPrompt(1) -endf - -fu! s:PrtDeleteWord() - unl! s:hstgot - let [str, s:matches] = [s:prompt[0], 1] - let str = match(str, '\W\w\+$') >= 0 ? matchstr(str, '^.\+\W\ze\w\+$') - \ : match(str, '\w\W\+$') >= 0 ? matchstr(str, '^.\+\w\ze\W\+$') - \ : match(str, '\s\+$') >= 0 ? matchstr(str, '^.*[^ \t]\+\ze\s\+$') - \ : match(str, ' ') <= 0 ? '' : str - let s:prompt[0] = str - cal s:BuildPrompt(1) -endf - -fu! s:PrtInsert(type) - unl! s:hstgot - " Insert current word, search register, last visual and clipboard - let s:prompt[0] .= a:type == 'w' ? s:crword - \ : a:type == 's' ? getreg('/') - \ : a:type == 'v' ? s:crvisual - \ : a:type == '+' ? substitute(getreg('+'), '\n', '\\n', 'g') : s:prompt[0] - cal s:BuildPrompt(1) -endf -" Movement {{{2 -fu! s:PrtCurLeft() - if !empty(s:prompt[0]) - let prt = s:prompt - let prt[2] = prt[1] . prt[2] - let prt[1] = strpart(prt[0], strlen(prt[0]) - 1) - let prt[0] = strpart(prt[0], -1, strlen(prt[0])) - en - cal s:BuildPrompt(0) -endf - -fu! s:PrtCurRight() - let prt = s:prompt - let prt[0] = prt[0] . prt[1] - let prt[1] = strpart(prt[2], 0, 1) - let prt[2] = strpart(prt[2], 1) - cal s:BuildPrompt(0) -endf - -fu! s:PrtCurStart() - let prt = s:prompt - let str = join(prt, '') - let [prt[0], prt[1], prt[2]] = ['', strpart(str, 0, 1), strpart(str, 1)] - cal s:BuildPrompt(0) -endf - -fu! s:PrtCurEnd() - let prt = s:prompt - let [prt[0], prt[1], prt[2]] = [join(prt, ''), '', ''] - cal s:BuildPrompt(0) -endf - -fu! s:PrtSelectMove(dir) - exe 'norm!' a:dir - let s:cline = line('.') - if line('$') > winheight(0) | cal s:BuildPrompt(0, s:Focus()) | en -endf - -fu! s:PrtSelectJump(char, ...) - let lines = copy(s:matched) - if exists('a:1') - cal map(lines, 'split(v:val, ''[\/]\ze[^\/]\+$'')[-1]') - en - " Cycle through matches, use s:jmpchr to store last jump - let chr = escape(a:char, '.~') - if match(lines, '\c^'.chr) >= 0 - " If not exists or does but not for the same char - let pos = match(lines, '\c^'.chr) - if !exists('s:jmpchr') || ( exists('s:jmpchr') && s:jmpchr[0] != chr ) - let [jmpln, s:jmpchr] = [pos, [chr, pos]] - elsei exists('s:jmpchr') && s:jmpchr[0] == chr - " Start of lines - if s:jmpchr[1] == -1 | let s:jmpchr[1] = pos | en - let npos = match(lines, '\c^'.chr, s:jmpchr[1] + 1) - let [jmpln, s:jmpchr] = [npos == -1 ? pos : npos, [chr, npos]] - en - keepj exe jmpln + 1 - let s:cline = line('.') - if line('$') > winheight(0) | cal s:BuildPrompt(0, s:Focus()) | en - en -endf -" Misc {{{2 -fu! s:PrtClearCache() - if s:itemtype == 1 | retu | en - if s:itemtype == 0 - cal ctrlp#clr() - elsei s:itemtype > 2 - cal ctrlp#clr(s:statypes[s:itemtype][1]) - en - if s:itemtype == 2 - let g:ctrlp_lines = ctrlp#mrufiles#list(-1, 1) - el - cal s:SetLines(s:itemtype) - en - let s:force = 1 - cal s:BuildPrompt(1) - unl s:force -endf - -fu! s:PrtDeleteMRU() - if s:itemtype == 2 - let s:force = 1 - let g:ctrlp_lines = ctrlp#mrufiles#list(-1, 2) - cal s:BuildPrompt(1) - unl s:force - en -endf - -fu! s:PrtExit() - if !has('autocmd') | cal s:Close() | en - exe s:currwin.'winc w' -endf - -fu! s:PrtHistory(...) - if !s:maxhst | retu | en - let [str, hst, s:matches] = [join(s:prompt, ''), s:hstry, 1] - " Save to history if not saved before - let [hst[0], hslen] = [exists('s:hstgot') ? hst[0] : str, len(hst)] - let idx = exists('s:hisidx') ? s:hisidx + a:1 : a:1 - " Limit idx within 0 and hslen - let idx = idx < 0 ? 0 : idx >= hslen ? hslen > 1 ? hslen - 1 : 0 : idx - let s:prompt = [hst[idx], '', ''] - let [s:hisidx, s:hstgot, s:force] = [idx, 1, 1] - cal s:BuildPrompt(1) - unl s:force -endf -"}}}1 -" * MapKeys() {{{1 -fu! s:MapKeys(...) - " Normal keys - let pfunc = exists('a:1') && !a:1 ? 'PrtSelectJump' : 'PrtAdd' - let dojmp = s:byfname && pfunc == 'PrtSelectJump' ? ', 1' : '' - for each in range(32, 126) - let cmd = "nn \ \ \ :\cal \%s(\"%s\"%s)\" - exe printf(cmd, each, pfunc, escape(nr2char(each), '"|\'), dojmp) - endfo - if exists('a:2') | retu | en - " Special keys - cal call('s:MapSpecs', exists('a:1') && !a:1 ? [1] : []) -endf - -fu! s:MapSpecs(...) - let [lcmap, prtmaps] = ['nn ', { - \ 'PrtBS()': [''], - \ 'PrtDelete()': [''], - \ 'PrtDeleteWord()': [''], - \ 'PrtClear()': [''], - \ 'PrtSelectMove("j")': ['', ''], - \ 'PrtSelectMove("k")': ['', ''], - \ 'PrtHistory(-1)': [''], - \ 'PrtHistory(1)': [''], - \ 'AcceptSelection("e")': ['', '<2-LeftMouse>'], - \ 'AcceptSelection("h")': ['', '', ''], - \ 'AcceptSelection("t")': ['', ''], - \ 'AcceptSelection("v")': ['', '', ''], - \ 'ToggleFocus()': [''], - \ 'ToggleRegex()': [''], - \ 'ToggleByFname()': [''], - \ 'ToggleType(1)': ['', '', ''], - \ 'PrtInsert("w")': [''], - \ 'PrtInsert("s")': [''], - \ 'PrtInsert("v")': [''], - \ 'PrtInsert("+")': [''], - \ 'PrtCurStart()': [''], - \ 'PrtCurEnd()': [''], - \ 'PrtCurLeft()': ['', ''], - \ 'PrtCurRight()': ['', ''], - \ 'PrtClearCache()': [''], - \ 'PrtDeleteMRU()': [''], - \ 'CreateNewFile()': [''], - \ 'MarkToOpen()': [''], - \ 'OpenMulti()': [''], - \ 'PrtExit()': ['', '', ''], - \ }] - if type(s:urprtmaps) == 4 - cal extend(prtmaps, s:urprtmaps) - en - " Correct arrow keys in terminal - if ( has('termresponse') && !empty(v:termresponse) ) - \ || &term =~? 'xterm\|\','\B ','\C ','\D '] - exe lcmap.' ['.each - endfo - en - if exists('a:1') - let prtunmaps = [ - \ 'PrtBS()', - \ 'PrtDelete()', - \ 'PrtDeleteWord()', - \ 'PrtClear()', - \ 'PrtCurStart()', - \ 'PrtCurEnd()', - \ 'PrtCurLeft()', - \ 'PrtCurRight()', - \ 'PrtHistory(-1)', - \ 'PrtHistory(1)', - \ 'PrtInsert("w")', - \ 'PrtInsert("s")', - \ 'PrtInsert("v")', - \ 'PrtInsert("+")', - \ ] - for ke in prtunmaps | for kp in prtmaps[ke] - exe lcmap kp '' - endfo | endfo - el - for [ke, va] in items(prtmaps) | for kp in va - exe lcmap kp ':cal '.ke.'' - endfo | endfo - en -endf -" * Toggling {{{1 -fu! s:Focus() - retu !exists('s:focus') ? 1 : s:focus -endf - -fu! s:ToggleFocus() - let s:focus = !exists('s:focus') || s:focus ? 0 : 1 - cal s:MapKeys(s:focus) - cal s:BuildPrompt(0, s:focus) -endf - -fu! s:ToggleRegex() - let s:regexp = s:regexp ? 0 : 1 - cal s:PrtSwitcher() -endf - -fu! s:ToggleByFname() - if s:ispathitem() - let s:byfname = s:byfname ? 0 : 1 - cal s:MapKeys(s:Focus(), 1) - cal s:PrtSwitcher() - en -endf - -fu! s:ToggleType(dir) - let ext = exists('g:ctrlp_ext_vars') ? len(g:ctrlp_ext_vars) : 0 - let s:itemtype = s:walker(g:ctrlp_builtins + ext, s:itemtype, a:dir) - let s:extid = s:itemtype - ( g:ctrlp_builtins + 1 ) - unl! g:ctrlp_nolimit - cal s:SetLines(s:itemtype) - cal s:PrtSwitcher() - if s:itemtype > 2 - if exists('g:ctrlp_ext_vars['.s:extid.'][4][0]') - let g:ctrlp_nolimit = g:ctrlp_ext_vars[s:extid][4][0] - en - el - cal s:syntax() - en -endf - -fu! s:PrtSwitcher() - let [s:force, s:matches] = [1, 1] - cal s:BuildPrompt(1, s:Focus()) - unl s:force -endf -fu! s:SetWD(...) "{{{1 - let pathmode = s:pathmode - if exists('a:1') && len(a:1) | if type(a:1) - cal ctrlp#setdir(a:1) | retu - el - let pathmode = a:1 - en | en - if !exists('a:2') - if match(s:crfile, '^\<.\+\>://.*') >= 0 || !pathmode | retu | en - if exists('+acd') | let [s:glb_acd, &acd] = [&acd, 0] | en - cal ctrlp#setdir(s:crfpath) - en - if pathmode == 1 | retu | en - let markers = ['root.dir','.git/','.hg/','.vimprojects','_darcs/','.bzr/'] - if type(s:rmarkers) == 3 && !empty(s:rmarkers) - cal extend(markers, s:rmarkers, 0) - en - for marker in markers - cal s:findroot(getcwd(), marker, 0, 0) - if exists('s:foundroot') | brea | en - endfo - unl! s:foundroot -endf -" * AcceptSelection() {{{1 -fu! ctrlp#acceptfile(mode, matchstr, ...) - let [md, matchstr] = [a:mode, a:matchstr] - " Get the full path - let filpath = s:itemtype ? matchstr : getcwd().s:lash.matchstr - cal s:PrtExit() - let bufnum = bufnr(filpath) - if s:jmptobuf && bufnum > 0 && md == 'e' - let [jmpb, bufwinnr] = [1, bufwinnr(bufnum)] - let buftab = s:jmptobuf > 1 ? s:buftab(bufnum) : [0, 0] - let j2l = a:0 ? a:1 : str2nr(matchstr(s:tail(), '^ +\zs\d\+$')) - en - " Switch to existing buffer or open new one - if exists('jmpb') && buftab[0] - exe 'tabn' buftab[1] - exe buftab[0].'winc w' - if j2l | cal s:j2l(j2l) | en - elsei exists('jmpb') && bufwinnr > 0 - exe bufwinnr.'winc w' - if j2l | cal s:j2l(j2l) | en - el - " Determine the command to use - let cmd = md == 't' || s:splitwin == 1 ? 'tabe' - \ : md == 'h' || s:splitwin == 2 ? 'new' - \ : md == 'v' || s:splitwin == 3 ? 'vne' : ctrlp#normcmd('e') - " Open new window/buffer - cal call('s:openfile', a:0 ? [cmd, filpath, ' +'.a:1] : [cmd, filpath]) - en -endf - -fu! s:AcceptSelection(mode) - if a:mode == 'e' | if s:specinputs() | retu | en | en - " Get the selected line - let matchstr = matchstr(getline('.'), '^> \zs.\+\ze\t*$') - if empty(matchstr) | retu | en - " Do something with it - let actfunc = s:itemtype =~ '0\|1\|2' ? 'ctrlp#acceptfile' - \ : g:ctrlp_ext_vars[s:itemtype - ( g:ctrlp_builtins + 1 )][1] - cal call(actfunc, [a:mode, matchstr]) -endf -fu! s:CreateNewFile() "{{{1 - let str = join(s:prompt, '') - if empty(str) | retu | en - let str = s:sanstail(str) - let arr = split(str, '[\/]') - let fname = remove(arr, -1) - if len(arr) | if isdirectory(s:createparentdirs(arr)) - let optyp = str - en | el - let optyp = fname - en - if exists('optyp') - let filpath = getcwd().s:lash.optyp - cal s:insertcache(str) - cal s:PrtExit() - let cmd = s:newfop == 1 ? 'tabe' - \ : s:newfop == 2 ? 'new' - \ : s:newfop == 3 ? 'vne' : ctrlp#normcmd('e') - cal s:openfile(cmd, filpath) - en -endf -" * OpenMulti() {{{1 -fu! s:MarkToOpen() - if s:bufnr <= 0 || !s:opmul || s:itemtype > g:ctrlp_builtins | retu | en - let matchstr = matchstr(getline('.'), '^> \zs.\+\ze\t*$') - if empty(matchstr) | retu | en - let filpath = s:itemtype ? matchstr : getcwd().s:lash.matchstr - if exists('s:marked') && s:dictindex(s:marked, filpath) > 0 - " Unmark and remove the file from s:marked - let key = s:dictindex(s:marked, filpath) - cal remove(s:marked, key) - if empty(s:marked) | unl! s:marked | en - if has('signs') - exe 'sign unplace' key 'buffer='.s:bufnr - en - el - " Add to s:marked and place a new sign - if exists('s:marked') - let vac = s:vacantdict(s:marked) - let key = empty(vac) ? len(s:marked) + 1 : vac[0] - let s:marked = extend(s:marked, { key : filpath }) - el - let [key, s:marked] = [1, { 1 : filpath }] - en - if has('signs') - exe 'sign place' key 'line='.line('.').' name=ctrlpmark buffer='.s:bufnr - en - en - sil! cal ctrlp#statusline() -endf - -fu! s:OpenMulti() - if !exists('s:marked') || !s:opmul - cal s:AcceptSelection('e') - retu - en - let mkd = s:marked - cal s:PrtExit() - " Try not to open a new tab - let [ntab, norwins] = [0, s:normbuf()] - if empty(norwins) | let ntab = 1 | el - for each in norwins - let bufnr = winbufnr(each) - if !empty(bufname(bufnr)) && !empty(getbufvar(bufnr, '&ft')) - \ && bufname(bufnr) != 'ControlP' - let ntab = 1 - en - endfo - if !ntab | let wnr = min(norwins) | en - en - if ntab | tabnew | en - let [ic, wnr] = [1, exists('wnr') ? wnr : 1] - let cmds = { 'v': 'vne', 'h': 'new', 't': 'tabe' } - let spt = len(s:opmul) > 1 ? cmds[matchstr(s:opmul, '\w$')] : 'vne' - let nr = matchstr(s:opmul, '^\d\+') - exe wnr.'winc w' - for [ke, va] in items(mkd) - let cmd = ic == 1 ? 'e' : spt - cal s:openfile(cmd, va) - if nr > 1 && nr < ic | clo! | el | let ic += 1 | en - endfo -endf -" ** Helper functions {{{1 -" Sorting {{{2 -fu! ctrlp#complen(s1, s2) - " By length - let [len1, len2] = [strlen(a:s1), strlen(a:s2)] - retu len1 == len2 ? 0 : len1 > len2 ? 1 : -1 -endf - -fu! s:compmatlen(s1, s2) - " By match length - let mln1 = s:shortest(s:matchlens(a:s1, s:compat)) - let mln2 = s:shortest(s:matchlens(a:s2, s:compat)) - retu mln1 == mln2 ? 0 : mln1 > mln2 ? 1 : -1 -endf - -fu! s:comptime(s1, s2) - " By last modified time - let [time1, time2] = [getftime(a:s1), getftime(a:s2)] - retu time1 == time2 ? 0 : time1 < time2 ? 1 : -1 -endf - -fu! s:comparent(s1, s2) - " By same parent dir - if match(s:crfpath, escape(getcwd(), '.^$*\')) >= 0 - let [as1, as2] = [getcwd().s:lash.a:s1, getcwd().s:lash.a:s2] - let [loc1, loc2] = [s:getparent(as1), s:getparent(as2)] - if loc1 == s:crfpath && loc2 != s:crfpath | retu -1 | en - if loc2 == s:crfpath && loc1 != s:crfpath | retu 1 | en - retu 0 - en - retu 0 -endf - -fu! s:matchlens(str, pat, ...) - if empty(a:pat) || index(['^','$'], a:pat) >= 0 | retu {} | en - let st = exists('a:1') ? a:1 : 0 - let lens = exists('a:2') ? a:2 : {} - let nr = exists('a:3') ? a:3 : 0 - if match(a:str, a:pat, st) != -1 - let [mst, mnd] = [matchstr(a:str, a:pat, st), matchend(a:str, a:pat, st)] - let lens = extend(lens, { nr : [len(mst), mst] }) - let lens = s:matchlens(a:str, a:pat, mnd, lens, nr + 1) - en - retu lens -endf - -fu! s:shortest(lens) - retu min(map(values(a:lens), 'v:val[0]')) -endf - -fu! s:mixedsort(s1, s2) - let [cml, cln] = [s:compmatlen(a:s1, a:s2), ctrlp#complen(a:s1, a:s2)] - if s:itemtype < 3 && s:height < 51 - let par = s:comparent(a:s1, a:s2) - if s:height < 21 - retu 6 * cml + 3 * par + 2 * s:comptime(a:s1, a:s2) + cln - en - retu 3 * cml + 2 * par + cln - en - retu 2 * cml + cln -endf -" Statusline {{{2 -fu! ctrlp#statusline(...) - if !exists('s:statypes') - let s:statypes = [ - \ ['files', 'fil'], - \ ['buffers', 'buf'], - \ ['mru files', 'mru'], - \ ] - if exists('g:ctrlp_ext_vars') - cal map(copy(g:ctrlp_ext_vars), 'add(s:statypes, [ v:val[2], v:val[3] ])') - en - en - let tps = s:statypes - let max = len(tps) - 1 - let nxt = tps[s:walker(max, s:itemtype, 1)][1] - let prv = tps[s:walker(max, s:itemtype, -1)][1] - let item = tps[s:itemtype][0] - let focus = s:Focus() ? 'prt' : 'win' - let byfname = s:byfname ? 'file' : 'path' - let regex = s:regexp ? '%#LineNr# regex %*' : '' - let focus = '%#LineNr# '.focus.' %*' - let byfname = '%#Character# '.byfname.' %*' - let item = '%#Character# '.item.' %*' - let slider = ' <'.prv.'>={'.item.'}=<'.nxt.'>' - let dir = ' %=%<%#LineNr# '.getcwd().' %*' - let marked = s:opmul ? exists('s:marked') ? ' <'.s:dismrk().'>' : ' <+>' : '' - let &l:stl = focus.byfname.regex.slider.marked.dir -endf - -fu! s:dismrk() - retu has('signs') ? '+'.len(s:marked) : - \ '%<'.join(values(map(copy(s:marked), 'split(v:val, "[\\/]")[-1]')), ', ') -endf - -fu! ctrlp#progress(len) - if has('macunix') || has('mac') | sl 1m | en - let &l:stl = '%#Function# '.a:len.' %* %=%<%#LineNr# '.getcwd().' %*' - redr -endf -" Paths {{{2 -fu! ctrlp#dirfilter(val) - retu isdirectory(a:val) && match(a:val, '[\/]\.\{,2}$') < 0 ? 1 : 0 -endf - -fu! s:ispathitem() - let ext = s:itemtype - ( g:ctrlp_builtins + 1 ) - if s:itemtype < 3 || ( s:itemtype > 2 && g:ctrlp_ext_vars[ext][3] == 'dir' ) - retu 1 - en - retu 0 -endf - -fu! ctrlp#rmbasedir(items) - let path = &ssl || !exists('+ssl') ? getcwd().'/' : - \ substitute(getcwd(), '\\', '\\\\', 'g').'\\' - retu map(a:items, 'substitute(v:val, path, "", "g")') -endf - -fu! s:parentdir(curr) - let parent = s:getparent(a:curr) - if parent != a:curr | cal ctrlp#setdir(parent) | en -endf - -fu! s:getparent(item) - retu split(a:item, '[\/]\ze[^\/]\+[\/:]\?$')[0] -endf - -fu! s:getgrand(item) - retu split(a:item, '[\/]\ze[^\/]\+[\/][^\/]\+[\/:]\?$')[0] -endf - -fu! s:createparentdirs(arr) - for each in a:arr - let curr = exists('curr') ? curr.s:lash.each : each - cal ctrlp#utils#mkdir(curr) - endfo - retu curr -endf - -fu! s:listdirs(path, parent) - let [str, dirs] = ['', split(s:glbpath(a:path, '*', 1), "\n")] - for entry in filter(dirs, 'isdirectory(v:val)') - let str .= a:parent . split(entry, '[\/]')[-1] . "\n" - endfo - retu str -endf - -fu! ctrlp#cpl(A, L, P) - let haslash = match(a:A, '[\/]') - let parent = substitute(a:A, '[^\/]*$', '', 'g') - let path = !haslash ? parent : haslash > 0 ? getcwd().s:lash.parent : getcwd() - retu s:listdirs(path, parent) -endf - -fu! s:findroot(curr, mark, depth, type) - let [depth, notfound] = [a:depth + 1, empty(s:glbpath(a:curr, a:mark, 1))] - if !notfound || depth > s:maxdepth - if notfound | cal ctrlp#setdir(s:cwd) | en - if a:type - let s:vcsroot = depth <= s:maxdepth ? a:curr : '' - el - cal ctrlp#setdir(a:curr) - let s:foundroot = 1 - en - el - let parent = s:getparent(a:curr) - if parent != a:curr | cal s:findroot(parent, a:mark, depth, a:type) | en - en -endf - -fu! s:glbpath(...) - retu call('globpath', v:version > 701 ? a:000 : a:000[:1]) -endf - -fu! ctrlp#fnesc(path) - retu exists('*fnameescape') ? fnameescape(a:path) : escape(a:path, " %#*?|<\"\n") -endf - -fu! ctrlp#setdir(path, ...) - let cmd = exists('a:1') ? a:1 : 'lc!' - try - exe cmd.' '.ctrlp#fnesc(a:path) - cat - cal ctrlp#msg("Can't change working dir. Directory not exists.") - endt -endf -" Highlighting {{{2 -fu! s:syntax() - sy match CtrlPNoEntries '^ == NO ENTRIES ==$' - sy match CtrlPLineMarker '^>' - hi link CtrlPNoEntries Error - hi CtrlPLineMarker guifg=bg -endf - -fu! s:highlight(pat, grp) - cal clearmatches() - if !empty(a:pat) && a:pat != '..' && s:itemtype < 3 - let pat = substitute(a:pat, '\~', '\\~', 'g') - if !s:regexp | let pat = escape(pat, '.') | en - " Match only filename - if s:byfname - let pat = substitute(pat, '\[\^\(.\{-}\)\]\\{-}', '[^\\/\1]\\{-}', 'g') - let pat = substitute(pat, '$', '\\ze[^\\/]*$', 'g') - en - cal matchadd(a:grp, '\c'.pat) - cal matchadd('CtrlPLineMarker', '^>') - en -endf - -fu! s:dohighlight() - retu type(s:mathi) == 3 && len(s:mathi) == 2 && s:mathi[0] - \ && exists('*clearmatches') -endf -" Prompt history {{{2 -fu! s:gethistloc() - let cache_dir = ctrlp#utils#cachedir().s:lash.'hist' - retu [cache_dir, cache_dir.s:lash.'cache.txt'] -endf - -fu! s:gethistdata() - retu ctrlp#utils#readfile(s:gethistloc()[1]) -endf - -fu! ctrlp#recordhist() - let str = join(s:prompt, '') - if empty(str) || !s:maxhst | retu | en - let hst = s:hstry - if len(hst) > 1 && hst[1] == str | retu | en - cal extend(hst, [str], 1) - if len(hst) > s:maxhst | cal remove(hst, s:maxhst, -1) | en -endf -" Signs {{{2 -fu! s:unmarksigns() - if !s:dosigns() | retu | en - for key in keys(s:marked) - exe 'sign unplace' key 'buffer='.s:bufnr - endfo -endf - -fu! s:remarksigns() - if !s:dosigns() | retu | en - let nls = s:matched - for ic in range(1, len(nls)) - let filpath = s:itemtype ? nls[ic - 1] : getcwd().s:lash.nls[ic - 1] - let key = s:dictindex(s:marked, filpath) - if key > 0 - exe 'sign place' key 'line='.ic.' name=ctrlpmark buffer='.s:bufnr - en - endfo -endf - -fu! s:dosigns() - retu exists('s:marked') && s:bufnr > 0 && s:opmul && has('signs') -endf -" Dictionaries {{{2 -fu! s:dictindex(dict, expr) - for key in keys(a:dict) - if a:dict[key] == a:expr | retu key | en - endfo - retu -1 -endf - -fu! s:vacantdict(dict) - retu filter(range(1, max(keys(a:dict))), '!has_key(a:dict, v:val)') -endf -" Buffers {{{2 -fu! s:buftab(bufnum) - for nr in range(1, tabpagenr('$')) - let buflist = tabpagebuflist(nr) - if match(buflist, a:bufnum) >= 0 - let [buftabnr, tabwinnrs] = [nr, tabpagewinnr(nr, '$')] - for ewin in range(1, tabwinnrs) - if buflist[ewin - 1] == a:bufnum - retu [ewin, buftabnr] - en - endfo - en - endfo - retu [0, 0] -endf - -fu! s:normbuf() - let winnrs = [] - for each in range(1, winnr('$')) - let bufnr = winbufnr(each) - if getbufvar(bufnr, '&bl') && empty(getbufvar(bufnr, '&bt')) - \ && getbufvar(bufnr, '&ma') - cal add(winnrs, each) - en - endfo - retu winnrs -endf - -fu! ctrlp#normcmd(cmd) - if !empty(s:nosplit) && match([bufname('%'), &l:ft], s:nosplit) >= 0 - retu a:cmd - en - " Find a regular buffer - let norwins = s:normbuf() - let norwin = empty(norwins) ? 0 : norwins[0] - if norwin - if index(norwins, winnr()) < 0 - exe norwin.'winc w' - en - retu a:cmd - en - retu 'bo vne' -endf - -fu! s:setupblank() - setl noswf nobl nonu nowrap nolist nospell nocuc wfh - setl fdc=0 fdl=99 tw=0 bt=nofile bh=unload - if v:version >= 703 - setl nornu noudf cc=0 - en -endf - -fu! s:leavepre() - if s:clrex && ( !has('clientserver') || - \ ( has('clientserver') && len(split(serverlist(), "\n")) == 1 ) ) - cal ctrlp#clra(1) - en - cal ctrlp#utils#writecache(s:hstry, s:gethistloc()[0], s:gethistloc()[1]) -endf - -fu! s:checkbuf() - if exists('s:init') | retu | en - if exists('s:bufnr') && s:bufnr > 0 - exe s:bufnr.'bw!' - en -endf -" Arguments {{{2 -fu! s:tail() - if exists('s:optail') && !empty('s:optail') - let tailpref = match(s:optail, '^\s*+') < 0 ? ' +' : ' ' - retu tailpref.s:optail - en - retu '' -endf - -fu! s:sanstail(str) - " Restore the number of backslashes - let str = substitute(a:str, '\\\\', '\', 'g') - unl! s:optail - if match(str, ':\([^:]\|\\:\)*$') >= 0 - let s:optail = matchstr(str, ':\zs\([^:]\|\\:\)*$') - retu substitute(str, ':\([^:]\|\\:\)*$', '', 'g') - en - retu str -endf -" Misc {{{2 -fu! s:specinputs() - let str = join(s:prompt, '') - let type = s:itemtype > 2 ? - \ g:ctrlp_ext_vars[s:itemtype - ( g:ctrlp_builtins + 1 )][3] : s:itemtype - if str == '..' && type =~ '0\|dir' - cal s:parentdir(getcwd()) - cal s:SetLines(s:itemtype) - cal s:PrtClear() - retu 1 - elsei ( str == '/' || str == '\' ) && type =~ '0\|dir' - cal s:SetWD(2, 0) - cal s:SetLines(s:itemtype) - cal s:PrtClear() - retu 1 - elsei str == '?' - cal s:PrtExit() - let hlpwin = &columns > 159 ? '| vert res 80' : '' - sil! exe 'bo vert h ctrlp-mappings' hlpwin '| norm! 0' - retu 1 - en - retu 0 -endf - -fu! s:lastvisual() - let cview = winsaveview() - let [ovreg, ovtype] = [getreg('v'), getregtype('v')] - let [oureg, outype] = [getreg('"'), getregtype('"')] - sil! norm! gv"vy - let selected = substitute(getreg('v'), '\n', '\\n', 'g') - cal setreg('v', ovreg, ovtype) - cal setreg('"', oureg, outype) - cal winrestview(cview) - retu selected -endf - -fu! ctrlp#msg(msg) - echoh Identifier | echon "CtrlP: ".a:msg | echoh None -endf - -fu! s:openfile(cmd, filpath, ...) - let cmd = a:cmd == 'e' && &modified ? 'hid e' : a:cmd - let tail = a:0 ? a:1 : s:tail() - try - exe cmd.tail.' '.ctrlp#fnesc(a:filpath) - cat - cal ctrlp#msg("Operation can't be completed. Make sure filename is valid.") - fina - if !empty(tail) - sil! norm! zOzz - en - endt -endf - -fu! s:writecache(read_cache, cache_file) - if !a:read_cache && ( ( g:ctrlp_newcache || !filereadable(a:cache_file) ) - \ && s:caching || len(g:ctrlp_allfiles) > s:nocache_lim ) - if len(g:ctrlp_allfiles) > s:nocache_lim | let s:caching = 1 | en - cal ctrlp#utils#writecache(g:ctrlp_allfiles) - en -endf - -fu! s:j2l(nr) - exe a:nr - sil! norm! zOzz -endf - -fu! s:regexfilter(str) - let str = a:str - let pats = { - \ '^\(\\|\)\|\(\\|\)$': '\\|', - \ '^\\\(zs\|ze\|<\|>\)': '^\\\(zs\|ze\|<\|>\)', - \ '^\S\*$': '\*', - \ '^\S\\?$': '\\?', - \ } - for key in keys(pats) | if match(str, key) >= 0 - let str = substitute(str, pats[key], '', 'g') - en | endfo - retu str -endf - -fu! s:walker(max, pos, dir) - retu a:dir > 0 ? a:pos < a:max ? a:pos + 1 : 0 : a:pos > 0 ? a:pos - 1 : a:max -endf - -fu! s:matchfname(item, pat) - retu match(split(a:item, '[\/]\ze[^\/]\+$')[-1], a:pat) -endf - -fu! s:matchtab(item, pat) - retu match(split(a:item, '\t\+[^\t]\+$')[0], a:pat) -endf - -fu! s:maxfiles(len) - retu s:maxfiles && a:len > s:maxfiles ? 1 : 0 -endf - -fu! s:insertcache(str) - let [data, g:ctrlp_newcache, str] = [g:ctrlp_allfiles, 1, a:str] - if strlen(str) <= strlen(data[0]) - let pos = 0 - elsei strlen(str) >= strlen(data[-1]) - let pos = len(data) - 1 - el - let pos = 0 - for each in data - if strlen(each) > strlen(str) | brea | en - let pos += 1 - endfo - en - cal insert(data, str, pos) - cal s:writecache(0, ctrlp#utils#cachefile()) -endf - -fu! s:lscommand() - let cmd = s:usrcmd - if type(cmd) == 1 - retu cmd - elsei type(cmd) == 3 && len(cmd) >= 2 && !empty(cmd[0]) && !empty(cmd[1]) - let rmarker = cmd[0] - " Find a repo root - cal s:findroot(getcwd(), rmarker, 0, 1) - if !exists('s:vcsroot') || ( exists('s:vcsroot') && empty(s:vcsroot) ) - " Try the secondary_command - retu len(cmd) == 3 ? cmd[2] : '' - en - let s:vcscmd = s:lash == '\' ? 1 : 0 - retu cmd[1] - en -endf -" Extensions {{{2 -fu! s:tagfiles() - retu filter(map(tagfiles(), 'fnamemodify(v:val, ":p")'), 'filereadable(v:val)') -endf - -fu! ctrlp#exit() - cal s:PrtExit() -endf - -fu! ctrlp#prtclear() - cal s:PrtClear() -endf - -fu! ctrlp#setlines(type) - cal s:SetLines(a:type) -endf -"}}}1 -" * Initialization {{{1 -fu! s:SetLines(type) - let s:itemtype = a:type - let types = [ - \ 's:Files()', - \ 's:Buffers()', - \ 'ctrlp#mrufiles#list(-1)', - \ ] - if exists('g:ctrlp_ext_vars') - cal map(copy(g:ctrlp_ext_vars), 'add(types, v:val[0])') - en - let g:ctrlp_lines = eval(types[a:type]) -endf - -fu! ctrlp#init(type, ...) - if exists('s:init') | retu | en - let [s:matches, s:init] = [1, 1] - cal s:Open() - cal s:SetWD(exists('a:1') ? a:1 : '') - cal s:MapKeys() - cal s:SetLines(a:type) - cal s:BuildPrompt(1) - if has('syntax') && exists('g:syntax_on') - cal s:syntax() - en -endf -if has('autocmd') "{{{1 - aug CtrlPAug - au! - au BufEnter ControlP cal s:checkbuf() - au BufLeave ControlP cal s:Close() - au VimLeavePre * cal s:leavepre() - if s:lazy - au CursorHold ControlP cal s:ForceUpdate() - en - aug END -en "}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/dir.vim b/.vim/autoload/ctrlp/dir.vim deleted file mode 100644 index 46e4403..0000000 --- a/.vim/autoload/ctrlp/dir.vim +++ /dev/null @@ -1,95 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/dir.vim -" Description: Directory extension -" Author: Kien Nguyen -" ============================================================================= - -" Init {{{1 -if exists('g:loaded_ctrlp_dir') && g:loaded_ctrlp_dir - fini -en -let [g:loaded_ctrlp_dir, g:ctrlp_newdir] = [1, 0] - -let s:ars = [ - \ 's:folsym', - \ 's:dotfiles', - \ 's:maxdepth', - \ 's:maxfiles', - \ 's:compare_lim', - \ 's:glob', - \ ] - -let s:dir_var = ['ctrlp#dir#init('.join(s:ars, ', ').')', 'ctrlp#dir#accept', - \ 'dirs', 'dir'] - -let g:ctrlp_ext_vars = exists('g:ctrlp_ext_vars') && !empty(g:ctrlp_ext_vars) - \ ? add(g:ctrlp_ext_vars, s:dir_var) : [s:dir_var] - -let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars) -" Utilities {{{1 -fu! s:globdirs(dirs, depth) - let entries = split(globpath(a:dirs, s:glob), "\n") - if !s:folsym - let entries = filter(entries, 'getftype(v:val) != "link"') - en - let ftrfunc = s:dotfiles ? 'ctrlp#dirfilter(v:val)' : 'isdirectory(v:val)' - let alldirs = filter(entries, ftrfunc) - cal extend(g:ctrlp_alldirs, alldirs) - let depth = a:depth + 1 - if !empty(g:ctrlp_alldirs) && !s:max(len(g:ctrlp_alldirs), s:maxfiles) - \ && depth <= s:maxdepth - sil! cal ctrlp#progress(len(g:ctrlp_alldirs)) - cal s:globdirs(join(alldirs, ','), depth) - en -endf - -fu! s:max(len, max) - retu a:max && a:len > a:max ? 1 : 0 -endf -" Public {{{1 -fu! ctrlp#dir#init(...) - let s:cwd = getcwd() - for each in range(len(s:ars)) - exe 'let' s:ars[each] '=' string(eval('a:'.(each + 1))) - endfo - let cadir = ctrlp#utils#cachedir().ctrlp#utils#lash().s:dir_var[3] - let cafile = cadir.ctrlp#utils#lash().ctrlp#utils#cachefile(s:dir_var[3]) - if g:ctrlp_newdir || !filereadable(cafile) - let g:ctrlp_alldirs = [] - cal s:globdirs(s:cwd, 0) - cal ctrlp#rmbasedir(g:ctrlp_alldirs) - let read_cache = 0 - el - let g:ctrlp_alldirs = ctrlp#utils#readfile(cafile) - let read_cache = 1 - en - if len(g:ctrlp_alldirs) <= s:compare_lim - cal sort(g:ctrlp_alldirs, 'ctrlp#complen') - en - if !read_cache - cal ctrlp#utils#writecache(g:ctrlp_alldirs, cadir, cafile) - let g:ctrlp_newdir = 0 - en - retu g:ctrlp_alldirs -endf - -fu! ctrlp#dir#accept(mode, str) - let path = a:mode == 'h' ? getcwd() : s:cwd.ctrlp#utils#lash().a:str - if a:mode =~ 't\|v\|h' - cal ctrlp#exit() - en - cal ctrlp#setdir(path, a:mode =~ 't\|h' ? 'chd!' : 'lc!') - if a:mode == 'e' - sil! cal ctrlp#statusline() - cal ctrlp#setlines(s:id) - cal ctrlp#recordhist() - cal ctrlp#prtclear() - en -endf - -fu! ctrlp#dir#id() - retu s:id -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/line.vim b/.vim/autoload/ctrlp/line.vim deleted file mode 100644 index 964de64..0000000 --- a/.vim/autoload/ctrlp/line.vim +++ /dev/null @@ -1,61 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/line.vim -" Description: Line extension - find a line in any buffer. -" Author: Kien Nguyen -" ============================================================================= - -" Init {{{1 -if exists('g:loaded_ctrlp_line') && g:loaded_ctrlp_line - fini -en -let g:loaded_ctrlp_line = 1 - -let s:line_var = ['ctrlp#line#init()', 'ctrlp#line#accept', 'lines', 'line'] - -let g:ctrlp_ext_vars = exists('g:ctrlp_ext_vars') && !empty(g:ctrlp_ext_vars) - \ ? add(g:ctrlp_ext_vars, s:line_var) : [s:line_var] - -let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars) -" Public {{{1 -fu! ctrlp#line#init() - let [bufs, lines] = [[], []] - for each in range(1, bufnr('$')) - if getbufvar(each, '&bl') - let bufname = bufname(each) - if strlen(bufname) && bufname != 'ControlP' - cal add(bufs, fnamemodify(bufname, ':p')) - en - en - endfo - cal filter(bufs, 'filereadable(v:val)') - for each in bufs - let from_file = readfile(each) - cal map(from_file, 'tr(v:val, '' '', '' '')') - let [id, len_ff, bufnr] = [1, len(from_file), bufnr(each)] - wh id <= len_ff - let from_file[id-1] .= ' #:'.bufnr.':'.id - let id += 1 - endw - cal filter(from_file, 'v:val !~ ''^\s*\t#:\d\+:\d\+$''') - cal extend(lines, from_file) - endfo - sy match CtrlPTabExtra '\zs\t.*\ze$' - hi link CtrlPTabExtra Comment - retu lines -endf - -fu! ctrlp#line#accept(mode, str) - let info = get(split(a:str, '\t#:\ze\d\+:\d\+$'), 1, 0) - let bufnr = str2nr(get(split(info, ':'), 0, 0)) - let linenr = get(split(info, ':'), 1, 0) - if bufnr - cal ctrlp#acceptfile(a:mode, fnamemodify(bufname(bufnr), ':p'), linenr) - en -endf - -fu! ctrlp#line#id() - retu s:id -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/mrufiles.vim b/.vim/autoload/ctrlp/mrufiles.vim deleted file mode 100644 index fa3a67f..0000000 --- a/.vim/autoload/ctrlp/mrufiles.vim +++ /dev/null @@ -1,68 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/mrufiles.vim -" Description: Most Recently Used Files extension -" Author: Kien Nguyen -" ============================================================================= - -" Static variables {{{1 -fu! ctrlp#mrufiles#opts() - let opts = { - \ 'g:ctrlp_mruf_max': ['s:max', 250], - \ 'g:ctrlp_mruf_include': ['s:include', ''], - \ 'g:ctrlp_mruf_exclude': ['s:exclude', ''], - \ 'g:ctrlp_mruf_case_sensitive': ['s:csen', 1], - \ } - for [ke, va] in items(opts) - exe 'let' va[0] '=' string(exists(ke) ? eval(ke) : va[1]) - endfo -endf -cal ctrlp#mrufiles#opts() -fu! ctrlp#mrufiles#list(bufnr, ...) "{{{1 - if s:locked | retu | en - " Get the list - let cadir = ctrlp#utils#cachedir().ctrlp#utils#lash().'mru' - let cafile = cadir.ctrlp#utils#lash().'cache.txt' - let mrufs = ctrlp#utils#readfile(cafile) - " Remove non-existent files - if exists('a:1') && a:1 == 1 - let mrufs = s:rmdeleted(mrufs, cadir, cafile) - elsei exists('a:1') && a:1 == 2 - cal ctrlp#utils#writecache([], cadir, cafile) - retu [] - en - " Return the list - if a:bufnr == -1 | retu mrufs | en - " Filter it - let filename = fnamemodify(bufname(a:bufnr + 0), ':p') - if empty(filename) || !empty(&bt) - \ || ( !empty(s:include) && filename !~# s:include ) - \ || ( !empty(s:exclude) && filename =~# s:exclude ) - \ || ( index(mrufs, filename) == -1 && !filereadable(filename) ) - retu - en - " Remove old matched entry - cal filter(mrufs, 'v:val !='.( s:csen ? "#" : "?" ).' filename') - " Insert new one - cal insert(mrufs, filename) - " Remove oldest entry - if len(mrufs) > s:max | cal remove(mrufs, s:max, -1) | en - cal ctrlp#utils#writecache(mrufs, cadir, cafile) -endf "}}} -fu! s:rmdeleted(mrufs, cadir, cafile) "{{{ - cal filter(a:mrufs, '!empty(ctrlp#utils#glob(v:val, 1))') - cal ctrlp#utils#writecache(a:mrufs, a:cadir, a:cafile) - retu a:mrufs -endf -fu! ctrlp#mrufiles#init() "{{{1 - let s:locked = 0 - aug CtrlPMRUF - au! - au BufReadPost,BufNewFile,BufWritePost * - \ cal ctrlp#mrufiles#list(expand('', 1)) - au QuickFixCmdPre *vimgrep* let s:locked = 1 - au QuickFixCmdPost *vimgrep* let s:locked = 0 - aug END -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/quickfix.vim b/.vim/autoload/ctrlp/quickfix.vim deleted file mode 100644 index 0013481..0000000 --- a/.vim/autoload/ctrlp/quickfix.vim +++ /dev/null @@ -1,55 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/quickfix.vim -" Description: Quickfix extension -" Author: Kien Nguyen -" ============================================================================= - -" Init {{{1 -if exists('g:loaded_ctrlp_quickfix') && g:loaded_ctrlp_quickfix - fini -en -let g:loaded_ctrlp_quickfix = 1 - -let s:var_qf = ['ctrlp#quickfix#init()', 'ctrlp#quickfix#accept', 'quickfix', - \ 'qfx', [1]] - -let g:ctrlp_ext_vars = exists('g:ctrlp_ext_vars') && !empty(g:ctrlp_ext_vars) - \ ? add(g:ctrlp_ext_vars, s:var_qf) : [s:var_qf] - -let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars) - -fu! s:lineout(dict) - retu printf('%s|%d:%d| %s', bufname(a:dict['bufnr']), a:dict['lnum'], - \ a:dict['col'], matchstr(a:dict['text'], '\s*\zs.*\S')) -endf -" Public {{{1 -fu! ctrlp#quickfix#init() - let g:ctrlp_nolimit = 1 - sy match CtrlPqfLineCol '|\zs\d\+:\d\+\ze|' - hi def link CtrlPqfLineCol Search - retu map(getqflist(), 's:lineout(v:val)') -endf - -fu! ctrlp#quickfix#accept(mode, str) - let items = matchlist(a:str, '^\([^|]\+\ze\)|\(\d\+\):\(\d\+\)|') - let [md, filpath] = [a:mode, fnamemodify(items[1], ':p')] - if empty(filpath) | retu | en - cal ctrlp#exit() - let cmd = md == 't' ? 'tabe' : md == 'h' ? 'new' : md == 'v' ? 'vne' - \ : ctrlp#normcmd('e') - let cmd = cmd == 'e' && &modified ? 'hid e' : cmd - try - exe cmd.' '.ctrlp#fnesc(filpath) - cat - cal ctrlp#msg("Invalid command or argument.") - fina - cal cursor(items[2], items[3]) | sil! norm! zOzz - endt -endf - -fu! ctrlp#quickfix#id() - retu s:id -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/tag.vim b/.vim/autoload/ctrlp/tag.vim deleted file mode 100644 index 8be9e48..0000000 --- a/.vim/autoload/ctrlp/tag.vim +++ /dev/null @@ -1,109 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/tag.vim -" Description: Tag file extension -" Author: Kien Nguyen -" ============================================================================= - -" Init {{{1 -if exists('g:loaded_ctrlp_tag') && g:loaded_ctrlp_tag - fini -en -let g:loaded_ctrlp_tag = 1 - -let s:tag_var = ['ctrlp#tag#init(s:tagfiles)', 'ctrlp#tag#accept', - \ 'tags', 'tag'] - -let g:ctrlp_ext_vars = exists('g:ctrlp_ext_vars') && !empty(g:ctrlp_ext_vars) - \ ? add(g:ctrlp_ext_vars, s:tag_var) : [s:tag_var] - -let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars) -" Utilities {{{1 -fu! s:nodup(items) - let dict = {} - for each in a:items - cal extend(dict, { each : 0 }) - endfo - retu keys(dict) -endf - -fu! s:findcount(str) - let [tg, fname] = split(a:str, '\t\+\ze[^\t]\+$') - let [&l:tags, fname] = [s:ltags, expand(fname, 1)] - let tgs = taglist('^'.tg.'$') - if empty(tgs) | retu [1, 1] | en - let [fnd, ct, pos] = [0, 0, 0] - for each in tgs - let ct += 1 - let fulname = fnamemodify(each["filename"], ':p') - if stridx(fulname, fname) >= 0 - \ && strlen(fname) + stridx(fulname, fname) == strlen(fulname) - let fnd += 1 - let pos = ct - en - if fnd > 1 | brea | en - endfo - retu [fnd, pos] -endf - -fu! s:filter(tags) - let [nr, alltags] = [0, a:tags] - wh 0 < 1 - if alltags[nr] =~ '^!' && alltags[nr] !~ '^!_TAG_' - let nr += 1 - con - en - if alltags[nr] =~ '^!_TAG_' && len(alltags) > nr - cal remove(alltags, nr) - el - brea - en - endw - retu alltags -endf -" Public {{{1 -fu! ctrlp#tag#init(tagfiles) - if empty(a:tagfiles) | retu [] | en - let tagfiles = sort(s:nodup(a:tagfiles)) - let s:ltags = join(tagfiles, ',') - let g:ctrlp_alltags = [] - for each in tagfiles - let alltags = s:filter(ctrlp#utils#readfile(each)) - cal extend(g:ctrlp_alltags, alltags) - endfo - sy match CtrlPTabExtra '\zs\t.*\ze$' - hi link CtrlPTabExtra Comment - retu g:ctrlp_alltags -endf - -fu! ctrlp#tag#accept(mode, str) - cal ctrlp#exit() - let str = matchstr(a:str, '^[^\t]\+\t\+[^\t]\+\ze\t') - let [md, tg] = [a:mode, split(str, '^[^\t]\+\zs\t')[0]] - let fnd = s:findcount(str) - let cmds = { - \ 't': ['tabe', 'tab stj'], - \ 'h': ['new', 'stj'], - \ 'v': ['vne', 'vert stj'], - \ 'e': ['ene', 'tj'], - \ } - let cmd = fnd[0] == 1 ? cmds[md][0] : cmds[md][1] - let cmd = cmd =~ 'tj\|ene' && &modified ? 'hid '.cmd : cmd - try - if fnd[0] == 1 - exe cmd - let &l:tags = s:ltags - exe fnd[1].'ta' tg - el - exe cmd.' '.tg - en - cat - cal ctrlp#msg("Tag not found.") - endt -endf - -fu! ctrlp#tag#id() - retu s:id -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/ctrlp/utils.vim b/.vim/autoload/ctrlp/utils.vim deleted file mode 100644 index 2f1517a..0000000 --- a/.vim/autoload/ctrlp/utils.vim +++ /dev/null @@ -1,68 +0,0 @@ -" ============================================================================= -" File: autoload/ctrlp/utils.vim -" Description: Utilities -" Author: Kien Nguyen -" ============================================================================= - -" Static variables {{{1 -fu! ctrlp#utils#lash() - retu &ssl || !exists('+ssl') ? '/' : '\' -endf -let s:lash = ctrlp#utils#lash() - -fu! ctrlp#utils#opts() - let s:cache_dir = $HOME.s:lash.'.ctrlp_cache' - if exists('g:ctrlp_cache_dir') - let s:cache_dir = expand(g:ctrlp_cache_dir, 1) - if isdirectory(s:cache_dir.s:lash.'.ctrlp_cache') - let s:cache_dir = s:cache_dir.s:lash.'.ctrlp_cache' - en - en -endf -cal ctrlp#utils#opts() -" Files and Directories {{{1 -fu! ctrlp#utils#cachedir() - retu s:cache_dir -endf - -fu! ctrlp#utils#cachefile(...) - let tail = exists('a:1') ? '.'.a:1 : '' - let cache_file = substitute(getcwd(), '\([\/]\|^\a\zs:\)', '%', 'g').tail.'.txt' - retu exists('a:1') ? cache_file : s:cache_dir.s:lash.cache_file -endf - -fu! ctrlp#utils#readfile(file) - if filereadable(a:file) - let data = readfile(a:file) - if empty(data) || type(data) != 3 - unl data - let data = [] - en - retu data - en - retu [] -endf - -fu! ctrlp#utils#mkdir(dir) - if exists('*mkdir') && !isdirectory(a:dir) - sil! cal mkdir(a:dir) - en -endf - -fu! ctrlp#utils#writecache(lines, ...) - let cache_dir = exists('a:1') ? a:1 : s:cache_dir - cal ctrlp#utils#mkdir(cache_dir) - if isdirectory(cache_dir) - sil! cal writefile(a:lines, exists('a:2') ? a:2 : ctrlp#utils#cachefile()) - if !exists('a:1') - let g:ctrlp_newcache = 0 - en - en -endf - -fu! ctrlp#utils#glob(...) - retu call('glob', v:version > 701 ? a:000 : a:1) -endf -"}}} - -" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2 diff --git a/.vim/autoload/fuf.vim b/.vim/autoload/fuf.vim deleted file mode 100644 index fe9e6eb..0000000 --- a/.vim/autoload/fuf.vim +++ /dev/null @@ -1,1046 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - - -" returns list of paths. -" An argument for glob() is normalized in order to avoid a bug on Windows. -function fuf#glob(expr) - " Substitutes "\", because on Windows, "**\" doesn't include ".\", - " but "**/" include "./". I don't know why. - return split(glob(substitute(a:expr, '\', '/', 'g')), "\n") -endfunction - -" -function fuf#countModifiedFiles(files, time) - return len(filter(copy(a:files), 'getftime(expand(v:val)) > a:time')) -endfunction - -" -function fuf#getCurrentTagFiles() - return sort(filter(map(tagfiles(), 'fnamemodify(v:val, '':p'')'), 'filereadable(v:val)')) -endfunction - -" -function fuf#mapToSetSerialIndex(in, offset) - for i in range(len(a:in)) - let a:in[i].index = i + a:offset - endfor - return a:in -endfunction - -" -function fuf#updateMruList(mrulist, newItem, maxItem, exclude) - let result = copy(a:mrulist) - let result = filter(result,'v:val.word !=# a:newItem.word') - let result = insert(result, a:newItem) - if len(a:exclude) - let result = filter(result, 'v:val.word !~ a:exclude') - endif - return result[0 : a:maxItem - 1] -endfunction - -" takes suffix number. if no digits, returns -1 -function fuf#suffixNumber(str) - let s = matchstr(a:str, '\d\+$') - return (len(s) ? str2nr(s) : -1) -endfunction - -" "foo/bar/buz/hoge" -> { head: "foo/bar/buz/", tail: "hoge" } -function fuf#splitPath(path) - let head = matchstr(a:path, '^.*[/\\]') - return { - \ 'head' : head, - \ 'tail' : a:path[strlen(head):] - \ } -endfunction - -" "foo/.../bar/...hoge" -> "foo/.../bar/../../hoge" -function fuf#expandTailDotSequenceToParentDir(pattern) - return substitute(a:pattern, '^\(.*[/\\]\)\?\zs\.\(\.\+\)\ze[^/\\]*$', - \ '\=repeat(".." . l9#getPathSeparator(), len(submatch(2)))', '') -endfunction - -" -function fuf#formatPrompt(prompt, partialMatching, otherString) - let indicator = escape((a:partialMatching ? '!' : '') . a:otherString, '\') - return substitute(a:prompt, '[]', indicator, 'g') -endfunction - -" -function fuf#getFileLines(file) - let bufnr = (type(a:file) ==# type(0) ? a:file : bufnr('^' . a:file . '$')) - let lines = getbufline(bufnr, 1, '$') - if !empty(lines) - return lines - endif - return l9#readFile(a:file) -endfunction - -" -function fuf#makePreviewLinesAround(lines, indices, page, maxHeight) - let index = ((empty(a:indices) ? 0 : a:indices[0]) - \ + a:page * a:maxHeight) % len(a:lines) - if empty(a:lines) || a:maxHeight <= 0 - return [] - endif - let beg = max([0, index - a:maxHeight / 2]) - let end = min([beg + a:maxHeight, len(a:lines)]) - let beg = max([0, end - a:maxHeight]) - let lines = [] - for i in range(beg, end - 1) - let mark = (count(a:indices, i) ? '>' : ' ') - call add(lines, printf('%s%4d ', mark, i + 1) . a:lines[i]) - endfor - return lines -endfunction - -" a:file: a path string or a buffer number -function fuf#makePreviewLinesForFile(file, count, maxHeight) - let lines = fuf#getFileLines(a:file) - if empty(lines) - return [] - endif - let bufnr = (type(a:file) ==# type(0) ? a:file : bufnr('^' . a:file . '$')) - if exists('s:bufferCursorPosMap[bufnr]') - let indices = [s:bufferCursorPosMap[bufnr][1] - 1] - else - let indices = [] - endif - return fuf#makePreviewLinesAround( - \ lines, indices, a:count, a:maxHeight) -endfunction - -" -function fuf#echoWarning(msg) - call l9#echoHl('WarningMsg', a:msg, '[fuf] ', 1) -endfunction - -" -function fuf#echoError(msg) - call l9#echoHl('ErrorMsg', a:msg, '[fuf] ', 1) -endfunction - -" -function fuf#openBuffer(bufNr, mode, reuse) - if a:reuse && ((a:mode ==# s:OPEN_TYPE_SPLIT && - \ l9#moveToBufferWindowInCurrentTabpage(a:bufNr)) || - \ (a:mode ==# s:OPEN_TYPE_VSPLIT && - \ l9#moveToBufferWindowInCurrentTabpage(a:bufNr)) || - \ (a:mode ==# s:OPEN_TYPE_TAB && - \ l9#moveToBufferWindowInOtherTabpage(a:bufNr))) - return - endif - execute printf({ - \ s:OPEN_TYPE_CURRENT : '%sbuffer' , - \ s:OPEN_TYPE_SPLIT : '%ssbuffer' , - \ s:OPEN_TYPE_VSPLIT : 'vertical %ssbuffer', - \ s:OPEN_TYPE_TAB : 'tab %ssbuffer' , - \ }[a:mode], a:bufNr) -endfunction - -" -function fuf#openFile(path, mode, reuse) - let bufNr = bufnr('^' . a:path . '$') - if bufNr > -1 - call fuf#openBuffer(bufNr, a:mode, a:reuse) - else - execute { - \ s:OPEN_TYPE_CURRENT : 'edit ' , - \ s:OPEN_TYPE_SPLIT : 'split ' , - \ s:OPEN_TYPE_VSPLIT : 'vsplit ' , - \ s:OPEN_TYPE_TAB : 'tabedit ', - \ }[a:mode] . fnameescape(fnamemodify(a:path, ':~:.')) - endif -endfunction - -" -function fuf#openTag(tag, mode) - execute { - \ s:OPEN_TYPE_CURRENT : 'tjump ' , - \ s:OPEN_TYPE_SPLIT : 'stjump ' , - \ s:OPEN_TYPE_VSPLIT : 'vertical stjump ', - \ s:OPEN_TYPE_TAB : 'tab stjump ' , - \ }[a:mode] . a:tag -endfunction - -" -function fuf#openHelp(tag, mode) - execute { - \ s:OPEN_TYPE_CURRENT : 'help ' , - \ s:OPEN_TYPE_SPLIT : 'help ' , - \ s:OPEN_TYPE_VSPLIT : 'vertical help ', - \ s:OPEN_TYPE_TAB : 'tab help ' , - \ }[a:mode] . a:tag -endfunction - -" -function fuf#prejump(mode) - execute { - \ s:OPEN_TYPE_CURRENT : '' , - \ s:OPEN_TYPE_SPLIT : 'split' , - \ s:OPEN_TYPE_VSPLIT : 'vsplit' , - \ s:OPEN_TYPE_TAB : 'tab split', - \ }[a:mode] -endfunction - -" -function fuf#compareRanks(i1, i2) - if exists('a:i1.ranks') && exists('a:i2.ranks') - for i in range(min([len(a:i1.ranks), len(a:i2.ranks)])) - if a:i1.ranks[i] > a:i2.ranks[i] - return +1 - elseif a:i1.ranks[i] < a:i2.ranks[i] - return -1 - endif - endfor - endif - return 0 -endfunction - -" -function fuf#makePathItem(fname, menu, appendsDirSuffix) - let pathPair = fuf#splitPath(a:fname) - let dirSuffix = (a:appendsDirSuffix && isdirectory(expand(a:fname)) - \ ? l9#getPathSeparator() - \ : '') - return { - \ 'word' : a:fname . dirSuffix, - \ 'wordForPrimaryHead': s:toLowerForIgnoringCase(pathPair.head), - \ 'wordForPrimaryTail': s:toLowerForIgnoringCase(pathPair.tail), - \ 'wordForBoundary' : s:toLowerForIgnoringCase(s:getWordBoundaries(pathPair.tail)), - \ 'wordForRefining' : s:toLowerForIgnoringCase(a:fname . dirSuffix), - \ 'wordForRank' : s:toLowerForIgnoringCase(pathPair.tail), - \ 'menu' : a:menu, - \ } -endfunction - -" -function fuf#makeNonPathItem(word, menu) - let wordL = s:toLowerForIgnoringCase(a:word) - return { - \ 'word' : a:word, - \ 'wordForPrimary' : wordL, - \ 'wordForBoundary': s:toLowerForIgnoringCase(s:getWordBoundaries(a:word)), - \ 'wordForRefining': wordL, - \ 'wordForRank' : wordL, - \ 'menu' : a:menu, - \ } -endfunction - -" -function fuf#makePatternSet(patternBase, interpreter, partialMatching) - let MakeMatchingExpr = function(a:partialMatching - \ ? 's:makePartialMatchingExpr' - \ : 's:makeFuzzyMatchingExpr') - let [primary; refinings] = split(a:patternBase, g:fuf_patternSeparator, 1) - let elements = call(a:interpreter, [primary]) - let primaryExprs = map(elements.matchingPairs, 'MakeMatchingExpr(v:val[0], v:val[1])') - let refiningExprs = map(refinings, 's:makeRefiningExpr(v:val)') - return { - \ 'primary' : elements.primary, - \ 'primaryForRank': elements.primaryForRank, - \ 'filteringExpr' : join(primaryExprs + refiningExprs, ' && '), - \ } -endfunction - -" -function fuf#enumExpandedDirsEntries(dir, exclude) - let entries = fuf#glob(a:dir . '*') + fuf#glob(a:dir . '.*') - " removes "*/." and "*/.." - call filter(entries, 'v:val !~ ''\v(^|[/\\])\.\.?$''') - call map(entries, 'fuf#makePathItem(v:val, "", 1)') - if len(a:exclude) - call filter(entries, 'v:val.word !~ a:exclude') - endif - return entries -endfunction - -" -function fuf#mapToSetAbbrWithSnippedWordAsPath(items) - let maxLenStats = {} - call map(a:items, 's:makeFileAbbrInfo(v:val, maxLenStats)') - let snippedHeads = - \ map(maxLenStats, 's:getSnippedHead(v:key[: -2], v:val)') - return map(a:items, 's:setAbbrWithFileAbbrData(v:val, snippedHeads)') -endfunction - -" -function fuf#setAbbrWithFormattedWord(item, abbrIndex) - let lenMenu = (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - let abbrPrefix = (exists('a:item.abbrPrefix') ? a:item.abbrPrefix : '') - let a:item.abbr = abbrPrefix . a:item.word - if a:abbrIndex - let a:item.abbr = printf('%4d: ', a:item.index) . a:item.abbr - endif - let a:item.abbr = l9#snipTail(a:item.abbr, g:fuf_maxMenuWidth - lenMenu, s:ABBR_SNIP_MASK) - return a:item -endfunction - -" -function s:onCommandPre() - for m in filter(copy(fuf#getModeNames()), 'fuf#{v:val}#requiresOnCommandPre()') - call fuf#{m}#onCommandPre(getcmdtype() . getcmdline()) - endfor - " lets last entry become the newest in the history - call histadd(getcmdtype(), getcmdline()) - " this is not mapped again (:help recursive_mapping) - return "\" -endfunction - -" -let s:modeNames = [] - -" -function fuf#addMode(modeName) - if count(g:fuf_modesDisable, a:modeName) > 0 - return - endif - call add(s:modeNames, a:modeName) - call fuf#{a:modeName}#renewCache() - call fuf#{a:modeName}#onInit() - if fuf#{a:modeName}#requiresOnCommandPre() - " cnoremap has a problem, which doesn't expand cabbrev. - cmap onCommandPre() - endif -endfunction - -" -function fuf#getModeNames() - return s:modeNames -endfunction - -" -function fuf#defineLaunchCommand(CmdName, modeName, prefixInitialPattern, tempVars) - if empty(a:tempVars) - let preCmd = '' - else - let preCmd = printf('call l9#tempvariables#setList(%s, %s) | ', - \ string(s:TEMP_VARIABLES_GROUP), string(a:tempVars)) - endif - execute printf('command! -range -bang -narg=? %s %s call fuf#launch(%s, %s . , len())', - \ a:CmdName, preCmd, string(a:modeName), a:prefixInitialPattern) -endfunction - -" -function fuf#defineKeyMappingInHandler(key, func) - " hacks to be able to use feedkeys(). - execute printf( - \ 'inoremap %s =fuf#getRunningHandler().%s ? "" : ""', - \ a:key, a:func) -endfunction - -" -let s:oneTimeVariables = [] - -" -function fuf#setOneTimeVariables(...) - let s:oneTimeVariables += a:000 -endfunction - -" -function fuf#launch(modeName, initialPattern, partialMatching) - if exists('s:runningHandler') - call fuf#echoWarning('FuzzyFinder is running.') - endif - if count(fuf#getModeNames(), a:modeName) == 0 - echoerr 'This mode is not available: ' . a:modeName - return - endif - let s:runningHandler = fuf#{a:modeName}#createHandler(copy(s:handlerBase)) - let s:runningHandler.stats = fuf#loadDataFile(s:runningHandler.getModeName(), 'stats') - let s:runningHandler.partialMatching = a:partialMatching - let s:runningHandler.bufNrPrev = bufnr('%') - let s:runningHandler.lastCol = -1 - let s:runningHandler.windowRestoringCommand = winrestcmd() - call s:runningHandler.onModeEnterPre() - " NOTE: updatetime is set, because in Buffer-Tag mode on Vim 7.3 on Windows, - " Vim keeps from triggering CursorMovedI for updatetime after system() is - " called. I don't know why. - call fuf#setOneTimeVariables( - \ ['&completeopt', 'menuone'], - \ ['&ignorecase', 0], - \ ['&updatetime', 10], - \ ) - if s:runningHandler.getPreviewHeight() > 0 - call fuf#setOneTimeVariables( - \ ['&cmdheight', s:runningHandler.getPreviewHeight() + 1]) - endif - call l9#tempvariables#setList(s:TEMP_VARIABLES_GROUP, s:oneTimeVariables) - let s:oneTimeVariables = [] - call s:activateFufBuffer() - augroup FufLocal - autocmd! - autocmd CursorMovedI call s:runningHandler.onCursorMovedI() - autocmd InsertLeave nested call s:runningHandler.onInsertLeave() - augroup END - for [key, func] in [ - \ [ g:fuf_keyOpen , 'onCr(' . s:OPEN_TYPE_CURRENT . ')' ], - \ [ g:fuf_keyOpenSplit , 'onCr(' . s:OPEN_TYPE_SPLIT . ')' ], - \ [ g:fuf_keyOpenVsplit , 'onCr(' . s:OPEN_TYPE_VSPLIT . ')' ], - \ [ g:fuf_keyOpenTabpage , 'onCr(' . s:OPEN_TYPE_TAB . ')' ], - \ [ '' , 'onBs()' ], - \ [ '' , 'onBs()' ], - \ [ '' , 'onDeleteWord()' ], - \ [ g:fuf_keyPreview , 'onPreviewBase(1)' ], - \ [ g:fuf_keyNextMode , 'onSwitchMode(+1)' ], - \ [ g:fuf_keyPrevMode , 'onSwitchMode(-1)' ], - \ [ g:fuf_keySwitchMatching, 'onSwitchMatching()' ], - \ [ g:fuf_keyPrevPattern , 'onRecallPattern(+1)' ], - \ [ g:fuf_keyNextPattern , 'onRecallPattern(-1)' ], - \ ] - call fuf#defineKeyMappingInHandler(key, func) - endfor - " Starts Insert mode and makes CursorMovedI event now. Command prompt is - " needed to forces a completion menu to update every typing. - call setline(1, s:runningHandler.getPrompt() . a:initialPattern) - call s:runningHandler.onModeEnterPost() - call feedkeys("A", 'n') " startinsert! does not work in InsertLeave event handler - redraw -endfunction - -" -function fuf#loadDataFile(modeName, dataName) - if !s:dataFileAvailable - return [] - endif - let lines = l9#readFile(l9#concatPaths([g:fuf_dataDir, a:modeName, a:dataName])) - return map(lines, 'eval(v:val)') -endfunction - -" -function fuf#saveDataFile(modeName, dataName, items) - if !s:dataFileAvailable - return -1 - endif - let lines = map(copy(a:items), 'string(v:val)') - return l9#writeFile(lines, l9#concatPaths([g:fuf_dataDir, a:modeName, a:dataName])) -endfunction - -" -function fuf#getDataFileTime(modeName, dataName) - if !s:dataFileAvailable - return -1 - endif - return getftime(expand(l9#concatPaths([g:fuf_dataDir, a:modeName, a:dataName]))) -endfunction - -" -function s:createDataBufferListener(dataFile) - let listener = { 'dataFile': a:dataFile } - - function listener.onWrite(lines) - let [modeName, dataName] = split(self.dataFile, l9#getPathSeparator()) - let items = map(filter(a:lines, '!empty(v:val)'), 'eval(v:val)') - call fuf#saveDataFile(modeName, dataName, items) - echo "Data files updated" - return 1 - endfunction - - return listener -endfunction - -" -function s:createEditDataListener() - let listener = {} - - function listener.onComplete(dataFile, method) - let bufName = '[fuf-info]' - let lines = l9#readFile(l9#concatPaths([g:fuf_dataDir, a:dataFile])) - call l9#tempbuffer#openWritable(bufName, 'vim', lines, 0, 0, 0, - \ s:createDataBufferListener(a:dataFile)) - endfunction - - return listener -endfunction - -" -function s:getEditableDataFiles(modeName) - let dataFiles = fuf#{a:modeName}#getEditableDataNames() - call filter(dataFiles, 'fuf#getDataFileTime(a:modeName, v:val) != -1') - return map(dataFiles, 'l9#concatPaths([a:modeName, v:val])') -endfunction - -" -function fuf#editDataFile() - let dataFiles = map(copy(fuf#getModeNames()), 's:getEditableDataFiles(v:val)') - let dataFiles = l9#concat(dataFiles) - call fuf#callbackitem#launch('', 0, '>Mode>', s:createEditDataListener(), dataFiles, 0) -endfunction - -" -function fuf#getRunningHandler() - return s:runningHandler -endfunction - -" -function fuf#onComplete(findstart, base) - return s:runningHandler.onComplete(a:findstart, a:base) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:TEMP_VARIABLES_GROUP = expand(':p') -let s:ABBR_SNIP_MASK = '...' -let s:OPEN_TYPE_CURRENT = 1 -let s:OPEN_TYPE_SPLIT = 2 -let s:OPEN_TYPE_VSPLIT = 3 -let s:OPEN_TYPE_TAB = 4 - -" a:pattern: 'str' -> '\V\.\*s\.\*t\.\*r\.\*' -function s:makeFuzzyMatchingExpr(target, pattern) - let wi = '' - for c in split(a:pattern, '\zs') - if wi =~# '[^*?]$' && c !~ '[*?]' - let wi .= '*' - endif - let wi .= c - endfor - return s:makePartialMatchingExpr(a:target, wi) -endfunction - -" a:pattern: 'str' -> '\Vstr' -" 'st*r' -> '\Vst\.\*r' -function s:makePartialMatchingExpr(target, pattern) - let patternMigemo = s:makeAdditionalMigemoPattern(a:pattern) - if a:pattern !~ '[*?]' && empty(patternMigemo) - " NOTE: stridx is faster than regexp matching - return 'stridx(' . a:target . ', ' . string(a:pattern) . ') >= 0' - endif - return a:target . ' =~# ' . - \ string(l9#convertWildcardToRegexp(a:pattern)) . patternMigemo -endfunction - -" -function s:makeRefiningExpr(pattern) - if g:fuf_fuzzyRefining - let expr = s:makeFuzzyMatchingExpr('v:val.wordForRefining', a:pattern) - else - let expr = s:makePartialMatchingExpr('v:val.wordForRefining', a:pattern) - endif - if a:pattern =~# '\D' - return expr - else - return '(' . expr . ' || v:val.index == ' . string(a:pattern) . ')' - endif -endfunction - -" -function s:makeAdditionalMigemoPattern(pattern) - if !g:fuf_useMigemo || a:pattern =~# '[^\x01-\x7e]' - return '' - endif - return '\|\m' . substitute(migemo(a:pattern), '\\_s\*', '.*', 'g') -endfunction - -" -function s:interpretPrimaryPatternForPathTail(pattern) - let pattern = fuf#expandTailDotSequenceToParentDir(a:pattern) - let pairL = fuf#splitPath(s:toLowerForIgnoringCase(pattern)) - return { - \ 'primary' : pattern, - \ 'primaryForRank': pairL.tail, - \ 'matchingPairs' : [['v:val.wordForPrimaryTail', pairL.tail],], - \ } -endfunction - -" -function s:interpretPrimaryPatternForPath(pattern) - let pattern = fuf#expandTailDotSequenceToParentDir(a:pattern) - let patternL = s:toLowerForIgnoringCase(pattern) - let pairL = fuf#splitPath(patternL) - if g:fuf_splitPathMatching - let matches = [ - \ ['v:val.wordForPrimaryHead', pairL.head], - \ ['v:val.wordForPrimaryTail', pairL.tail], - \ ] - else - let matches = [ - \ ['v:val.wordForPrimaryHead . v:val.wordForPrimaryTail', patternL], - \ ] - endif - return { - \ 'primary' : pattern, - \ 'primaryForRank': pairL.tail, - \ 'matchingPairs' : matches, - \ } -endfunction - -" -function s:interpretPrimaryPatternForNonPath(pattern) - let patternL = s:toLowerForIgnoringCase(a:pattern) - return { - \ 'primary' : a:pattern, - \ 'primaryForRank': patternL, - \ 'matchingPairs' : [['v:val.wordForPrimary', patternL],], - \ } -endfunction - -" -function s:getWordBoundaries(word) - return substitute(a:word, '\a\zs\l\+\|\zs\A', '', 'g') -endfunction - -" -function s:toLowerForIgnoringCase(str) - return (g:fuf_ignoreCase ? tolower(a:str) : a:str) -endfunction - -" -function s:setRanks(item, pattern, exprBoundary, stats) - "let word2 = substitute(a:eval_word, '\a\zs\l\+\|\zs\A', '', 'g') - let a:item.ranks = [ - \ s:evaluateLearningRank(a:item.word, a:stats), - \ -s:scoreSequentialMatching(a:item.wordForRank, a:pattern), - \ -s:scoreBoundaryMatching(a:item.wordForBoundary, - \ a:pattern, a:exprBoundary), - \ a:item.index, - \ ] - return a:item -endfunction - -" -function s:evaluateLearningRank(word, stats) - for i in range(len(a:stats)) - if a:stats[i].word ==# a:word - return i - endif - endfor - return len(a:stats) -endfunction - -" range of return value is [0.0, 1.0] -function s:scoreSequentialMatching(word, pattern) - if empty(a:pattern) - return str2float('0.0') - endif - let pos = stridx(a:word, a:pattern) - if pos < 0 - return str2float('0.0') - endif - let lenRest = len(a:word) - len(a:pattern) - pos - return str2float(pos == 0 ? '0.5' : '0.0') + str2float('0.5') / (lenRest + 1) -endfunction - -" range of return value is [0.0, 1.0] -function s:scoreBoundaryMatching(wordForBoundary, pattern, exprBoundary) - if empty(a:pattern) - return str2float('0.0') - endif - if !eval(a:exprBoundary) - return 0 - endif - return (s:scoreSequentialMatching(a:wordForBoundary, a:pattern) + 1) / 2 -endfunction - -" -function s:highlightPrompt(prompt) - syntax clear - execute printf('syntax match %s /^\V%s/', g:fuf_promptHighlight, escape(a:prompt, '\/')) -endfunction - -" -function s:highlightError() - syntax clear - syntax match Error /^.*$/ -endfunction - -" -function s:expandAbbrevMap(pattern, abbrevMap) - let result = [a:pattern] - for [pattern, subs] in items(a:abbrevMap) - let exprs = result - let result = [] - for expr in exprs - let result += map(copy(subs), 'substitute(expr, pattern, escape(v:val, ''\''), "g")') - endfor - endfor - return l9#unique(result) -endfunction - -" -function s:makeFileAbbrInfo(item, maxLenStats) - let head = matchstr(a:item.word, '^.*[/\\]\ze.') - let a:item.abbr = { 'head' : head, - \ 'tail' : a:item.word[strlen(head):], - \ 'key' : head . '.', - \ 'prefix' : printf('%4d: ', a:item.index), } - if exists('a:item.abbrPrefix') - let a:item.abbr.prefix .= a:item.abbrPrefix - endif - let len = len(a:item.abbr.prefix) + len(a:item.word) + - \ (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - if !exists('a:maxLenStats[a:item.abbr.key]') || len > a:maxLenStats[a:item.abbr.key] - let a:maxLenStats[a:item.abbr.key] = len - endif - return a:item -endfunction - -" -function s:getSnippedHead(head, baseLen) - return l9#snipMid(a:head, len(a:head) + g:fuf_maxMenuWidth - a:baseLen, s:ABBR_SNIP_MASK) -endfunction - -" -function s:setAbbrWithFileAbbrData(item, snippedHeads) - let lenMenu = (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - let abbr = a:item.abbr.prefix . a:snippedHeads[a:item.abbr.key] . a:item.abbr.tail - let a:item.abbr = l9#snipTail(abbr, g:fuf_maxMenuWidth - lenMenu, s:ABBR_SNIP_MASK) - return a:item -endfunction - -" -let s:FUF_BUF_NAME = '[fuf]' - -" -function s:activateFufBuffer() - " lcd . : To avoid the strange behavior that unnamed buffer changes its cwd - " if 'autochdir' was set on. - lcd . - let cwd = getcwd() - call l9#tempbuffer#openScratch(s:FUF_BUF_NAME, 'fuf', [], 1, 0, 1, {}) - resize 1 " for issue #21 - " lcd ... : countermeasure against auto-cd script - lcd `=cwd` - setlocal nocursorline " for highlighting - setlocal nocursorcolumn " for highlighting - setlocal omnifunc=fuf#onComplete - redraw " for 'lazyredraw' - if exists(':AcpLock') - AcpLock - elseif exists(':AutoComplPopLock') - AutoComplPopLock - endif -endfunction - -" -function s:deactivateFufBuffer() - if exists(':AcpUnlock') - AcpUnlock - elseif exists(':AutoComplPopUnlock') - AutoComplPopUnlock - endif - call l9#tempbuffer#close(s:FUF_BUF_NAME) -endfunction - -" }}}1 -"============================================================================= -" s:handlerBase {{{1 - -let s:handlerBase = {} - -"----------------------------------------------------------------------------- -" PURE VIRTUAL FUNCTIONS {{{2 -" -" " -" s:handler.getModeName() -" -" " -" s:handler.getPrompt() -" -" " -" s:handler.getCompleteItems(patternSet) -" -" " -" s:handler.onOpen(word, mode) -" -" " Before entering FuzzyFinder buffer. This function should return in a short time. -" s:handler.onModeEnterPre() -" -" " After entering FuzzyFinder buffer. -" s:handler.onModeEnterPost() -" -" " After leaving FuzzyFinder buffer. -" s:handler.onModeLeavePost(opened) -" -" }}}2 -"----------------------------------------------------------------------------- - -" -function s:handlerBase.concretize(deriv) - call extend(self, a:deriv, 'error') - return self -endfunction - -" -function s:handlerBase.addStat(pattern, word) - let stat = { 'pattern' : a:pattern, 'word' : a:word } - call filter(self.stats, 'v:val !=# stat') - call insert(self.stats, stat) - let self.stats = self.stats[0 : g:fuf_learningLimit - 1] -endfunction - -" -function s:handlerBase.getMatchingCompleteItems(patternBase) - let MakeMatchingExpr = function(self.partialMatching - \ ? 's:makePartialMatchingExpr' - \ : 's:makeFuzzyMatchingExpr') - let patternSet = self.makePatternSet(a:patternBase) - let exprBoundary = s:makeFuzzyMatchingExpr('a:wordForBoundary', patternSet.primaryForRank) - let stats = filter( - \ copy(self.stats), 'v:val.pattern ==# patternSet.primaryForRank') - let items = self.getCompleteItems(patternSet.primary) - " NOTE: In order to know an excess, plus 1 to limit number - let items = l9#filterWithLimit( - \ items, patternSet.filteringExpr, g:fuf_enumeratingLimit + 1) - return map(items, - \ 's:setRanks(v:val, patternSet.primaryForRank, exprBoundary, stats)') -endfunction - -" -function s:handlerBase.onComplete(findstart, base) - if a:findstart - return 0 - elseif !self.existsPrompt(a:base) - return [] - endif - call s:highlightPrompt(self.getPrompt()) - let items = [] - for patternBase in s:expandAbbrevMap(self.removePrompt(a:base), g:fuf_abbrevMap) - let items += self.getMatchingCompleteItems(patternBase) - if len(items) > g:fuf_enumeratingLimit - let items = items[ : g:fuf_enumeratingLimit - 1] - call s:highlightError() - break - endif - endfor - if empty(items) - call s:highlightError() - else - call sort(items, 'fuf#compareRanks') - if g:fuf_autoPreview - call feedkeys("\\\=fuf#getRunningHandler().onPreviewBase(0) ? '' : ''\", 'n') - else - call feedkeys("\\", 'n') - endif - let self.lastFirstWord = items[0].word - endif - return items -endfunction - -" -function s:handlerBase.existsPrompt(line) - return strlen(a:line) >= strlen(self.getPrompt()) && - \ a:line[:strlen(self.getPrompt()) -1] ==# self.getPrompt() -endfunction - -" -function s:handlerBase.removePrompt(line) - return a:line[(self.existsPrompt(a:line) ? strlen(self.getPrompt()) : 0):] -endfunction - -" -function s:handlerBase.restorePrompt(line) - let i = 0 - while i < len(self.getPrompt()) && i < len(a:line) && self.getPrompt()[i] ==# a:line[i] - let i += 1 - endwhile - return self.getPrompt() . a:line[i : ] -endfunction - -" -function s:handlerBase.onCursorMovedI() - if !self.existsPrompt(getline('.')) - call setline('.', self.restorePrompt(getline('.'))) - call feedkeys("\", 'n') - elseif col('.') <= len(self.getPrompt()) - " if the cursor is moved before command prompt - call feedkeys(repeat("\", len(self.getPrompt()) - col('.') + 1), 'n') - elseif col('.') > strlen(getline('.')) && col('.') != self.lastCol - " if the cursor is placed on the end of the line and has been actually moved. - let self.lastCol = col('.') - let self.lastPattern = self.removePrompt(getline('.')) - call feedkeys("\\", 'n') - endif -endfunction - -" -function s:handlerBase.onInsertLeave() - unlet s:runningHandler - let tempVars = l9#tempvariables#getList(s:TEMP_VARIABLES_GROUP) - call l9#tempvariables#end(s:TEMP_VARIABLES_GROUP) - call s:deactivateFufBuffer() - call fuf#saveDataFile(self.getModeName(), 'stats', self.stats) - execute self.windowRestoringCommand - let fOpen = exists('s:reservedCommand') - if fOpen - call self.onOpen(s:reservedCommand[0], s:reservedCommand[1]) - unlet s:reservedCommand - endif - call self.onModeLeavePost(fOpen) - if exists('self.reservedMode') - call l9#tempvariables#setList(s:TEMP_VARIABLES_GROUP, tempVars) - call fuf#launch(self.reservedMode, self.lastPattern, self.partialMatching) - endif -endfunction - -" -function s:handlerBase.onCr(openType) - if pumvisible() - call feedkeys(printf("\\=fuf#getRunningHandler().onCr(%d) ? '' : ''\", - \ a:openType), 'n') - return - endif - if !empty(self.lastPattern) - call self.addStat(self.lastPattern, self.removePrompt(getline('.'))) - endif - if !self.isOpenable(getline('.')) - " To clear i_ expression (fuf#getRunningHandler().onCr...) - echo '' - return - endif - let s:reservedCommand = [self.removePrompt(getline('.')), a:openType] - call feedkeys("\", 'n') " stopinsert behavior is strange... -endfunction - -" -function s:handlerBase.onBs() - call feedkeys((pumvisible() ? "\\" : "\"), 'n') -endfunction - -" -function s:getLastBlockLength(pattern, patternIsPath) - let separatorPos = strridx(a:pattern, g:fuf_patternSeparator) - if separatorPos >= 0 - return len(a:pattern) - separatorPos - endif - if a:patternIsPath && a:pattern =~# '[/\\].' - return len(matchstr(a:pattern, '[^/\\]*.$')) - endif - return len(a:pattern) -endfunction - -" -function s:handlerBase.onDeleteWord() - let pattern = self.removePrompt(getline('.')[ : col('.') - 2]) - let numBs = s:getLastBlockLength(pattern, 1) - call feedkeys((pumvisible() ? "\" : "") . repeat("\", numBs), 'n') -endfunction - -" -function s:handlerBase.onPreviewBase(repeatable) - if self.getPreviewHeight() <= 0 - return - elseif !pumvisible() - return - elseif !self.existsPrompt(getline('.')) - let word = self.removePrompt(getline('.')) - elseif !exists('self.lastFirstWord') - return - else - let word = self.lastFirstWord - endif - redraw - if a:repeatable && exists('self.lastPreviewInfo') && self.lastPreviewInfo.word ==# word - let self.lastPreviewInfo.count += 1 - else - let self.lastPreviewInfo = {'word': word, 'count': 0} - endif - let lines = self.makePreviewLines(word, self.lastPreviewInfo.count) - let lines = lines[: self.getPreviewHeight() - 1] - call map(lines, 'substitute(v:val, "\t", repeat(" ", &tabstop), "g")') - call map(lines, 'strtrans(v:val)') - call map(lines, 'l9#snipTail(v:val, &columns - 1, s:ABBR_SNIP_MASK)') - echo join(lines, "\n") -endfunction - -" -function s:handlerBase.onSwitchMode(shift) - let modes = copy(fuf#getModeNames()) - call map(modes, '{ "ranks": [ fuf#{v:val}#getSwitchOrder(), v:val ] }') - call filter(modes, 'v:val.ranks[0] >= 0') - call sort(modes, 'fuf#compareRanks') - let self.reservedMode = self.getModeName() - for i in range(len(modes)) - if modes[i].ranks[1] ==# self.getModeName() - let self.reservedMode = modes[(i + a:shift) % len(modes)].ranks[1] - break - endif - endfor - call feedkeys("\", 'n') " stopinsert doesn't work. -endfunction - -" -function s:handlerBase.onSwitchMatching() - let self.partialMatching = !self.partialMatching - let self.lastCol = -1 - call setline('.', self.restorePrompt(self.lastPattern)) - call feedkeys("\", 'n') - "call self.onCursorMovedI() -endfunction - -" -function s:handlerBase.onRecallPattern(shift) - let patterns = map(copy(self.stats), 'v:val.pattern') - if !exists('self.indexRecall') - let self.indexRecall = -1 - endif - let self.indexRecall += a:shift - if self.indexRecall < 0 - let self.indexRecall = -1 - elseif self.indexRecall >= len(patterns) - let self.indexRecall = len(patterns) - 1 - else - call setline('.', self.getPrompt() . patterns[self.indexRecall]) - call feedkeys("\", 'n') - endif -endfunction - -" }}}1 -"============================================================================= -" INITIALIZATION {{{1 - -augroup FufGlobal - autocmd! - autocmd BufLeave * let s:bufferCursorPosMap[bufnr('')] = getpos('.') -augroup END - -let s:bufferCursorPosMap = {} - -" -let s:DATA_FILE_VERSION = 400 - -" -function s:checkDataFileCompatibility() - if empty(g:fuf_dataDir) - let s:dataFileAvailable = 0 - return - endif - let versionPath = l9#concatPaths([g:fuf_dataDir, 'VERSION']) - let lines = l9#readFile(versionPath) - if empty(lines) - call l9#writeFile([s:DATA_FILE_VERSION], versionPath) - let s:dataFileAvailable = 1 - elseif str2nr(lines[0]) == s:DATA_FILE_VERSION - let s:dataFileAvailable = 1 - else - call fuf#echoWarning(printf( - \ "=======================================================\n" . - \ " Existing data files for FuzzyFinder is no longer \n" . - \ " compatible with this version of FuzzyFinder. Remove \n" . - \ " %-53s\n" . - \ "=======================================================\n" , - \ string(g:fuf_dataDir))) - call l9#inputHl('Question', 'Press Enter') - let s:dataFileAvailable = 0 - endif -endfunction - -call s:checkDataFileCompatibility() - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/fuf/bookmarkdir.vim b/.vim/autoload/fuf/bookmarkdir.vim deleted file mode 100644 index 01585ff..0000000 --- a/.vim/autoload/fuf/bookmarkdir.vim +++ /dev/null @@ -1,163 +0,0 @@ -"============================================================================= -" Copyright (c) 2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#bookmarkdir#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#bookmarkdir#getSwitchOrder() - return g:fuf_bookmarkdir_switchOrder -endfunction - -" -function fuf#bookmarkdir#getEditableDataNames() - return ['items'] -endfunction - -" -function fuf#bookmarkdir#renewCache() -endfunction - -" -function fuf#bookmarkdir#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#bookmarkdir#onInit() - call fuf#defineLaunchCommand('FufBookmarkDir', s:MODE_NAME, '""', []) - command! -bang -narg=? FufBookmarkDirAdd call s:bookmark() -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -" -function s:bookmark(word) - let item = { - \ 'time' : localtime(), - \ } - - let item.path = l9#inputHl('Question', '[fuf] Directory to bookmark:', - \ fnamemodify(getcwd(), ':p:~'), 'dir') - if item.path !~ '\S' - call fuf#echoWarning('Canceled') - return - endif - let item.word = l9#inputHl('Question', '[fuf] Bookmark as:', - \ fnamemodify(getcwd(), ':p:~')) - if item.word !~ '\S' - call fuf#echoWarning('Canceled') - return - endif - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - call insert(items, item) - call fuf#saveDataFile(s:MODE_NAME, 'items', items) -endfunction - -" -function s:findItem(items, word) - for item in a:items - if item.word ==# a:word - return item - endif - endfor - return {} -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_bookmarkdir_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:mode ==# s:OPEN_TYPE_DELETE - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - call filter(items, 'v:val.word !=# a:word') - call fuf#saveDataFile(s:MODE_NAME, 'items', items) - let self.reservedMode = self.getModeName() - return - else - let item = s:findItem(fuf#loadDataFile(s:MODE_NAME, 'items'), a:word) - if !empty(item) - execute ':cd ' . fnameescape(item.path) - endif - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - call fuf#defineKeyMappingInHandler(g:fuf_bookmarkdir_keyDelete, - \ 'onCr(' . s:OPEN_TYPE_DELETE . ')') - let self.items = fuf#loadDataFile(s:MODE_NAME, 'items') - call map(self.items, 'fuf#makeNonPathItem(v:val.word, strftime(g:fuf_timeFormat, v:val.time))') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/bookmarkfile.vim b/.vim/autoload/fuf/bookmarkfile.vim deleted file mode 100644 index 12ac80f..0000000 --- a/.vim/autoload/fuf/bookmarkfile.vim +++ /dev/null @@ -1,199 +0,0 @@ -"============================================================================= -" Copyright (c) 2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#bookmarkfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#bookmarkfile#getSwitchOrder() - return g:fuf_bookmarkfile_switchOrder -endfunction - -" -function fuf#bookmarkfile#getEditableDataNames() - return ['items'] -endfunction - -" -function fuf#bookmarkfile#renewCache() -endfunction - -" -function fuf#bookmarkfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#bookmarkfile#onInit() - call fuf#defineLaunchCommand('FufBookmarkFile', s:MODE_NAME, '""', []) - command! -bang -narg=? FufBookmarkFileAdd call s:bookmarkHere() - command! -bang -narg=0 -range FufBookmarkFileAddAsSelectedText call s:bookmarkHere(l9#getSelectedText()) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -" opens a:path and jumps to the line matching to a:pattern from a:lnum within -" a:range. if not found, jumps to a:lnum. -function s:jumpToBookmark(path, mode, pattern, lnum) - call fuf#openFile(a:path, a:mode, g:fuf_reuseWindow) - call cursor(s:getMatchingLineNumber(getline(1, '$'), a:pattern, a:lnum), 0) - normal! zvzz -endfunction - -" -function s:getMatchingLineNumber(lines, pattern, lnumBegin) - let l = min([a:lnumBegin, len(a:lines)]) - for [l0, l1] in map(range(0, g:fuf_bookmarkfile_searchRange), - \ '[l + v:val, l - v:val]') - if l0 <= len(a:lines) && a:lines[l0 - 1] =~# a:pattern - return l0 - elseif l1 >= 0 && a:lines[l1 - 1] =~# a:pattern - return l1 - endif - endfor - return l -endfunction - -" -function s:getLinePattern(lnum) - return '\C\V\^' . escape(getline(a:lnum), '\') . '\$' -endfunction - -" -function s:bookmarkHere(word) - if !empty(&buftype) || expand('%') !~ '\S' - call fuf#echoWarning('Can''t bookmark this buffer.') - return - endif - let item = { - \ 'word' : (a:word =~# '\S' ? substitute(a:word, '\n', ' ', 'g') - \ : pathshorten(expand('%:p:~')) . '|' . line('.') . '| ' . getline('.')), - \ 'path' : expand('%:p'), - \ 'lnum' : line('.'), - \ 'pattern' : s:getLinePattern(line('.')), - \ 'time' : localtime(), - \ } - let item.word = l9#inputHl('Question', '[fuf] Bookmark as:', item.word) - if item.word !~ '\S' - call fuf#echoWarning('Canceled') - return - endif - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - call insert(items, item) - call fuf#saveDataFile(s:MODE_NAME, 'items', items) -endfunction - -" -function s:findItem(items, word) - for item in a:items - if item.word ==# a:word - return item - endif - endfor - return {} -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_bookmarkfile_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let item = s:findItem(fuf#loadDataFile(s:MODE_NAME, 'items'), a:word) - let lines = fuf#getFileLines(item.path) - if empty(lines) - return [] - endif - let index = s:getMatchingLineNumber(lines, item.pattern, item.lnum) - 1 - return fuf#makePreviewLinesAround( - \ lines, [index], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:mode ==# s:OPEN_TYPE_DELETE - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - call filter(items, 'v:val.word !=# a:word') - call fuf#saveDataFile(s:MODE_NAME, 'items', items) - let self.reservedMode = self.getModeName() - return - else - let item = s:findItem(fuf#loadDataFile(s:MODE_NAME, 'items'), a:word) - if !empty(item) - call s:jumpToBookmark(item.path, a:mode, item.pattern, item.lnum) - endif - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - call fuf#defineKeyMappingInHandler(g:fuf_bookmarkfile_keyDelete, - \ 'onCr(' . s:OPEN_TYPE_DELETE . ')') - let self.items = fuf#loadDataFile(s:MODE_NAME, 'items') - call map(self.items, 'fuf#makeNonPathItem(v:val.word, strftime(g:fuf_timeFormat, v:val.time))') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/buffer.vim b/.vim/autoload/fuf/buffer.vim deleted file mode 100644 index 08b954a..0000000 --- a/.vim/autoload/fuf/buffer.vim +++ /dev/null @@ -1,189 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#buffer#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#buffer#getSwitchOrder() - return g:fuf_buffer_switchOrder -endfunction - -" -function fuf#buffer#getEditableDataNames() - return [] -endfunction - -" -function fuf#buffer#renewCache() -endfunction - -" -function fuf#buffer#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#buffer#onInit() - call fuf#defineLaunchCommand('FufBuffer', s:MODE_NAME, '""', []) - augroup fuf#buffer - autocmd! - autocmd BufEnter * call s:updateBufTimes() - autocmd BufWritePost * call s:updateBufTimes() - augroup END -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -let s:bufTimes = {} - -" -function s:updateBufTimes() - let s:bufTimes[bufnr('%')] = localtime() -endfunction - -" -function s:makeItem(nr) - let fname = (empty(bufname(a:nr)) - \ ? '[No Name]' - \ : fnamemodify(bufname(a:nr), ':p:~:.')) - let time = (exists('s:bufTimes[a:nr]') ? s:bufTimes[a:nr] : 0) - let item = fuf#makePathItem(fname, strftime(g:fuf_timeFormat, time), 0) - let item.index = a:nr - let item.bufNr = a:nr - let item.time = time - let item.abbrPrefix = s:getBufIndicator(a:nr) . ' ' - return item -endfunction - -" -function s:getBufIndicator(bufNr) - if !getbufvar(a:bufNr, '&modifiable') - return '[-]' - elseif getbufvar(a:bufNr, '&modified') - return '[+]' - elseif getbufvar(a:bufNr, '&readonly') - return '[R]' - else - return ' ' - endif -endfunction - -" -function s:compareTimeDescending(i1, i2) - return a:i1.time == a:i2.time ? 0 : a:i1.time > a:i2.time ? -1 : +1 -endfunction - -" -function s:findItem(items, word) - for item in a:items - if item.word ==# a:word - return item - endif - endfor - return {} -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_buffer_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let item = s:findItem(self.items, a:word) - if empty(item) - return [] - endif - return fuf#makePreviewLinesForFile(item.bufNr, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - " not use bufnr(a:word) in order to handle unnamed buffer - let item = s:findItem(self.items, a:word) - if empty(item) - " do nothing - elseif a:mode ==# s:OPEN_TYPE_DELETE - execute item.bufNr . 'bdelete' - let self.reservedMode = self.getModeName() - else - call fuf#openBuffer(item.bufNr, a:mode, g:fuf_reuseWindow) - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - call fuf#defineKeyMappingInHandler(g:fuf_buffer_keyDelete, - \ 'onCr(' . s:OPEN_TYPE_DELETE . ')') - let self.items = range(1, bufnr('$')) - call filter(self.items, 'buflisted(v:val) && v:val != self.bufNrPrev && v:val != bufnr("%")') - call map(self.items, 's:makeItem(v:val)') - if g:fuf_buffer_mruOrder - call sort(self.items, 's:compareTimeDescending') - call fuf#mapToSetSerialIndex(self.items, 1) - endif - let self.items = fuf#mapToSetAbbrWithSnippedWordAsPath(self.items) -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/buffertag.vim b/.vim/autoload/fuf/buffertag.vim deleted file mode 100644 index 392b996..0000000 --- a/.vim/autoload/fuf/buffertag.vim +++ /dev/null @@ -1,300 +0,0 @@ -"============================================================================= -" Copyright (c) 2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#buffertag#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#buffertag#getSwitchOrder() - return g:fuf_buffertag_switchOrder -endfunction - -" -function fuf#buffertag#getEditableDataNames() - return [] -endfunction - -" -function fuf#buffertag#renewCache() - let s:tagItemsCache = {} - let s:tagDataCache = {} -endfunction - -" -function fuf#buffertag#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#buffertag#onInit() - call fuf#defineLaunchCommand('FufBufferTag', s:MODE_NAME, '""', - \ [['g:fuf_buffertag_forAll', 0]]) - call fuf#defineLaunchCommand('FufBufferTagAll', s:MODE_NAME, '""', - \ [['g:fuf_buffertag_forAll', 1]]) - call fuf#defineLaunchCommand('FufBufferTagWithCursorWord', s:MODE_NAME, - \ 'expand('''')', [['g:fuf_buffertag_forAll', 0]]) - call fuf#defineLaunchCommand('FufBufferTagAllWithCursorWord', s:MODE_NAME, - \ 'expand('''')', [['g:fuf_buffertag_forAll', 1]]) - call fuf#defineLaunchCommand('FufBufferTagWithSelectedText', s:MODE_NAME, - \ 'l9#getSelectedText()', [['g:fuf_buffertag_forAll', 0]]) - call fuf#defineLaunchCommand('FufBufferTagAllWithSelectedText', s:MODE_NAME, - \ 'l9#getSelectedText()', [['g:fuf_buffertag_forAll', 1]]) - call l9#defineVariableDefault('g:fuf_buffertag_forAll', 0) " private option - " the following settings originate from taglist.vim - call l9#defineVariableDefault('g:fuf_buffertag__asm' , '--language-force=asm --asm-types=dlmt') - call l9#defineVariableDefault('g:fuf_buffertag__aspperl' , '--language-force=asp --asp-types=fsv') - call l9#defineVariableDefault('g:fuf_buffertag__aspvbs' , '--language-force=asp --asp-types=fsv') - call l9#defineVariableDefault('g:fuf_buffertag__awk' , '--language-force=awk --awk-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__beta' , '--language-force=beta --beta-types=fsv') - call l9#defineVariableDefault('g:fuf_buffertag__c' , '--language-force=c --c-types=dgsutvf') - call l9#defineVariableDefault('g:fuf_buffertag__cpp' , '--language-force=c++ --c++-types=nvdtcgsuf') - call l9#defineVariableDefault('g:fuf_buffertag__cs' , '--language-force=c# --c#-types=dtncEgsipm') - call l9#defineVariableDefault('g:fuf_buffertag__cobol' , '--language-force=cobol --cobol-types=dfgpPs') - call l9#defineVariableDefault('g:fuf_buffertag__eiffel' , '--language-force=eiffel --eiffel-types=cf') - call l9#defineVariableDefault('g:fuf_buffertag__erlang' , '--language-force=erlang --erlang-types=drmf') - call l9#defineVariableDefault('g:fuf_buffertag__expect' , '--language-force=tcl --tcl-types=cfp') - call l9#defineVariableDefault('g:fuf_buffertag__fortran' , '--language-force=fortran --fortran-types=pbceiklmntvfs') - call l9#defineVariableDefault('g:fuf_buffertag__html' , '--language-force=html --html-types=af') - call l9#defineVariableDefault('g:fuf_buffertag__java' , '--language-force=java --java-types=pcifm') - call l9#defineVariableDefault('g:fuf_buffertag__javascript', '--language-force=javascript --javascript-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__lisp' , '--language-force=lisp --lisp-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__lua' , '--language-force=lua --lua-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__make' , '--language-force=make --make-types=m') - call l9#defineVariableDefault('g:fuf_buffertag__pascal' , '--language-force=pascal --pascal-types=fp') - call l9#defineVariableDefault('g:fuf_buffertag__perl' , '--language-force=perl --perl-types=clps') - call l9#defineVariableDefault('g:fuf_buffertag__php' , '--language-force=php --php-types=cdvf') - call l9#defineVariableDefault('g:fuf_buffertag__python' , '--language-force=python --python-types=cmf') - call l9#defineVariableDefault('g:fuf_buffertag__rexx' , '--language-force=rexx --rexx-types=s') - call l9#defineVariableDefault('g:fuf_buffertag__ruby' , '--language-force=ruby --ruby-types=cfFm') - call l9#defineVariableDefault('g:fuf_buffertag__scheme' , '--language-force=scheme --scheme-types=sf') - call l9#defineVariableDefault('g:fuf_buffertag__sh' , '--language-force=sh --sh-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__csh' , '--language-force=sh --sh-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__zsh' , '--language-force=sh --sh-types=f') - call l9#defineVariableDefault('g:fuf_buffertag__slang' , '--language-force=slang --slang-types=nf') - call l9#defineVariableDefault('g:fuf_buffertag__sml' , '--language-force=sml --sml-types=ecsrtvf') - call l9#defineVariableDefault('g:fuf_buffertag__sql' , '--language-force=sql --sql-types=cFPrstTvfp') - call l9#defineVariableDefault('g:fuf_buffertag__tcl' , '--language-force=tcl --tcl-types=cfmp') - call l9#defineVariableDefault('g:fuf_buffertag__vera' , '--language-force=vera --vera-types=cdefgmpPtTvx') - call l9#defineVariableDefault('g:fuf_buffertag__verilog' , '--language-force=verilog --verilog-types=mcPertwpvf') - call l9#defineVariableDefault('g:fuf_buffertag__vim' , '--language-force=vim --vim-types=avf') - call l9#defineVariableDefault('g:fuf_buffertag__yacc' , '--language-force=yacc --yacc-types=l') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:parseTagLine(line) - " tag W:\Win32\SRC7\NCSIM\NCVW32\CUBEFACE.H /^#define CUBEFACE_H$/;" macro line:4 - let fields = matchlist(a:line, '\v^([^\t]+)\t(.+)\t\/\^(.+)\$\/\;\"\t(.+)\tline\:(\d+)') - if empty(fields) - return {} - endif - return { - \ 'tag' : fields[1], - \ 'fname' : fields[2], - \ 'pattern': fields[3], - \ 'kind' : fields[4], - \ 'lnum' : str2nr(fields[5]), - \ } -endfunction - -" -let s:TEMP_VARIABLES_GROUP = expand(':p') - -" -function s:getFileType(bufNr) - let ft = getbufvar(a:bufNr, '&filetype') - if !empty(ft) || bufloaded(a:bufNr) - return ft - endif - let ft = getbufvar(a:bufNr, 'fuf_buffertag_filetype') - if !empty(ft) - return ft - endif - call l9#tempvariables#set(s:TEMP_VARIABLES_GROUP, '&eventignore', 'FileType') - call l9#tempvariables#set(s:TEMP_VARIABLES_GROUP, '&filetype', &filetype) - " from taglist.vim - execute 'doautocmd filetypedetect BufRead ' . bufname(a:bufNr) - let ft = &filetype - call l9#tempvariables#end(s:TEMP_VARIABLES_GROUP) - call setbufvar(a:bufNr, 'fuf_buffertag_filetype', ft) - return ft -endfunction - -" -function s:makeCtagsCmd(bufNr) - let ft = s:getFileType(a:bufNr) - if !exists('g:fuf_buffertag__{ft}') - return '' - endif - " - let cmd = join([g:fuf_buffertag_ctagsPath, - \ '-f - --sort=no --excmd=pattern --fields=nKs', - \ g:fuf_buffertag__{ft}, - \ shellescape(fnamemodify(bufname(a:bufNr), ':p'))]) - return cmd -endfunction - -" -function s:getTagItems(bufNr) - let cmd = s:makeCtagsCmd(a:bufNr) - if empty(cmd) - return [] - elseif !exists('s:tagItemsCache[cmd]') || - \ s:tagItemsCache[cmd].time < getftime(expand(bufname(a:bufNr))) - let items = split(system(cmd), "\n") - if v:shell_error - call fuf#echoError([cmd] + items) - throw "Command error" - endif - call map(items, 's:parseTagLine(v:val)') - call filter(items, '!empty(v:val)') - let s:tagItemsCache[cmd] = { - \ 'time' : localtime(), - \ 'items' : items, - \ } - endif - return s:tagItemsCache[cmd].items -endfunction - -" -function s:makeItem(tag, itemMap) - let menu = fnamemodify(a:itemMap[a:tag][0].fname, ':t') - \ . ' [' . a:itemMap[a:tag][0].kind . ']' - if len(a:itemMap[a:tag]) > 1 - let menu .= ' (' . len(a:itemMap[a:tag]) . ')' - endif - let item = fuf#makeNonPathItem(a:tag, menu) - return item -endfunction - -" -function s:getTagData(bufNrs) - let key = join([0] + sort(copy(a:bufNrs)), "\n") - let bufNames = map(copy(a:bufNrs), 'bufname(v:val)') - if !exists('s:tagDataCache[key]') || - \ fuf#countModifiedFiles(bufNames, s:tagDataCache[key].time) > 0 - let itemMap = {} - for item in l9#concat(map(copy(a:bufNrs), 's:getTagItems(v:val)')) - if !exists('itemMap[item.tag]') - let itemMap[item.tag] = [] - endif - call add(itemMap[item.tag], item) - endfor - let items = sort(keys(itemMap)) - call map(items, 's:makeItem(v:val, itemMap)') - call fuf#mapToSetSerialIndex(items, 1) - call map(items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - let s:tagDataCache[key] = { - \ 'time' : localtime(), - \ 'itemMap': itemMap, - \ 'items' : items, - \ } - endif - return [s:tagDataCache[key].items, s:tagDataCache[key].itemMap] -endfunction - -" -function s:jumpToTag(item, mode) - call fuf#openFile(a:item.fname, a:mode, g:fuf_reuseWindow) - call cursor(a:item.lnum, 1) - normal! zvzz -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_buffertag_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - if !exists('self.itemMap[a:word][0]') - call fuf#echoError('Definition not found:' . a:word) - return - elseif len(self.itemMap[a:word]) == 1 - let i = 0 - else - let list = map(fuf#mapToSetSerialIndex(copy(self.itemMap[a:word]), 1), - \ 'printf(" %2d: %s|%d| [%s] %s",v:val.index, fnamemodify(v:val.fname, ":~:."), v:val.lnum, v:val.kind, v:val.pattern)') - let i = inputlist(['Select a definition of "' . a:word . '":'] + list) - 1 - endif - if 0 <= i && i < len(self.itemMap[a:word]) - call s:jumpToTag(self.itemMap[a:word][i], a:mode) - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - if g:fuf_buffertag_forAll - let bufNrs = filter(range(1, bufnr('$')), 'buflisted(v:val)') - else - let bufNrs = [self.bufNrPrev] - endif - let [self.items, self.itemMap] = s:getTagData(bufNrs) -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/callbackfile.vim b/.vim/autoload/fuf/callbackfile.vim deleted file mode 100644 index fedf0cf..0000000 --- a/.vim/autoload/fuf/callbackfile.vim +++ /dev/null @@ -1,137 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#callbackfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#callbackfile#getSwitchOrder() - return -1 -endfunction - -" -function fuf#callbackfile#getEditableDataNames() - return [] -endfunction - -" -function fuf#callbackfile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#callbackfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#callbackfile#onInit() -endfunction - -" -function fuf#callbackfile#launch(initialPattern, partialMatching, prompt, exclude, listener) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:exclude = a:exclude - let s:listener = a:listener - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = getcwd() . g:fuf_ignoreCase . s:exclude . "\n" . a:dir - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, s:exclude) - if isdirectory(a:dir) - call insert(s:cache[key], fuf#makePathItem(a:dir . '.', '', 0)) - endif - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return a:enteredPattern =~# '[^/\\]$' -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - let items = copy(s:enumItems(fuf#splitPath(a:patternPrimary).head)) - return filter(items, 'bufnr("^" . v:val.word . "$") != self.bufNrPrev') -endfunction - -" -function s:handler.onOpen(word, mode) - call s:listener.onComplete(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) - if !a:opened && exists('s:listener.onAbort()') - call s:listener.onAbort() - endif -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/callbackitem.vim b/.vim/autoload/fuf/callbackitem.vim deleted file mode 100644 index 118ee08..0000000 --- a/.vim/autoload/fuf/callbackitem.vim +++ /dev/null @@ -1,139 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#callbackitem#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#callbackitem#getSwitchOrder() - return -1 -endfunction - -" -function fuf#callbackitem#getEditableDataNames() - return [] -endfunction - -" -function fuf#callbackitem#renewCache() -endfunction - -" -function fuf#callbackitem#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#callbackitem#onInit() -endfunction - -" -function fuf#callbackitem#launch(initialPattern, partialMatching, prompt, listener, items, forPath) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:listener = a:listener - let s:forPath = a:forPath - let s:items = copy(a:items) - if s:forPath - call map(s:items, 'fuf#makePathItem(v:val, "", 1)') - call fuf#mapToSetSerialIndex(s:items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:items) - else - call map(s:items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - endif - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - if s:forPath - return g:fuf_previewHeight - endif - return 0 -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - let parser = (s:forPath - \ ? 's:interpretPrimaryPatternForPath' - \ : 's:interpretPrimaryPatternForNonPath') - return fuf#makePatternSet(a:patternBase, parser, self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - if s:forPath - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) - endif - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - call s:listener.onComplete(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) - if !a:opened && exists('s:listener.onAbort()') - call s:listener.onAbort() - endif -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/changelist.vim b/.vim/autoload/fuf/changelist.vim deleted file mode 100644 index 545f6ca..0000000 --- a/.vim/autoload/fuf/changelist.vim +++ /dev/null @@ -1,172 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#changelist#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#changelist#getSwitchOrder() - return g:fuf_changelist_switchOrder -endfunction - -" -function fuf#changelist#getEditableDataNames() - return [] -endfunction - -" -function fuf#changelist#renewCache() -endfunction - -" -function fuf#changelist#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#changelist#onInit() - call fuf#defineLaunchCommand('FufChangeList', s:MODE_NAME, '""', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getChangesLines() - redir => result - :silent changes - redir END - return split(result, "\n") -endfunction - -" -function s:parseChangesLine(line) - " return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') - let elements = matchlist(a:line, '\v^(.)\s*(\d+)\s+(\d+)\s+(\d+)\s*(.*)$') - if empty(elements) - return {} - endif - return { - \ 'prefix': elements[1], - \ 'count' : elements[2], - \ 'lnum' : elements[3], - \ 'text' : printf('|%d:%d|%s', elements[3], elements[4], elements[5]), - \ } -endfunction - -" -function s:makeItem(line) - let parsed = s:parseChangesLine(a:line) - if empty(parsed) - return {} - endif - let item = fuf#makeNonPathItem(parsed.text, '') - let item.abbrPrefix = parsed.prefix - let item.lnum = parsed.lnum - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_changelist_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(self.bufNrPrev) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - let older = 0 - for line in reverse(s:getChangesLines()) - if stridx(line, '>') == 0 - let older = 1 - endif - let parsed = s:parseChangesLine(line) - if !empty(parsed) && parsed.text ==# a:word - if parsed.count != 0 - execute 'normal! ' . parsed.count . (older ? 'g;' : 'g,') . 'zvzz' - endif - break - endif - endfor -endfunction - -" -function s:handler.onModeEnterPre() - let self.items = s:getChangesLines() -endfunction - -" -function s:handler.onModeEnterPost() - call map(self.items, 's:makeItem(v:val)') - call filter(self.items, '!empty(v:val)') - call reverse(self.items) - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/fuf/coveragefile.vim b/.vim/autoload/fuf/coveragefile.vim deleted file mode 100644 index 1471ef8..0000000 --- a/.vim/autoload/fuf/coveragefile.vim +++ /dev/null @@ -1,199 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#coveragefile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#coveragefile#getSwitchOrder() - return g:fuf_coveragefile_switchOrder -endfunction - -" -function fuf#coveragefile#getEditableDataNames() - return ['coverages'] -endfunction - -" -function fuf#coveragefile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#coveragefile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#coveragefile#onInit() - call fuf#defineLaunchCommand('FufCoverageFile', s:MODE_NAME, '""', []) - call l9#defineVariableDefault('g:fuf_coveragefile_name', '') " private option - command! -bang -narg=0 FufCoverageFileRegister call s:registerCoverage() - command! -bang -narg=? FufCoverageFileChange call s:changeCoverage() -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems() - let key = join([getcwd(), g:fuf_ignoreCase, g:fuf_coveragefile_exclude, - \ g:fuf_coveragefile_globPatterns], "\n") - if !exists('s:cache[key]') - let s:cache[key] = l9#concat(map(copy(g:fuf_coveragefile_globPatterns), - \ 'fuf#glob(v:val)')) - call filter(s:cache[key], 'filereadable(v:val)') " filter out directories - call map(s:cache[key], 'fuf#makePathItem(fnamemodify(v:val, ":~:."), "", 0)') - if len(g:fuf_coveragefile_exclude) - call filter(s:cache[key], 'v:val.word !~ g:fuf_coveragefile_exclude') - endif - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" -function s:registerCoverage() - let patterns = [] - while 1 - let pattern = l9#inputHl('Question', '[fuf] Glob pattern for coverage ( and end):', - \ '', 'file') - if pattern !~ '\S' - break - endif - call add(patterns, pattern) - endwhile - if empty(patterns) - call fuf#echoWarning('Canceled') - return - endif - echo '[fuf] patterns: ' . string(patterns) - let name = l9#inputHl('Question', '[fuf] Coverage name:') - if name !~ '\S' - call fuf#echoWarning('Canceled') - return - endif - let coverages = fuf#loadDataFile(s:MODE_NAME, 'coverages') - call insert(coverages, {'name': name, 'patterns': patterns}) - call fuf#saveDataFile(s:MODE_NAME, 'coverages', coverages) -endfunction - -" -function s:createChangeCoverageListener() - let listener = {} - - function listener.onComplete(name, method) - call s:changeCoverage(a:name) - endfunction - - return listener -endfunction - -" -function s:changeCoverage(name) - let coverages = fuf#loadDataFile(s:MODE_NAME, 'coverages') - if a:name !~ '\S' - let names = map(copy(coverages), 'v:val.name') - call fuf#callbackitem#launch('', 0, '>Coverage>', s:createChangeCoverageListener(), names, 0) - return - else - let name = a:name - endif - call filter(coverages, 'v:val.name ==# name') - if empty(coverages) - call fuf#echoError('Coverage not found: ' . name) - return - endif - call fuf#setOneTimeVariables( - \ ['g:fuf_coveragefile_globPatterns', coverages[0].patterns], - \ ['g:fuf_coveragefile_name' , a:name] - \ ) - FufCoverageFile -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - let nameString = (empty(g:fuf_coveragefile_name) ? '' - \ : '[' . g:fuf_coveragefile_name . ']') - return fuf#formatPrompt(g:fuf_coveragefile_prompt, self.partialMatching, - \ nameString) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - " NOTE: Comparing filenames is faster than bufnr('^' . fname . '$') - let bufNamePrev = fnamemodify(bufname(self.bufNrPrev), ':~:.') - let self.items = copy(s:enumItems()) - call filter(self.items, 'v:val.word !=# bufNamePrev') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/dir.vim b/.vim/autoload/fuf/dir.vim deleted file mode 100644 index 5316093..0000000 --- a/.vim/autoload/fuf/dir.vim +++ /dev/null @@ -1,132 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#dir#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#dir#getSwitchOrder() - return g:fuf_dir_switchOrder -endfunction - -" -function fuf#dir#getEditableDataNames() - return [] -endfunction - -" -function fuf#dir#renewCache() - let s:cache = {} -endfunction - -" -function fuf#dir#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#dir#onInit() - call fuf#defineLaunchCommand('FufDir' , s:MODE_NAME, '""', []) - call fuf#defineLaunchCommand('FufDirWithFullCwd' , s:MODE_NAME, 'fnamemodify(getcwd(), '':p'')', []) - call fuf#defineLaunchCommand('FufDirWithCurrentBufferDir', s:MODE_NAME, 'expand(''%:~:.'')[:-1-len(expand(''%:~:.:t''))]', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = getcwd() . g:fuf_ignoreCase . g:fuf_dir_exclude . "\n" . a:dir - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, g:fuf_dir_exclude) - call filter(s:cache[key], 'v:val.word =~# ''[/\\]$''') - if isdirectory(a:dir) - call insert(s:cache[key], fuf#makePathItem(a:dir . '.', '', 0)) - endif - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_dir_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return a:enteredPattern =~# '[^/\\]$' -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesAround( - \ fuf#glob(fnamemodify(a:word, ':p') . '*'), - \ [], a:count, self.getPreviewHeight()) - return -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumItems(fuf#splitPath(a:patternPrimary).head) -endfunction - -" -function s:handler.onOpen(word, mode) - execute ':cd ' . fnameescape(a:word) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/file.vim b/.vim/autoload/fuf/file.vim deleted file mode 100644 index 1569192..0000000 --- a/.vim/autoload/fuf/file.vim +++ /dev/null @@ -1,139 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#file#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#file#getSwitchOrder() - return g:fuf_file_switchOrder -endfunction - -" -function fuf#file#getEditableDataNames() - return [] -endfunction - -" -function fuf#file#renewCache() - let s:cache = {} -endfunction - -" -function fuf#file#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#file#onInit() - call fuf#defineLaunchCommand('FufFile' , s:MODE_NAME, '""', []) - call fuf#defineLaunchCommand('FufFileWithFullCwd' , s:MODE_NAME, 'fnamemodify(getcwd(), '':p'')', []) - call fuf#defineLaunchCommand('FufFileWithCurrentBufferDir', s:MODE_NAME, 'expand(''%:~:.'')[:-1-len(expand(''%:~:.:t''))]', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = join([getcwd(), g:fuf_ignoreCase, g:fuf_file_exclude, a:dir], "\n") - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, g:fuf_file_exclude) - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" -function s:enumNonCurrentItems(dir, bufNrPrev, cache) - let key = a:dir . 'AVOIDING EMPTY KEY' - if !exists('a:cache[key]') - " NOTE: Comparing filenames is faster than bufnr('^' . fname . '$') - let bufNamePrev = bufname(a:bufNrPrev) - let a:cache[key] = - \ filter(copy(s:enumItems(a:dir)), 'v:val.word !=# bufNamePrev') - endif - return a:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_file_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return a:enteredPattern =~# '[^/\\]$' -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumNonCurrentItems( - \ fuf#splitPath(a:patternPrimary).head, self.bufNrPrev, self.cache) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.cache = {} -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/givencmd.vim b/.vim/autoload/fuf/givencmd.vim deleted file mode 100644 index d59178c..0000000 --- a/.vim/autoload/fuf/givencmd.vim +++ /dev/null @@ -1,123 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givencmd#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givencmd#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givencmd#getEditableDataNames() - return [] -endfunction - -" -function fuf#givencmd#renewCache() -endfunction - -" -function fuf#givencmd#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givencmd#onInit() -endfunction - -" -function fuf#givencmd#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = copy(a:items) - call map(s:items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:word[0] =~# '[:/?]' - call histadd(a:word[0], a:word[1:]) - endif - call feedkeys(a:word . "\", 'n') -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/givendir.vim b/.vim/autoload/fuf/givendir.vim deleted file mode 100644 index e654d85..0000000 --- a/.vim/autoload/fuf/givendir.vim +++ /dev/null @@ -1,123 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givendir#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givendir#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givendir#getEditableDataNames() - return [] -endfunction - -" -function fuf#givendir#renewCache() -endfunction - -" -function fuf#givendir#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givendir#onInit() -endfunction - -" -function fuf#givendir#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = map(copy(a:items), 'substitute(v:val, ''[/\\]\?$'', "", "")') - let s:items = map(s:items, 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(s:items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:items) - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesAround( - \ fuf#glob(fnamemodify(a:word, ':p') . '*'), - \ [], a:count, self.getPreviewHeight()) - return -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - execute ':cd ' . fnameescape(a:word) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/givenfile.vim b/.vim/autoload/fuf/givenfile.vim deleted file mode 100644 index 5419ff8..0000000 --- a/.vim/autoload/fuf/givenfile.vim +++ /dev/null @@ -1,121 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givenfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givenfile#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givenfile#getEditableDataNames() - return [] -endfunction - -" -function fuf#givenfile#renewCache() -endfunction - -" -function fuf#givenfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givenfile#onInit() -endfunction - -" -function fuf#givenfile#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = map(copy(a:items), 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/help.vim b/.vim/autoload/fuf/help.vim deleted file mode 100644 index 8f03e36..0000000 --- a/.vim/autoload/fuf/help.vim +++ /dev/null @@ -1,198 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#help#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#help#getSwitchOrder() - return g:fuf_help_switchOrder -endfunction - -" -function fuf#help#getEditableDataNames() - return [] -endfunction - -" -function fuf#help#renewCache() - let s:cache = {} -endfunction - -" -function fuf#help#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#help#onInit() - call fuf#defineLaunchCommand('FufHelp' , s:MODE_NAME, '""', []) - call fuf#defineLaunchCommand('FufHelpWithCursorWord', s:MODE_NAME, 'expand('''')', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getCurrentHelpTagFiles() - let prefix = 'doc' . l9#getPathSeparator() - let tagFiles = split(globpath(&runtimepath, prefix . 'tags' ), "\n") - \ + split(globpath(&runtimepath, prefix . 'tags-??'), "\n") - return sort(map(tagFiles, 'fnamemodify(v:val, ":p")')) -endfunction - -" -function s:parseHelpTagEntry(line, tagFile) - let elements = split(a:line, "\t") - if len(elements) != 3 || elements[0][0] ==# '!' - return {} - endif - let suffix = matchstr(a:tagFile, '-\zs..$') - if empty(suffix) - let suffix = '@en' - else - let suffix = '@' . suffix - endif - let dir = fnamemodify(a:tagFile, ':h') . l9#getPathSeparator() - return { - \ 'word' : elements[0] . suffix, - \ 'path' : dir . elements[1], - \ 'pattern': elements[2][1:], - \ } -endfunction - -" -function s:getHelpTagEntries(tagFile) - let names = map(l9#readFile(a:tagFile), 's:parseHelpTagEntry(v:val, a:tagFile)') - return filter(names, '!empty(v:val)') -endfunction - -" -function s:parseHelpTagFiles(tagFiles, key) - let cacheName = 'cache-' . l9#hash224(a:key) - let cacheTime = fuf#getDataFileTime(s:MODE_NAME, cacheName) - if cacheTime != -1 && fuf#countModifiedFiles(a:tagFiles, cacheTime) == 0 - return fuf#loadDataFile(s:MODE_NAME, cacheName) - endif - let items = l9#unique(l9#concat(map(copy(a:tagFiles), 's:getHelpTagEntries(v:val)'))) - let items = map(items, 'extend(v:val, fuf#makeNonPathItem(v:val.word, ""))') - call fuf#mapToSetSerialIndex(items, 1) - let items = map(items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#saveDataFile(s:MODE_NAME, cacheName, items) - return items -endfunction - -" -function s:enumHelpTags(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join([g:fuf_ignoreCase] + a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseHelpTagFiles(a:tagFiles, key) - \ } - endif - return s:cache[key].items -endfunction - -" -function s:getMatchingIndex(lines, pattern) - if empty(a:pattern) - return -1 - endif - for i in range(len(a:lines)) - if stridx(a:lines[i], a:pattern) >= 0 - return i - endif - endfor - return -1 -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_help_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(s:enumHelpTags(self.tagFiles)), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].path) - let index = s:getMatchingIndex(lines, items[0].pattern) - return [items[0].path . ':'] + fuf#makePreviewLinesAround( - \ lines, (index < 0 ? [] : [index]), a:count, self.getPreviewHeight() - 1) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumHelpTags(self.tagFiles) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openHelp(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = s:getCurrentHelpTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/jumplist.vim b/.vim/autoload/fuf/jumplist.vim deleted file mode 100644 index ddbb1ab..0000000 --- a/.vim/autoload/fuf/jumplist.vim +++ /dev/null @@ -1,182 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#jumplist#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#jumplist#getSwitchOrder() - return g:fuf_jumplist_switchOrder -endfunction - -" -function fuf#jumplist#getEditableDataNames() - return [] -endfunction - -" -function fuf#jumplist#renewCache() -endfunction - -" -function fuf#jumplist#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#jumplist#onInit() - call fuf#defineLaunchCommand('FufJumpList', s:MODE_NAME, '""', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getJumpsLines() - redir => result - :silent jumps - redir END - return split(result, "\n") -endfunction - -" -function s:parseJumpsLine(line, bufnrPrev) - "return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') - let elements = matchlist(a:line, '\v^(.)\s*(\d+)\s+(\d+)\s+(\d+)\s*(.*)$') - if empty(elements) - return {} - endif - let linePrevBuffer = join(getbufline(a:bufnrPrev, elements[3])) - if stridx(linePrevBuffer, elements[5]) >= 0 - let fname = bufname(a:bufnrPrev) - let text = elements[5] - else - let fname = elements[5] - let text = join(getbufline('^' . elements[5] . '$', elements[3])) - endif - return { - \ 'prefix': elements[1], - \ 'count' : elements[2], - \ 'lnum' : elements[3], - \ 'fname' : fname, - \ 'text' : printf('%s|%d:%d|%s', fname, elements[3], elements[4], text), - \ } -endfunction - -" -function s:makeItem(line, bufnrPrev) - let parsed = s:parseJumpsLine(a:line, a:bufnrPrev) - if empty(parsed) - return {} - endif - let item = fuf#makeNonPathItem(parsed.text, '') - let item.abbrPrefix = parsed.prefix - let item.lnum = parsed.lnum - let item.fname = parsed.fname - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_jumplist_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].fname) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - let older = 0 - for line in reverse(s:getJumpsLines()) - if stridx(line, '>') == 0 - let older = 1 - endif - let parsed = s:parseJumpsLine(line, self.bufNrPrev) - if !empty(parsed) && parsed.text ==# a:word - if parsed.count != 0 - execute 'normal! ' . parsed.count . (older ? "\" : "\") . 'zvzz' - endif - break - endif - endfor -endfunction - -" -function s:handler.onModeEnterPre() - let self.items = s:getJumpsLines() -endfunction - -" -function s:handler.onModeEnterPost() - call map(self.items, 's:makeItem(v:val, self.bufNrPrev)') - call filter(self.items, '!empty(v:val)') - call reverse(self.items) - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/fuf/line.vim b/.vim/autoload/fuf/line.vim deleted file mode 100644 index 60447b5..0000000 --- a/.vim/autoload/fuf/line.vim +++ /dev/null @@ -1,135 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#line#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#line#getSwitchOrder() - return g:fuf_line_switchOrder -endfunction - -" -function fuf#line#getEditableDataNames() - return [] -endfunction - -" -function fuf#line#renewCache() -endfunction - -" -function fuf#line#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#line#onInit() - call fuf#defineLaunchCommand('FufLine', s:MODE_NAME, '""', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_line_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(self.bufNrPrev) - return fuf#makePreviewLinesAround( - \ lines, [items[0].index - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - call filter(self.items, 'v:val.word ==# a:word') - if empty(self.items) - return - execute 'cc ' . self.items[0].index - endif - call cursor(self.items[0].index, 0) - normal! zvzz -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let tab = repeat(' ', getbufvar(self.bufNrPrev, '&tabstop')) - let self.items = getbufline(self.bufNrPrev, 1, '$') - let lnumFormat = '%' . len(string(len(self.items) + 1)) . 'd|' - for i in range(len(self.items)) - let self.items[i] = printf(lnumFormat, i + 1) - \ . substitute(self.items[i], "\t", tab, 'g') - endfor - call map(self.items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 0)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/mrucmd.vim b/.vim/autoload/fuf/mrucmd.vim deleted file mode 100644 index 58632ce..0000000 --- a/.vim/autoload/fuf/mrucmd.vim +++ /dev/null @@ -1,134 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#mrucmd#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#mrucmd#getSwitchOrder() - return g:fuf_mrucmd_switchOrder -endfunction - -" -function fuf#mrucmd#getEditableDataNames() - return ['items'] -endfunction - -" -function fuf#mrucmd#renewCache() -endfunction - -" -function fuf#mrucmd#requiresOnCommandPre() - return 1 -endfunction - -" -function fuf#mrucmd#onInit() - call fuf#defineLaunchCommand('FufMruCmd', s:MODE_NAME, '""', []) -endfunction - -" -function fuf#mrucmd#onCommandPre(cmd) - if getcmdtype() =~# '^[:/?]' - call s:updateInfo(a:cmd) - endif -endfunction - - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:updateInfo(cmd) - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - let items = fuf#updateMruList( - \ items, { 'word' : a:cmd, 'time' : localtime() }, - \ g:fuf_mrucmd_maxItem, g:fuf_mrucmd_exclude) - call fuf#saveDataFile(s:MODE_NAME, 'items', items) -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_mrucmd_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call s:updateInfo(a:word) - call histadd(a:word[0], a:word[1:]) - call feedkeys(a:word . "\", 'n') -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = fuf#loadDataFile(s:MODE_NAME, 'items') - call map(self.items, 'fuf#makeNonPathItem(v:val.word, strftime(g:fuf_timeFormat, v:val.time))') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/mrufile.vim b/.vim/autoload/fuf/mrufile.vim deleted file mode 100644 index f90b9e3..0000000 --- a/.vim/autoload/fuf/mrufile.vim +++ /dev/null @@ -1,234 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#mrufile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#mrufile#getSwitchOrder() - return g:fuf_mrufile_switchOrder -endfunction - -" -function fuf#mrufile#getEditableDataNames() - return ['items', 'itemdirs'] -endfunction - -" -function fuf#mrufile#renewCache() - let s:cache = {} - let s:aroundCache = {} -endfunction - -" -function fuf#mrufile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#mrufile#onInit() - call fuf#defineLaunchCommand('FufMruFile', s:MODE_NAME, '""', []) - call fuf#defineLaunchCommand('FufMruFileInCwd', s:MODE_NAME, - \ '""', [['g:fuf_mrufile_underCwd', 1]]) - call l9#defineVariableDefault('g:fuf_mrufile_underCwd', 0) " private option - call l9#defineVariableDefault('g:fuf_mrufile_searchAroundLevel', -1) " private option - augroup fuf#mrufile - autocmd! - autocmd BufEnter * call s:updateData() - autocmd BufWritePost * call s:updateData() - augroup END -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_EXPAND = -1 - -" -function s:updateData() - if !empty(&buftype) || !filereadable(expand('%')) - return - endif - let items = fuf#loadDataFile(s:MODE_NAME, 'items') - let items = fuf#updateMruList( - \ items, { 'word' : expand('%:p'), 'time' : localtime() }, - \ g:fuf_mrufile_maxItem, g:fuf_mrufile_exclude) - call fuf#saveDataFile(s:MODE_NAME, 'items', items) - call s:removeItemFromCache(expand('%:p')) - let itemDirs = fuf#loadDataFile(s:MODE_NAME, 'itemdirs') - let itemDirs = fuf#updateMruList( - \ itemDirs, { 'word' : expand('%:p:h') }, - \ g:fuf_mrufile_maxItemDir, g:fuf_mrufile_exclude) - call fuf#saveDataFile(s:MODE_NAME, 'itemdirs', itemDirs) -endfunction - -" -function s:removeItemFromCache(word) - for items in values(s:cache) - if exists('items[a:word]') - unlet items[a:word] - endif - endfor -endfunction - -" returns empty value if invalid item -function s:formatItemUsingCache(item) - if a:item.word !~ '\S' - return {} - endif - if !exists('s:cache[a:item.word]') - if filereadable(a:item.word) - let s:cache[a:item.word] = fuf#makePathItem( - \ fnamemodify(a:item.word, ':p:~'), strftime(g:fuf_timeFormat, a:item.time), 0) - else - let s:cache[a:item.word] = {} - endif - endif - return s:cache[a:item.word] -endfunction - -" -function s:expandSearchDir(dir, level) - let dirs = [a:dir] - let dirPrev = a:dir - for i in range(a:level) - let dirPrev = l9#concatPaths([dirPrev, '*']) - call add(dirs, dirPrev) - endfor - let dirPrev = a:dir - for i in range(a:level) - let dirPrevPrev = dirPrev - let dirPrev = fnamemodify(dirPrev, ':h') - if dirPrevPrev ==# dirPrev - break - endif - call add(dirs, dirPrev) - endfor - return dirs -endfunction - -" -function s:listAroundFiles(dir) - if !exists('s:aroundCache[a:dir]') - let s:aroundCache[a:dir] = [a:dir] + - \ fuf#glob(l9#concatPaths([a:dir, '*' ])) + - \ fuf#glob(l9#concatPaths([a:dir, '.*'])) - call filter(s:aroundCache[a:dir], 'filereadable(v:val)') - call map(s:aroundCache[a:dir], 'fuf#makePathItem(fnamemodify(v:val, ":~"), "", 0)') - if len(g:fuf_mrufile_exclude) - call filter(s:aroundCache[a:dir], 'v:val.word !~ g:fuf_mrufile_exclude') - endif - endif - return s:aroundCache[a:dir] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - let cwdString = (g:fuf_mrufile_underCwd ? '[CWD]' : '') - let levelString = (g:fuf_mrufile_searchAroundLevel < 0 ? '' - \ : '[Around:' . g:fuf_mrufile_searchAroundLevel . ']') - return fuf#formatPrompt(g:fuf_mrufile_prompt, self.partialMatching, cwdString . levelString) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:mode ==# s:OPEN_TYPE_EXPAND - let nextLevel = (self.searchAroundLevel < 0 ? 0 : self.searchAroundLevel + 1) - call fuf#setOneTimeVariables(['g:fuf_mrufile_searchAroundLevel', nextLevel]) - let self.reservedMode = self.getModeName() - return - else - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.searchAroundLevel = g:fuf_mrufile_searchAroundLevel - call fuf#defineKeyMappingInHandler(g:fuf_mrufile_keyExpand, - \ 'onCr(' . s:OPEN_TYPE_EXPAND . ')') - if self.searchAroundLevel < 0 - let self.items = fuf#loadDataFile(s:MODE_NAME, 'items') - call map(self.items, 's:formatItemUsingCache(v:val)') - else - let self.items = fuf#loadDataFile(s:MODE_NAME, 'itemdirs') - call map(self.items, 's:expandSearchDir(v:val.word, g:fuf_mrufile_searchAroundLevel)') - let self.items = l9#concat(self.items) - let self.items = l9#unique(self.items) - call map(self.items, 's:listAroundFiles(v:val)') - let self.items = l9#concat(self.items) - endif - " NOTE: Comparing filenames is faster than bufnr('^' . fname . '$') - let bufNamePrev = fnamemodify(bufname(self.bufNrPrev), ':p:~') - call filter(self.items, '!empty(v:val) && v:val.word !=# bufNamePrev') - if g:fuf_mrufile_underCwd - let cwd = fnamemodify(getcwd(), ':p:~') - call filter(self.items, 'stridx(v:val.word, cwd) == 0') - endif - call fuf#mapToSetSerialIndex(self.items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(self.items) -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/quickfix.vim b/.vim/autoload/fuf/quickfix.vim deleted file mode 100644 index dd5d67c..0000000 --- a/.vim/autoload/fuf/quickfix.vim +++ /dev/null @@ -1,154 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#quickfix#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#quickfix#getSwitchOrder() - return g:fuf_quickfix_switchOrder -endfunction - -" -function fuf#quickfix#getEditableDataNames() - return [] -endfunction - -" -function fuf#quickfix#renewCache() -endfunction - -" -function fuf#quickfix#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#quickfix#onInit() - call fuf#defineLaunchCommand('FufQuickfix', s:MODE_NAME, '""', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getJumpsLines() - redir => result - :silent jumps - redir END - return split(result, "\n") -endfunction - -" -function s:parseJumpsLine(line) - return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') -endfunction - -" -function s:makeItem(qfItem) - if !a:qfItem.valid - return {} - endif - let item = fuf#makeNonPathItem( - \ printf('%s|%d:%d|%s', bufname(a:qfItem.bufnr), a:qfItem.lnum, - \ a:qfItem.col, matchstr(a:qfItem.text, '\s*\zs.*\S')) - \ , '') - let item.bufnr = a:qfItem.bufnr - let item.lnum = a:qfItem.lnum - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_quickfix_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].bufnr) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - call filter(self.items, 'v:val.word ==# a:word') - if !empty(self.items) - execute 'cc ' . self.items[0].index - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = getqflist() - call map(self.items, 's:makeItem(v:val)') - call fuf#mapToSetSerialIndex(self.items, 1) - call filter(self.items, 'exists("v:val.word")') - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/fuf/tag.vim b/.vim/autoload/fuf/tag.vim deleted file mode 100644 index 362cabf..0000000 --- a/.vim/autoload/fuf/tag.vim +++ /dev/null @@ -1,178 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#tag#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#tag#getSwitchOrder() - return g:fuf_tag_switchOrder -endfunction - -" -function fuf#tag#getEditableDataNames() - return [] -endfunction - -" -function fuf#tag#renewCache() - let s:cache = {} -endfunction - -" -function fuf#tag#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#tag#onInit() - call fuf#defineLaunchCommand('FufTag' , s:MODE_NAME, '""', []) - call fuf#defineLaunchCommand('FufTagWithCursorWord', s:MODE_NAME, 'expand('''')', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getTagNames(tagFile) - let names = map(l9#readFile(a:tagFile), 'matchstr(v:val, ''^[^!\t][^\t]*'')') - return filter(names, 'v:val =~# ''\S''') -endfunction - -" -function s:parseTagFiles(tagFiles, key) - let cacheName = 'cache-' . l9#hash224(a:key) - let cacheTime = fuf#getDataFileTime(s:MODE_NAME, cacheName) - if cacheTime != -1 && fuf#countModifiedFiles(a:tagFiles, cacheTime) == 0 - return fuf#loadDataFile(s:MODE_NAME, cacheName) - endif - let items = l9#unique(l9#concat(map(copy(a:tagFiles), 's:getTagNames(v:val)'))) - let items = map(items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(items, 1) - let items = map(items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#saveDataFile(s:MODE_NAME, cacheName, items) - return items -endfunction - -" -function s:enumTags(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join([g:fuf_ignoreCase] + a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseTagFiles(a:tagFiles, key) - \ } - endif - return s:cache[key].items -endfunction - -" -function s:getMatchingIndex(lines, cmd) - if a:cmd !~# '\D' - return str2nr(a:cmd) - endif - let pattern = matchstr(a:cmd, '^\/\^\zs.*\ze\$\/$') - if empty(pattern) - return -1 - endif - for i in range(len(a:lines)) - if a:lines[i] ==# pattern - return i - endif - endfor - return -1 -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_tag_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" 'cmd' is '/^hoge hoge$/' or line number -function s:handler.makePreviewLines(word, count) - let tags = taglist('^' . a:word . '$') - if empty(tags) - return [] - endif - let i = a:count % len(tags) - let title = printf('(%d/%d) %s', i + 1, len(tags), tags[i].filename) - let lines = fuf#getFileLines(tags[i].filename) - let index = s:getMatchingIndex(lines, tags[i].cmd) - return [title] + fuf#makePreviewLinesAround( - \ lines, (index < 0 ? [] : [index]), 0, self.getPreviewHeight() - 1) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumTags(self.tagFiles) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openTag(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = fuf#getCurrentTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() - let &l:tags = join(self.tagFiles, ',') -endfunction - -" -function s:handler.onModeLeavePost(opened) - let &l:tags = '' -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/fuf/taggedfile.vim b/.vim/autoload/fuf/taggedfile.vim deleted file mode 100644 index 74652fc..0000000 --- a/.vim/autoload/fuf/taggedfile.vim +++ /dev/null @@ -1,159 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#taggedfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#taggedfile#getSwitchOrder() - return g:fuf_taggedfile_switchOrder -endfunction - -" -function fuf#taggedfile#getEditableDataNames() - return [] -endfunction - -" -function fuf#taggedfile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#taggedfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#taggedfile#onInit() - call fuf#defineLaunchCommand('FufTaggedFile', s:MODE_NAME, '""', []) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getTaggedFileList(tagfile) - execute 'cd ' . fnamemodify(a:tagfile, ':h') - let result = map(l9#readFile(a:tagfile), 'matchstr(v:val, ''^[^!\t][^\t]*\t\zs[^\t]\+'')') - call map(l9#readFile(a:tagfile), 'fnamemodify(v:val, ":p")') - cd - - call map(l9#readFile(a:tagfile), 'fnamemodify(v:val, ":~:.")') - return filter(result, 'v:val =~# ''[^/\\ ]$''') -endfunction - -" -function s:parseTagFiles(tagFiles, key) - let cacheName = 'cache-' . l9#hash224(a:key) - let cacheTime = fuf#getDataFileTime(s:MODE_NAME, cacheName) - if cacheTime != -1 && fuf#countModifiedFiles(a:tagFiles, cacheTime) == 0 - return fuf#loadDataFile(s:MODE_NAME, cacheName) - endif - let items = l9#unique(l9#concat(map(copy(a:tagFiles), 's:getTaggedFileList(v:val)'))) - call map(items, 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(items) - call fuf#saveDataFile(s:MODE_NAME, cacheName, items) - return items -endfunction - -" -function s:enumTaggedFiles(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join([getcwd(), g:fuf_ignoreCase] + a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseTagFiles(a:tagFiles, key) - \ } - endif - return s:cache[key].items -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_taggedfile_prompt, self.partialMatching, '') -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.isOpenable(enteredPattern) - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = fuf#getCurrentTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() - " NOTE: Comparing filenames is faster than bufnr('^' . fname . '$') - let bufNamePrev = fnamemodify(bufname(self.bufNrPrev), ':p:~:.') - " NOTE: Don't do this in onModeEnterPre() - " because that should return in a short time. - let self.items = copy(s:enumTaggedFiles(self.tagFiles)) - call filter(self.items, 'v:val.word !=# bufNamePrev') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/l9.vim b/.vim/autoload/l9.vim deleted file mode 100644 index b6a0ae7..0000000 --- a/.vim/autoload/l9.vim +++ /dev/null @@ -1,570 +0,0 @@ -"============================================================================= -" Copyright (c) 2009-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_l9') - finish -endif -let g:loaded_autoload_l9 = 1 - -" }}}1 -"============================================================================= -" COMPATIBILITY TEST {{{1 - -" -let s:L9_VERSION_CURRENT = 101 -let s:L9_VERSION_PASSABLE = 101 - -" returns true if given version is compatible. -function l9#isCompatible(ver) - return -endfunction - -let s:VERSION_FACTOR = str2float('0.01') - -" returns false if the caller script should finish. -" a:vimVersion: if 0, don't check vim version -" a:l9Version: same rule as v:version -function l9#guardScriptLoading(path, vimVersion, l9Version, exprs) - let loadedVarName = 'g:loaded_' . substitute(a:path, '\W', '_', 'g') - if exists(loadedVarName) - return 0 - elseif a:vimVersion > 0 && a:vimVersion > v:version - echoerr a:path . ' requires Vim version ' . string(a:vimVersion * s:VERSION_FACTOR) - return 0 - elseif a:l9Version > 0 && (a:l9Version > s:L9_VERSION_CURRENT || - \ a:l9Version < s:L9_VERSION_PASSABLE) - echoerr a:path . ' requires L9 library version ' . string(a:l9Version * s:VERSION_FACTOR) - return 0 - endif - for expr in a:exprs - if !eval(expr) - echoerr a:path . ' requires: ' . expr - return 0 - endif - endfor - let {loadedVarName} = 1 - return 1 -endfunction - -" -function l9#getVersion() - return s:L9_VERSION_CURRENT -endfunction - -" }}}1 -"============================================================================= -" LIST {{{1 - -" Removes duplicates (unstable) -" This function doesn't change the list of argument. -function l9#unique(items) - let sorted = sort(a:items) - if len(sorted) < 2 - return sorted - endif - let last = remove(sorted, 0) - let result = [last] - for item in sorted - if item != last - call add(result, item) - let last = item - endif - endfor - return result -endfunction - -" Removes duplicates (stable) -" This function doesn't change the list of argument. -function l9#uniqueStably(items) - let result = [] - for item in a:items - if count(result, item, &ignorecase) == 0 - call add(result, item) - endif - endfor - return result -endfunction - -" [ [0], [1,2], [3] ] -> [ 0, 1, 2, 3 ] -" This function doesn't change the list of argument. -function l9#concat(items) - let result = [] - for l in a:items - let result += l - endfor - return result -endfunction - -" [ [0,1,2], [3,4], [5,6,7,8] ] -> [ [0,3,5],[1,4,6] ] -" This function doesn't change the list of argument. -function l9#zip(items) - let result = [] - for i in range(min(map(copy(a:items), 'len(v:val)'))) - call add(result, map(copy(a:items), 'v:val[i]')) - endfor - return result -endfunction - -" filter() with the maximum number of items -" This function doesn't change the list of argument. -function l9#filterWithLimit(items, expr, limit) - if a:limit <= 0 - return filter(copy(a:items), a:expr) - endif - let result = [] - let stride = a:limit * 3 / 2 " x1.5 - for i in range(0, len(a:items) - 1, stride) - let result += filter(a:items[i : i + stride - 1], a:expr) - if len(result) >= a:limit - return remove(result, 0, a:limit - 1) - endif - endfor - return result -endfunction - -" Removes if a:expr is evaluated as non-zero and returns removed items. -" This function change the list of argument. -function l9#removeIf(items, expr) - let removed = filter(copy(a:items), a:expr) - call filter(a:items, '!( ' . a:expr . ')') - return removed -endfunction - -" }}}1 -"============================================================================= -" NUMERIC {{{1 - -" }}}1 -"============================================================================= -" STRING {{{1 - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function l9#snipHead(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - return a:mask . a:str[-a:len + len(a:mask):] -endfunction - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function l9#snipTail(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - return a:str[:a:len - 1 - len(a:mask)] . a:mask -endfunction - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function l9#snipMid(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - let len_head = (a:len - len(a:mask)) / 2 - let len_tail = a:len - len(a:mask) - len_head - return (len_head > 0 ? a:str[: len_head - 1] : '') . a:mask . - \ (len_tail > 0 ? a:str[-len_tail :] : '') -endfunction - -" -function l9#hash224(str) - let a = 0x00000800 " shift 11 bit (if unsigned) - let b = 0x001fffff " extract 11 bit (if unsigned) - let nHash = 7 - let hashes = repeat([0], nHash) - for i in range(len(a:str)) - let iHash = i % nHash - let hashes[iHash] = hashes[iHash] * a + hashes[iHash] / b - let hashes[iHash] += char2nr(a:str[i]) - endfor - return join(map(hashes, 'printf("%08x", v:val)'), '') -endfunction - -" wildcard -> regexp -function l9#convertWildcardToRegexp(expr) - let re = escape(a:expr, '\') - for [pat, sub] in [ [ '*', '\\.\\*' ], [ '?', '\\.' ], [ '[', '\\[' ], ] - let re = substitute(re, pat, sub, 'g') - endfor - return '\V' . re -endfunction - -" }}}1 -"============================================================================= -" LINES {{{1 - -" Removes from the line matching with a:begin first to the line matching with -" a:end next and returns removed lines. -" If matching range is not found, returns [] -function l9#removeLinesBetween(lines, begin, end) - for i in range(len(a:lines) - 1) - if a:lines[i] =~ a:begin - break - endif - endfor - for j in range(i + 1, len(a:lines) - 1) - if a:lines[j] =~ a:end - let g:l0 += [a:lines[i : j]] - return remove(a:lines, i, j) - endif - endfor - return [] -endfunction - -" }}}1 -"============================================================================= -" PATH {{{1 - -" returns the path separator charactor. -function l9#getPathSeparator() - return (!&shellslash && (has('win32') || has('win64')) ? '\' : '/') -endfunction - -" [ 'a', 'b/', '/c' ] -> 'a/b/c' -function l9#concatPaths(paths) - let result = '' - for p in a:paths - if empty(p) - continue - elseif empty(result) - let result = p - else - let result = substitute(result, '[/\\]$', '', '') . l9#getPathSeparator() - \ . substitute(p, '^[/\\]', '', '') - endif - endfor - return result -endfunction - -" path: '/a/b/c/d', dir: '/a/b' => 'c/d' -function l9#modifyPathRelativeToDir(path, dir) - let pathFull = fnamemodify(a:path, ':p') - let dirFull = fnamemodify(a:dir, ':p') - if len(pathFull) < len(dirFull) || pathFull[:len(dirFull) - 1] !=# dirFull - return pathFull - endif - return pathFull[len(dirFull):] -endfunction - -" }}}1 -"============================================================================= -" FILE {{{1 - -" Almost same as readfile(). -function l9#readFile(...) - let args = copy(a:000) - let args[0] = expand(args[0]) - try - return call('readfile', args) - catch - endtry - return [] -endfunction - -" Almost same as writefile(). -function l9#writeFile(...) - let args = copy(a:000) - let args[1] = expand(args[1]) - let dir = fnamemodify(args[1], ':h') - try - if !isdirectory(dir) - call mkdir(dir, 'p') - endif - return call('writefile', args) - catch - endtry - return -1 " -1 is error code. -endfunction - -" }}}1 -"============================================================================= -" BUFFER {{{1 - -" :wall/:wall! wrapper. Useful for writing readonly buffers. -function l9#writeAll() - try - silent update " NOTE: avoiding a problem with a buftype=acwrite buffer. - silent wall - catch /^Vim/ " E45, E505 - if l9#inputHl('Question', v:exception . "\nWrite readonly files? (Y/N) : ", 'Y') ==? 'y' - redraw - :wall! - endif - endtry -endfunction - -" Loads given files with :edit command -function l9#loadFilesToBuffers(files) - for file in filter(copy(a:files), '!bufloaded(v:val)') - execute 'edit ' . fnameescape(file) - if !exists('bufNrFirst') - let bufNrFirst = bufnr('%') - endif - endfor - if exists('bufNrFirst') - execute bufNrFirst . 'buffer' - endif -endfunction - -" Deletes all buffers except given files with :bdelete command -function l9#deleteAllBuffersExcept(files) - let bufNrExcepts = map(copy(a:files), 'bufnr("^" . v:val . "$")') - for bufNr in filter(range(1, bufnr('$')), 'bufloaded(v:val)') - if count(bufNrExcepts, bufNr) == 0 - execute bufNr . 'bdelete' - endif - endfor -endfunction - -" }}}1 -"============================================================================= -" WINDOW {{{1 - -" move current window to next tabpage. -function l9#shiftWinNextTabpage() - if tabpagenr('$') < 2 - return - endif - let bufnr = bufnr('%') - tabnext - execute bufnr . 'sbuffer' - tabprevious - if winnr('$') > 1 - close - tabnext - else - close " if tabpage is closed, next tabpage will become current - endif -endfunction - -" move current window to previous tabpage. -function l9#shiftWinPrevTabpage() - if tabpagenr('$') < 2 - return - endif - let bufnr = bufnr('%') - tabprevious - execute bufnr . 'sbuffer' - tabnext - close - tabprevious -endfunction - -" move to a window containing specified buffer. -" returns 0 if the buffer is not found. -function l9#moveToBufferWindowInCurrentTabpage(bufNr) - if bufnr('%') == a:bufNr - return 1 - elseif count(tabpagebuflist(), a:bufNr) == 0 - return 0 - endif - execute bufwinnr(a:bufNr) . 'wincmd w' - return 1 -endfunction - -" returns 0 if the buffer is not found. -function s:moveToOtherTabpageOpeningBuffer(bufNr) - for tabNr in range(1, tabpagenr('$')) - if tabNr != tabpagenr() && count(tabpagebuflist(tabNr), a:bufNr) > 0 - execute 'tabnext ' . tabNr - return 1 - endif - endfor - return 0 -endfunction - -" move to a window containing specified buffer. -" returns 0 if the buffer is not found. -function l9#moveToBufferWindowInOtherTabpage(bufNr) - if !s:moveToOtherTabpageOpeningBuffer(a:bufNr) - return 0 - endif - return l9#moveToBufferWindowInCurrentTabpage(a:bufNr) -endfunction - -" }}}1 -"============================================================================= -" COMMAND LINE {{{1 - -" echo/echomsg with highlighting. -function l9#echoHl(hl, msg, prefix, addingHistory) - let echoCmd = (a:addingHistory ? 'echomsg' : 'echo') - execute "echohl " . a:hl - try - for l in (type(a:msg) == type([]) ? a:msg : split(a:msg, "\n")) - execute echoCmd . ' a:prefix . l' - endfor - finally - echohl None - endtry -endfunction - -" input() with highlighting. -" This function can take list as {completion} argument. -function l9#inputHl(hl, ...) - execute "echohl " . a:hl - try - let args = copy(a:000) - if len(args) > 2 && type(args[2]) == type([]) - let s:candidatesForInputHl = args[2] - let args[2] = 'custom,l9#completeForInputHl' - endif - let s = call('input', args) - unlet! s:candidatesForInputHl - finally - echohl None - endtry - redraw " needed to show following echo to next line. - return s -endfunction - -" only called by l9#inputHl() for completion. -function l9#completeForInputHl(lead, line, pos) - return join(s:candidatesForInputHl, "\n") -endfunction - -" }}}1 -"============================================================================= -" VISUAL MODE {{{1 - -" returns last selected text in Visual mode. -function l9#getSelectedText() - let reg_ = [@", getregtype('"')] - let regA = [@a, getregtype('a')] - if mode() =~# "[vV\]" - silent normal! "aygv - else - let pos = getpos('.') - silent normal! gv"ay - call setpos('.', pos) - endif - let text = @a - call setreg('"', reg_[0], reg_[1]) - call setreg('a', regA[0], regA[1]) - return text -endfunction - - -" }}}1 -"============================================================================= -" EVAL {{{1 - -" loads given text as Vim script with :source command -function l9#loadScript(text) - let lines = (type(a:text) == type([]) ? a:text : split(a:text, "\n")) - let fname = tempname() - call writefile(lines, fname) - source `=fname` - call delete(fname) -endfunction - - -" }}}1 -"============================================================================= -" VARIABLES {{{1 - -" -function l9#defineVariableDefault(name, default) - if !exists(a:name) - let {a:name} = a:default - endif -endfunction - -" }}}1 -"============================================================================= -" GREP {{{1 - -" Execute :vimgrep and opens the quickfix window if matches are found. -" -" a:pattern: search pattern. If ommitted, last search pattern (@/) is used. -" a:files: List of files -function l9#grepFiles(pattern, files) - let target = join(map(a:files, 'escape(v:val, " ")'), ' ') - let pattern = (a:pattern[0] ==# '/' ? a:pattern[1:] : a:pattern) - let pattern = (empty(pattern) ? @/ : pattern) - try - execute printf('vimgrep/%s/j %s', pattern, target) - catch /^Vim/ - call setqflist([]) - endtry - call l9#quickfix#sort() - call l9#quickfix#openIfNotEmpty(1, 0) -endfunction - -" Execute :vimgrep for buffers using l9#grepFiles() -" See also: :L9GrepBuffer :L9GrepBufferAll -function l9#grepBuffers(pattern, bufNrs) - let files = map(filter(a:bufNrs, 'bufloaded(v:val)'), 'bufname(v:val)') - call l9#grepFiles(a:pattern, files) -endfunction - -" }}}1 -"============================================================================= -" SIGN {{{1 - -" Highlights lines using :sign define and :sign place. -" -" a:linehl, a:text, a:texthl: See |signs|. Ignored if empty string. -" a:locations: List of [{buffer number}, {line number}] for highlighting -function l9#placeSign(linehl, text, texthl, locations) - let argLinehl = (empty(a:linehl) ? '' : 'linehl=' . a:linehl) - let argText = (empty(a:text) ? '' : 'text=' . a:text) - let argTexthl = (empty(a:texthl) ? '' : 'texthl=' . a:texthl) - let name = 'l9--' . a:linehl . '--' . a:text . '--' . a:texthl - execute printf('sign define %s linehl=%s text=%s texthl=%s', - \ name, a:linehl, a:text, a:texthl) - for [bufNr, lnum] in a:locations - execute printf('sign place 1 line=%d name=%s buffer=%d', lnum, name, bufNr) - endfor -endfunction - -" }}}1 -"============================================================================= -" NOTIFY EXTERNALLY {{{1 - -" Notify a message using an external program. -" Currently supports Balloonly, Screen, and Tmux. -function l9#notifyExternally(msg) - return l9#notifyBalloonly(a:msg) - \ || l9#notifyScreen(a:msg) - \ || l9#notifyTmux(a:msg) -endfunction - -" -function l9#notifyBalloonly(msg) - if !(has('win32') || has('win64')) || !executable(g:l9_balloonly) - return 0 - endif - execute 'silent !start ' . shellescape(g:l9_balloonly) . ' 4000 "l9" ' . shellescape(a:msg) - return 1 -endfunction - -" -function l9#notifyScreen(msg) - if !has('unix') || has('gui_running') || $WINDOW !~ '\d' || !executable('screen') - return 0 - endif - call system('screen -X wall ' . shellescape('l9: ' . a:msg)) - return 1 -endfunction - -" -function l9#notifyTmux(msg) - if !has('unix') || has('gui_running') || empty($TMUX) || !executable('tmux') - return 0 - endif - call system('tmux display-message ' . shellescape('l9: ' . a:msg)) - return 1 -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/.vim/autoload/l9/async.py b/.vim/autoload/l9/async.py deleted file mode 100644 index eeb0cc3..0000000 --- a/.vim/autoload/l9/async.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python - -from __future__ import with_statement -import vim -import os -import subprocess -import threading -import Queue - - -class Asyncer: - - def __init__(self): - self._workers = {} - - def execute(self, var_key, var_command, var_cwd, var_input, var_appends): - key = vim.eval(var_key) - command = vim.eval(var_command) - cwd = vim.eval(var_cwd) - input = vim.eval(var_input) - appends = vim.eval(var_appends) - if key not in self._workers: - self._workers[key] = Worker() - self._workers[key].start() - self._workers[key].put(Executor(command, cwd, input, appends)) - - def print_output(self, var_key): - key = vim.eval(var_key) - if key not in self._workers: - return - for l in self._workers[key].copy_outputs(): - print l, - - def print_worker_keys(self): - for k in self._workers.keys(): - print k - - def print_active_worker_keys(self): - for k in self._workers.keys(): - print k - - -class Worker(threading.Thread): - - def __init__(self): - threading.Thread.__init__(self) - self._queue = Queue.Queue() - self._lines = [] - self._lock = threading.Lock() - - def run(self): - while True: - self._queue.get().execute(self) - self._queue.task_done() - - def put(self, executor): - self._queue.put(executor) - - def clear_outputs(self): - with self._lock: - self._lines = [] - - def record_output(self, line): - with self._lock: - self._lines.append(line) - - def copy_outputs(self): - with self._lock: - return self._lines[:] - - -class Executor: - - def __init__(self, command, cwd, input, appends): - self._command = command - self._cwd = cwd - self._input = input - self._appends = appends - - def execute(self, worker): - if not self._appends: - worker.clear_outputs() - os.chdir(self._cwd) - p = subprocess.Popen(self._command, shell=True, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - p.stdin.write(self._input) - line = p.stdout.readline() - while line: - worker.record_output(line) - line = p.stdout.readline() - - diff --git a/.vim/autoload/l9/async.vim b/.vim/autoload/l9/async.vim deleted file mode 100644 index fa66e9f..0000000 --- a/.vim/autoload/l9/async.vim +++ /dev/null @@ -1,67 +0,0 @@ -"============================================================================= -" Copyright (C) 2009-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, ['has("python")']) - finish -endif - -" }}}1 -"============================================================================= -" ASYNC EXECUTE {{{1 - -" -function s:checkKey(key) - if a:key =~ '\n' || a:key !~ '\S' - throw "Asyncer: Invalid key: " . a:key - endif -endfunction - -" -function l9#async#execute(key, cmd, cwd, input, appends) - call s:checkKey(a:key) - python asyncer.execute('a:key', 'a:cmd', 'a:cwd', 'a:input', 'a:appends') -endfunction - -" -function l9#async#read(key) - call s:checkKey(a:key) - redir => result - silent python asyncer.print_output('a:key') - redir END - " NOTE: "\n" is somehow inserted by redir. - return (result[0] ==# "\n" ? result[1:] : result) -endfunction - -" -function l9#async#listWorkers() - redir => result - silent python asyncer.print_worker_keys() - redir END - return split(result, "\n") -endfunction - -" -function l9#async#listActiveWorkers() - redir => result - silent python asyncer.print_active_worker_keys() - redir END - return split(result, "\n") -endfunction - -" }}}1 -"============================================================================= -" INITIALIZATION {{{1 - -let s:ASYNC_PY_PATH = fnamemodify(expand(':p:h'), ':p') . 'async.py' - -pyfile `=s:ASYNC_PY_PATH` -python asyncer = Asyncer() - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - - diff --git a/.vim/autoload/l9/quickfix.vim b/.vim/autoload/l9/quickfix.vim deleted file mode 100644 index 1758b39..0000000 --- a/.vim/autoload/l9/quickfix.vim +++ /dev/null @@ -1,107 +0,0 @@ -"============================================================================= -" Copyright (C) 2009-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" QUICKFIX {{{1 - -" Returns non-zero if quickfix window is opened. -function l9#quickfix#isWindowOpened() - return count(map(range(1, winnr('$')), 'getwinvar(v:val, "&buftype")'), 'quickfix') > 0 -endfunction - -" Opens quickfix window if quickfix is not empty, and echo the number of errors. -" -" a:onlyRecognized: if non-zero, opens only if quickfix has recognized errors. -" a:holdCursor: if non-zero, the cursor won't move to quickfix window. -function l9#quickfix#openIfNotEmpty(onlyRecognized, holdCursor) - let numErrors = len(filter(getqflist(), 'v:val.valid')) - let numOthers = len(getqflist()) - numErrors - if numErrors > 0 || (!a:onlyRecognized && numOthers > 0) - copen - if a:holdCursor - wincmd p - endif - else - cclose - endif - redraw - if numOthers > 0 - echo printf('Quickfix: %d(+%d)', numErrors, numOthers) - else - echo printf('Quickfix: %d', numErrors) - endif -endfunction - -" Toggles Quickfix window -function l9#quickfix#toggleWindow() - if l9#quickfix#isWindowOpened() - cclose - else - call l9#quickfix#openIfNotEmpty(0, 0) - endif -endfunction - -" Creates quickfix list form given lines and opens the quickfix window if -" errors exists. -" -" a:lines: -" a:jump: if non-zero, jump to the first error. -function l9#quickfix#setMakeResult(lines) - cexpr a:lines - call l9#quickfix#openIfNotEmpty(0, 1) -endfunction - -" Compares quickfix entries for sorting. -function l9#quickfix#compareEntries(e0, e1) - if a:e0.bufnr != a:e1.bufnr - let i0 = bufname(a:e0.bufnr) - let i1 = bufname(a:e1.bufnr) - elseif a:e0.lnum != a:e1.lnum - let i0 = a:e0.lnum - let i1 = a:e1.lnum - elseif a:e0.col != a:e1.col - let i0 = a:e0.col - let i1 = a:e1.col - else - return 0 - endif - return (i0 > i1 ? +1 : -1) -endfunction - -" Sorts quickfix -function l9#quickfix#sort() - call setqflist(sort(getqflist(), 'l9#quickfix#compareEntries'), 'r') -endfunction - -" Highlights Quickfix lines by :sign. -" Inspired by errormarker plugin. -" -" You can customize the highlighting via L9ErrorLine and L9WarningLine -" highlight groups. -function l9#quickfix#placeSign() - let warnings = [] - let errors = [] - for e in filter(getqflist(), 'v:val.valid') - let warning = (e.type ==? 'w' || e.text =~? '^\s*warning:') - call add((warning ? warnings : errors), [e.bufnr, e.lnum]) - endfor - sign unplace * - call l9#placeSign('L9WarningLine', '>>', '', warnings) - call l9#placeSign('L9ErrorLine', '>>', '', errors) -endfunction - -highlight default L9ErrorLine ctermfg=white ctermbg=52 guibg=#5F0000 -highlight default L9WarningLine ctermfg=white ctermbg=17 guibg=#00005F - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/l9/tempbuffer.vim b/.vim/autoload/l9/tempbuffer.vim deleted file mode 100644 index 6f11a78..0000000 --- a/.vim/autoload/l9/tempbuffer.vim +++ /dev/null @@ -1,112 +0,0 @@ -"============================================================================= -" Copyright (C) 2009-2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" TEMPORARY BUFFER {{{1 - -" each key is a buffer name. -let s:dataMap = {} - -" -function s:onBufDelete(bufname) - if exists('s:dataMap[a:bufname].listener.onClose') - call s:dataMap[a:bufname].listener.onClose(s:dataMap[a:bufname].written) - endif - if bufnr('%') == s:dataMap[a:bufname].bufNr && winnr('#') != 0 - " if winnr('#') returns 0, "wincmd p" causes ringing the bell. - wincmd p - endif -endfunction - -" -function s:onBufWriteCmd(bufname) - if !exists('s:dataMap[a:bufname].listener.onWrite') || - \ s:dataMap[a:bufname].listener.onWrite(getline(1, '$')) - setlocal nomodified - let s:dataMap[a:bufname].written = 1 - call l9#tempbuffer#close(a:bufname) - else - endif -endfunction - -" a:bufname: -" a:height: Window height. If 0, default height is used. -" If less than 0, the window becomes full-screen. -" a:listener: -" a:listener.onClose(written) -function l9#tempbuffer#openScratch(bufname, filetype, lines, topleft, vertical, height, listener) - let openCmdPrefix = (a:topleft ? 'topleft ' : '') - \ . (a:vertical ? 'vertical ' : '') - \ . (a:height > 0 ? a:height : '') - if !exists('s:dataMap[a:bufname]') || !bufexists(s:dataMap[a:bufname].bufNr) - execute openCmdPrefix . 'new' - else - call l9#tempbuffer#close(a:bufname) - execute openCmdPrefix . 'split' - execute 'silent ' . s:dataMap[a:bufname].bufNr . 'buffer' - endif - if a:height < 0 - only - endif - setlocal buflisted noswapfile bufhidden=delete modifiable noreadonly buftype=nofile - let &l:filetype = a:filetype - silent file `=a:bufname` - call setline(1, a:lines) - setlocal nomodified - augroup L9TempBuffer - autocmd! * - execute printf('autocmd BufDelete call s:onBufDelete (%s)', string(a:bufname)) - execute printf('autocmd BufWriteCmd nested call s:onBufWriteCmd(%s)', string(a:bufname)) - augroup END - let s:dataMap[a:bufname] = { - \ 'bufNr': bufnr('%'), - \ 'written': 0, - \ 'listener': a:listener, - \ } -endfunction - -" -function l9#tempbuffer#openReadOnly(bufname, filetype, lines, topleft, vertical, height, listener) - call l9#tempbuffer#openScratch(a:bufname, a:filetype, a:lines, a:topleft, a:vertical, a:height, a:listener) - setlocal nomodifiable readonly -endfunction - -" a:listener: -" a:listener.onClose(written) -" a:listener.onWrite(lines) -function l9#tempbuffer#openWritable(bufname, filetype, lines, topleft, vertical, height, listener) - call l9#tempbuffer#openScratch(a:bufname, a:filetype, a:lines, a:topleft, a:vertical, a:height, a:listener) - setlocal buftype=acwrite -endfunction - -" makes specified temp buffer current. -function l9#tempbuffer#moveTo(bufname) - return l9#moveToBufferWindowInCurrentTabpage(s:dataMap[a:bufname].bufNr) || - \ l9#moveToBufferWindowInOtherTabpage(s:dataMap[a:bufname].bufNr) -endfunction - -" -function l9#tempbuffer#close(bufname) - if !l9#tempbuffer#isOpen(a:bufname) - return - endif - execute printf('%dbdelete!', s:dataMap[a:bufname].bufNr) -endfunction - -" -function l9#tempbuffer#isOpen(bufname) - return exists('s:dataMap[a:bufname]') && bufloaded(s:dataMap[a:bufname].bufNr) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/l9/tempvariables.vim b/.vim/autoload/l9/tempvariables.vim deleted file mode 100644 index ee847ee..0000000 --- a/.vim/autoload/l9/tempvariables.vim +++ /dev/null @@ -1,60 +0,0 @@ -"============================================================================= -" Copyright (C) 2010 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if !l9#guardScriptLoading(expand(':p'), 0, 0, []) - finish -endif - -" }}}1 -"============================================================================= -" TEMPORARY VARIABLES {{{1 - -" -let s:origMap = {} - -" set temporary variables -function l9#tempvariables#set(group, name, value) - if !exists('s:origMap[a:group]') - let s:origMap[a:group] = {} - endif - if !exists('s:origMap[a:group][a:name]') - let s:origMap[a:group][a:name] = eval(a:name) - endif - execute 'let ' . a:name . ' = a:value' -endfunction - -" set temporary variables -function l9#tempvariables#setList(group, variables) - for [name, value] in a:variables - call l9#tempvariables#set(a:group, name, value) - unlet value " to avoid E706 - endfor -endfunction - -" get temporary variables -function l9#tempvariables#getList(group) - if !exists('s:origMap[a:group]') - return [] - endif - return map(keys(s:origMap[a:group]), '[v:val, eval(v:val)]') -endfunction - -" restore original variables and clean up. -function l9#tempvariables#end(group) - if !exists('s:origMap[a:group]') - return - endif - for [name, value] in items(s:origMap[a:group]) - execute 'let ' . name . ' = value' - unlet value " to avoid E706 - endfor - unlet s:origMap[a:group] -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/.vim/autoload/rails.vim b/.vim/autoload/rails.vim deleted file mode 100644 index f3fc46f..0000000 --- a/.vim/autoload/rails.vim +++ /dev/null @@ -1,4607 +0,0 @@ -" autoload/rails.vim -" Author: Tim Pope - -" Install this file as autoload/rails.vim. This file is sourced manually by -" plugin/rails.vim. It is in autoload directory to allow for future usage of -" Vim 7's autoload feature. - -" ============================================================================ - -" Exit quickly when: -" - this plugin was already loaded (or disabled) -" - when 'compatible' is set -if &cp || exists("g:autoloaded_rails") - finish -endif -let g:autoloaded_rails = '4.0' - -let s:cpo_save = &cpo -set cpo&vim - -" Utility Functions {{{1 - -let s:app_prototype = {} -let s:file_prototype = {} -let s:buffer_prototype = {} -let s:readable_prototype = {} - -function! s:add_methods(namespace, method_names) - for name in a:method_names - let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name) - endfor -endfunction - -function! s:function(name) - return function(substitute(a:name,'^s:',matchstr(expand(''), '\d\+_'),'')) -endfunction - -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:startswith(string,prefix) - return strpart(a:string, 0, strlen(a:prefix)) ==# a:prefix -endfunction - -function! s:compact(ary) - return s:sub(s:sub(s:gsub(a:ary,'\n\n+','\n'),'\n$',''),'^\n','') -endfunction - -function! s:scrub(collection,item) - " Removes item from a newline separated collection - let col = "\n" . a:collection - let idx = stridx(col,"\n".a:item."\n") - let cnt = 0 - while idx != -1 && cnt < 100 - let col = strpart(col,0,idx).strpart(col,idx+strlen(a:item)+1) - let idx = stridx(col,"\n".a:item."\n") - let cnt += 1 - endwhile - return strpart(col,1) -endfunction - -function! s:escarg(p) - return s:gsub(a:p,'[ !%#]','\\&') -endfunction - -function! s:esccmd(p) - return s:gsub(a:p,'[!%#]','\\&') -endfunction - -function! s:rquote(str) - " Imperfect but adequate for Ruby arguments - if a:str =~ '^[A-Za-z0-9_/.:-]\+$' - return a:str - elseif &shell =~? 'cmd' - return '"'.s:gsub(s:gsub(a:str,'\','\\'),'"','\\"').'"' - else - return "'".s:gsub(s:gsub(a:str,'\','\\'),"'","'\\\\''")."'" - endif -endfunction - -function! s:sname() - return fnamemodify(s:file,':t:r') -endfunction - -function! s:pop_command() - if exists("s:command_stack") && len(s:command_stack) > 0 - exe remove(s:command_stack,-1) - endif -endfunction - -function! s:push_chdir(...) - if !exists("s:command_stack") | let s:command_stack = [] | endif - if exists("b:rails_root") && a:0 ? getcwd() !=# rails#app().path() : !s:startswith(getcwd(), rails#app().path()) - let chdir = exists("*haslocaldir") && haslocaldir() ? "lchdir " : "chdir " - call add(s:command_stack,chdir.s:escarg(getcwd())) - exe chdir.s:escarg(rails#app().path()) - else - call add(s:command_stack,"") - endif -endfunction - -function! s:app_path(...) dict - return join([self.root]+a:000,'/') -endfunction - -function! s:app_has_file(file) dict - return filereadable(self.path(a:file)) -endfunction - -function! s:app_find_file(name, ...) dict abort - let trim = strlen(self.path())+1 - if a:0 - let path = s:pathjoin(map(s:pathsplit(a:1),'self.path(v:val)')) - else - let path = s:pathjoin([self.path()]) - endif - let suffixesadd = s:pathjoin(get(a:000,1,&suffixesadd)) - let default = get(a:000,2,'') - let oldsuffixesadd = &l:suffixesadd - try - let &suffixesadd = suffixesadd - " Versions before 7.1.256 returned directories from findfile - if type(default) == type(0) && (v:version < 702 || default == -1) - let all = findfile(a:name,path,-1) - if v:version < 702 - call filter(all,'!isdirectory(v:val)') - endif - call map(all,'s:gsub(strpart(fnamemodify(v:val,":p"),trim),"\\\\","/")') - return default < 0 ? all : get(all,default-1,'') - elseif type(default) == type(0) - let found = findfile(a:name,path,default) - else - let i = 1 - let found = findfile(a:name,path) - while v:version < 702 && found != "" && isdirectory(found) - let i += 1 - let found = findfile(a:name,path,i) - endwhile - endif - return found == "" ? default : s:gsub(strpart(fnamemodify(found,':p'),trim),'\\','/') - finally - let &l:suffixesadd = oldsuffixesadd - endtry -endfunction - -call s:add_methods('app',['path','has_file','find_file']) - -" Split a path into a list. From pathogen.vim -function! s:pathsplit(path) abort - if type(a:path) == type([]) | return copy(a:path) | endif - let split = split(a:path,'\\\@' - if matchstr(self.getline(a:lnum+1),'^'.spc) && !matchstr(self.getline(a:lnum+1),'^'.spc.endpat) && matchstr(cline,endpat) - return a:lnum - endif - let endl = a:lnum - while endl <= self.line_count() - let endl += 1 - if self.getline(endl) =~ '^'.spc.endpat - return endl - elseif self.getline(endl) =~ '^=begin\>' - while self.getline(endl) !~ '^=end\>' && endl <= self.line_count() - let endl += 1 - endwhile - let endl += 1 - elseif self.getline(endl) !~ '^'.spc && self.getline(endl) !~ '^\s*\%(#.*\)\=$' - return 0 - endif - endwhile - return 0 -endfunction - -function! s:endof(lnum) - return rails#buffer().end_of(a:lnum) -endfunction - -function! s:readable_last_opening_line(start,pattern,limit) dict abort - let line = a:start - while line > a:limit && self.getline(line) !~ a:pattern - let line -= 1 - endwhile - let lend = self.end_of(line) - if line > a:limit && (lend < 0 || lend >= a:start) - return line - else - return -1 - endif -endfunction - -function! s:lastopeningline(pattern,limit,start) - return rails#buffer().last_opening_line(a:start,a:pattern,a:limit) -endfunction - -function! s:readable_define_pattern() dict abort - if self.name() =~ '\.yml$' - return '^\%(\h\k*:\)\@=' - endif - let define = '^\s*def\s\+\(self\.\)\=' - if self.name() =~# '\.rake$' - let define .= "\\\|^\\s*\\%(task\\\|file\\)\\s\\+[:'\"]" - endif - if self.name() =~# '/schema\.rb$' - let define .= "\\\|^\\s*create_table\\s\\+[:'\"]" - endif - return define -endfunction - -function! s:readable_last_method_line(start) dict abort - return self.last_opening_line(a:start,self.define_pattern(),0) -endfunction - -function! s:lastmethodline(start) - return rails#buffer().last_method_line(a:start) -endfunction - -function! s:readable_last_method(start) dict abort - let line = self.last_method_line(a:start) - if line - return s:sub(matchstr(self.getline(line),'\%('.self.define_pattern().'\)\zs\h\%(\k\|[:.]\)*[?!=]\='),':$','') - else - return "" - endif -endfunction - -function! s:lastmethod(...) - return rails#buffer().last_method(a:0 ? a:1 : line(".")) -endfunction - -function! s:readable_last_format(start) dict abort - let rline = self.last_opening_line('\C^\s*respond_to\s*\%(\ rline - let match = matchstr(self.getline(line),'\C^\s*'.variable.'\s*\.\s*\zs\h\k*') - if match != '' - return match - endif - let line -= 1 - endwhile - endif - return "" -endfunction - -function! s:lastformat(start) - return rails#buffer().last_format(a:start) -endfunction - -function! s:format(...) - if RailsFileType() =~ '^view\>' - let format = fnamemodify(RailsFilePath(),':r:e') - else - let format = rails#buffer().last_format(a:0 > 1 ? a:2 : line(".")) - endif - if format == '' - return get({'rhtml': 'html', 'rxml': 'xml', 'rjs': 'js'},fnamemodify(RailsFilePath(),':e'),a:0 ? a:1 : '') - endif - return format -endfunction - -call s:add_methods('readable',['end_of','last_opening_line','last_method_line','last_method','last_format','define_pattern']) - -let s:view_types = 'rhtml,erb,rxml,builder,rjs,mab,liquid,haml,dryml,mn' - -function! s:viewspattern() - return '\%('.s:gsub(s:view_types,',','\\|').'\)' -endfunction - -function! s:controller(...) - return rails#buffer().controller_name(a:0 ? a:1 : 0) -endfunction - -function! s:readable_controller_name(...) dict abort - let f = self.name() - if has_key(self,'getvar') && self.getvar('rails_controller') != '' - return self.getvar('rails_controller') - elseif f =~ '\ get(self,last_lines_ftime,0) - let self.last_lines = readfile(self.path()) - let self.last_lines_ftime = ftime - endif - return get(self,'last_lines',[]) -endfunction - -function! s:file_getline(lnum,...) dict abort - if a:0 - return self.lines[lnum-1 : a:1-1] - else - return self.lines[lnum-1] - endif -endfunction - -function! s:buffer_lines() dict abort - return self.getline(1,'$') -endfunction - -function! s:buffer_getline(...) dict abort - if a:0 == 1 - return get(call('getbufline',[self.number()]+a:000),0,'') - else - return call('getbufline',[self.number()]+a:000) - endif -endfunction - -function! s:readable_line_count() dict abort - return len(self.lines()) -endfunction - -function! s:environment() - if exists('$RAILS_ENV') - return $RAILS_ENV - else - return "development" - endif -endfunction - -function! s:Complete_environments(...) - return s:completion_filter(rails#app().environments(),a:0 ? a:1 : "") -endfunction - -function! s:warn(str) - echohl WarningMsg - echomsg a:str - echohl None - " Sometimes required to flush output - echo "" - let v:warningmsg = a:str -endfunction - -function! s:error(str) - echohl ErrorMsg - echomsg a:str - echohl None - let v:errmsg = a:str -endfunction - -function! s:debug(str) - if exists("g:rails_debug") && g:rails_debug - echohl Debug - echomsg a:str - echohl None - endif -endfunction - -function! s:buffer_getvar(varname) dict abort - return getbufvar(self.number(),a:varname) -endfunction - -function! s:buffer_setvar(varname, val) dict abort - return setbufvar(self.number(),a:varname,a:val) -endfunction - -call s:add_methods('buffer',['getvar','setvar']) - -" }}}1 -" "Public" Interface {{{1 - -" RailsRoot() is the only official public function - -function! rails#underscore(str) - let str = s:gsub(a:str,'::','/') - let str = s:gsub(str,'(\u+)(\u\l)','\1_\2') - let str = s:gsub(str,'(\l|\d)(\u)','\1_\2') - let str = tolower(str) - return str -endfunction - -function! rails#camelize(str) - let str = s:gsub(a:str,'/(.=)','::\u\1') - let str = s:gsub(str,'%([_-]|<)(.)','\u\1') - return str -endfunction - -function! rails#singularize(word) - " Probably not worth it to be as comprehensive as Rails but we can - " still hit the common cases. - let word = a:word - if word =~? '\.js$' || word == '' - return word - endif - let word = s:sub(word,'eople$','ersons') - let word = s:sub(word,'[aeio]@ 0 && getbufvar(nr,'rails_file_type') != '' - return getbufvar(nr,'rails_file_type') - elseif f =~ '_controller\.rb$' || f =~ '\' - let r = "controller-api" - else - let r = "controller" - endif - elseif f =~ '_api\.rb' - let r = "api" - elseif f =~ '\' - let top = join(s:readfile(full_path,50),"\n") - let class = matchstr(top,'\') - if class == "ActiveResource::Base" - let class = "ares" - let r = "model-ares" - elseif class != '' - let class = tolower(s:gsub(class,'[^A-Z]','')) - let r = "model-".s:sub(class,'^amb>','mailer') - elseif f =~ '_mailer\.rb$' - let r = "model-mailer" - elseif top =~ '\<\%(validates_\w\+_of\|set_\%(table_name\|primary_key\)\|has_one\|has_many\|belongs_to\)\>' - let r = "model-arb" - else - let r = "model" - endif - elseif f =~ '\.*\.' - let r = "view-layout-" . e - elseif f =~ '\<\%(app/views\|components\)/.*/_\k\+\.\k\+\%(\.\k\+\)\=$' - let r = "view-partial-" . e - elseif f =~ '\.*\.' || f =~ '\' - if e == "yml" - let r = "fixtures-yaml" - else - let r = "fixtures" . (e == "" ? "" : "-" . e) - endif - elseif f =~ '\' || f=~ '\.*\.rb$' - let r = "config-routes" - elseif f =~ '\"')) - else - return a:type - endif -endfunction - -function! s:app_environments() dict - if self.cache.needs('environments') - call self.cache.set('environments',self.relglob('config/environments/','**/*','.rb')) - endif - return copy(self.cache.get('environments')) -endfunction - -function! s:app_default_locale() dict abort - if self.cache.needs('default_locale') - let candidates = map(filter(s:readfile(self.path('config/environment.rb')),'v:val =~ "^ *config.i18n.default_locale = :[\"'']\\=[A-Za-z-]\\+[\"'']\\= *$"'),'matchstr(v:val,"[A-Za-z-]\\+[\"'']\\= *$")') - call self.cache.set('default_locale',get(candidates,0,'en')) - endif - return self.cache.get('default_locale') -endfunction - -function! s:app_has(feature) dict - let map = { - \'test': 'test/', - \'spec': 'spec/', - \'cucumber': 'features/', - \'sass': 'public/stylesheets/sass/'} - if self.cache.needs('features') - call self.cache.set('features',{}) - endif - let features = self.cache.get('features') - if !has_key(features,a:feature) - let path = get(map,a:feature,a:feature.'/') - let features[a:feature] = isdirectory(rails#app().path(path)) - endif - return features[a:feature] -endfunction - -" Returns the subset of ['test', 'spec', 'cucumber'] present on the app. -function! s:app_test_suites() dict - return filter(['test','spec','cucumber'],'self.has(v:val)') -endfunction - -call s:add_methods('app',['default_locale','environments','file','has','test_suites']) -call s:add_methods('file',['path','name','lines','getline']) -call s:add_methods('buffer',['app','number','path','name','lines','getline','type_name']) -call s:add_methods('readable',['app','calculate_file_type','type_name','line_count']) - -" }}}1 -" Ruby Execution {{{1 - -function! s:app_ruby_shell_command(cmd) dict abort - if self.path() =~ '://' - return "ruby ".a:cmd - else - return "ruby -C ".s:rquote(self.path())." ".a:cmd - endif -endfunction - -function! s:app_background_ruby_command(cmd) dict abort - let cmd = s:esccmd(self.ruby_shell_command(a:cmd)) - if has_key(self,'options') && has_key(self.options,'gnu_screen') - let screen = self.options.gnu_screen - else - let screen = g:rails_gnu_screen - endif - if has("gui_win32") - if &shellcmdflag == "-c" && ($PATH . &shell) =~? 'cygwin' - silent exe "!cygstart -d ".s:rquote(self.path())." ruby ".a:cmd - else - exe "!start ".cmd - endif - elseif exists("$STY") && !has("gui_running") && screen && executable("screen") - silent exe "!screen -ln -fn -t ".s:sub(s:sub(a:cmd,'\s.*',''),'^%(script|-rcommand)/','rails-').' '.cmd - else - exe "!".cmd - endif - return v:shell_error -endfunction - -function! s:app_execute_ruby_command(cmd) dict abort - exe "!".s:esccmd(self.ruby_shell_command(a:cmd)) - return v:shell_error -endfunction - -function! s:app_lightweight_ruby_eval(ruby,...) dict abort - let def = a:0 ? a:1 : "" - if !executable("ruby") - return def - endif - let args = '-e '.s:rquote('begin; require %{rubygems}; rescue LoadError; end; begin; require %{active_support}; rescue LoadError; end; '.a:ruby) - let cmd = self.ruby_shell_command(args) - " If the shell is messed up, this command could cause an error message - silent! let results = system(cmd) - return v:shell_error == 0 ? results : def -endfunction - -function! s:app_eval(ruby,...) dict abort - let def = a:0 ? a:1 : "" - if !executable("ruby") - return def - endif - let args = "-r./config/boot -r ".s:rquote(self.path("config/environment"))." -e ".s:rquote(a:ruby) - let cmd = self.ruby_shell_command(args) - " If the shell is messed up, this command could cause an error message - silent! let results = system(cmd) - return v:shell_error == 0 ? results : def -endfunction - -call s:add_methods('app', ['ruby_shell_command','execute_ruby_command','background_ruby_command','lightweight_ruby_eval','eval']) - -" }}}1 -" Commands {{{1 - -function! s:prephelp() - let fn = fnamemodify(s:file,':h:h').'/doc/' - if filereadable(fn.'rails.txt') - if !filereadable(fn.'tags') || getftime(fn.'tags') <= getftime(fn.'rails.txt') - silent! helptags `=fn` - endif - endif -endfunction - -function! RailsHelpCommand(...) - call s:prephelp() - let topic = a:0 ? a:1 : "" - if topic == "" || topic == "-" - return "help rails" - elseif topic =~ '^g:' - return "help ".topic - elseif topic =~ '^-' - return "help rails".topic - else - return "help rails-".topic - endif -endfunction - -function! s:BufCommands() - call s:BufFinderCommands() - call s:BufNavCommands() - call s:BufScriptWrappers() - command! -buffer -bar -nargs=? -bang -count -complete=customlist,s:Complete_rake Rake :call s:Rake(0,! && ? -1 : ,) - command! -buffer -bar -nargs=? -bang -range -complete=customlist,s:Complete_preview Rpreview :call s:Preview(0,,) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_environments Rlog :call s:Log(0,) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_set Rset :call s:Set(0,) - command! -buffer -bar -nargs=0 Rtags :call rails#app().tags_command() - " Embedding all this logic directly into the command makes the error - " messages more concise. - command! -buffer -bar -nargs=? -bang Rdoc : - \ if 0 || =~ "^\\([:'-]\\|g:\\)" | - \ exe RailsHelpCommand() | - \ else | call s:Doc(0,) | endif - command! -buffer -bar -nargs=0 -bang Rrefresh :if 0|unlet! g:autoloaded_rails|source `=s:file`|endif|call s:Refresh(0) - if exists(":NERDTree") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rtree :NERDTree `=rails#app().path()` - elseif exists(":Project") - command! -buffer -bar -nargs=? Rtree :call s:Project(0,) - endif - command! -buffer -bar -nargs=? Rproject :call s:warn("Warning: :Rproject has been deprecated in favor of :Rtree") | Rtree - if exists("g:loaded_dbext") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_environments Rdbext :call s:BufDatabase(2,)|let b:dbext_buffer_defaulted = 1 - endif - let ext = expand("%:e") - if ext =~ s:viewspattern() - " TODO: complete controller names with trailing slashes here - command! -buffer -bar -nargs=? -range -complete=customlist,s:controllerList Rextract :,call s:Extract(0,) - endif - if RailsFilePath() =~ '\0) - endif -endfunction - -function! s:Doc(bang, string) - if a:string != "" - if exists("g:rails_search_url") - let query = substitute(a:string,'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g') - let url = printf(g:rails_search_url, query) - else - return s:error("specify a g:rails_search_url with %s for a query placeholder") - endif - elseif isdirectory(rails#app().path("doc/api/classes")) - let url = rails#app().path("/doc/api/index.html") - elseif s:getpidfor("0.0.0.0","8808") > 0 - let url = "http://localhost:8808" - else - let url = "http://api.rubyonrails.org" - endif - call s:initOpenURL() - if exists(":OpenURL") - exe "OpenURL ".s:escarg(url) - else - return s:error("No :OpenURL command found") - endif -endfunction - -function! s:Log(bang,arg) - if a:arg == "" - let lf = "log/".s:environment().".log" - else - let lf = "log/".a:arg.".log" - endif - let size = getfsize(rails#app().path(lf)) - if size >= 1048576 - call s:warn("Log file is ".((size+512)/1024)."KB. Consider :Rake log:clear") - endif - if a:bang - exe "cgetfile ".lf - clast - else - if exists(":Tail") - Tail `=rails#app().path(lf)` - else - pedit `=rails#app().path(lf)` - endif - endif -endfunction - -function! rails#new_app_command(bang,...) - if a:0 == 0 - let msg = "rails.vim ".g:autoloaded_rails - if a:bang && exists('b:rails_root') && RailsFileType() == '' - echo msg." (Rails)" - elseif a:bang && exists('b:rails_root') - echo msg." (Rails-".RailsFileType().")" - elseif a:bang - echo msg - else - !rails - endif - return - endif - let dir = "" - if a:1 !~ '^-' - let dir = a:1 - elseif a:{a:0} =~ '[\/]' - let dir = a:{a:0} - else - let dir = a:1 - endif - let str = "" - let c = 1 - while c <= a:0 - let str .= " " . s:rquote(expand(a:{c})) - let c += 1 - endwhile - let dir = expand(dir) - let append = "" - if g:rails_default_database != "" && str !~ '-d \|--database=' - let append .= " -d ".g:rails_default_database - endif - if a:bang - let append .= " --force" - endif - exe "!rails".append.str - if filereadable(dir."/".g:rails_default_file) - edit `=dir.'/'.g:rails_default_file` - endif -endfunction - -function! s:app_tags_command() dict - if exists("g:Tlist_Ctags_Cmd") - let cmd = g:Tlist_Ctags_Cmd - elseif executable("exuberant-ctags") - let cmd = "exuberant-ctags" - elseif executable("ctags-exuberant") - let cmd = "ctags-exuberant" - elseif executable("ctags") - let cmd = "ctags" - elseif executable("ctags.exe") - let cmd = "ctags.exe" - else - return s:error("ctags not found") - endif - exe '!'.cmd.' -f '.s:escarg(self.path("tmp/tags")).' -R --langmap="ruby:+.rake.builder.rjs" '.g:rails_ctags_arguments.' '.s:escarg(self.path()) -endfunction - -call s:add_methods('app',['tags_command']) - -function! s:Refresh(bang) - if exists("g:rubycomplete_rails") && g:rubycomplete_rails && has("ruby") && exists('g:rubycomplete_completions') - silent! ruby ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) - silent! ruby if defined?(ActiveSupport::Dependencies); ActiveSupport::Dependencies.clear; elsif defined?(Dependencies); Dependencies.clear; end - if a:bang - silent! ruby ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) - endif - endif - call rails#app().cache.clear() - silent doautocmd User BufLeaveRails - if a:bang - for key in keys(s:apps) - if type(s:apps[key]) == type({}) - call s:apps[key].cache.clear() - endif - call extend(s:apps[key],filter(copy(s:app_prototype),'type(v:val) == type(function("tr"))'),'force') - endfor - endif - let i = 1 - let max = bufnr('$') - while i <= max - let rr = getbufvar(i,"rails_root") - if rr != "" - call setbufvar(i,"rails_refresh",1) - endif - let i += 1 - endwhile - silent doautocmd User BufEnterRails -endfunction - -function! s:RefreshBuffer() - if exists("b:rails_refresh") && b:rails_refresh - let oldroot = b:rails_root - unlet! b:rails_root - let b:rails_refresh = 0 - call RailsBufInit(oldroot) - unlet! b:rails_refresh - endif -endfunction - -" }}}1 -" Rake {{{1 - -function! s:app_rake_tasks() dict - if self.cache.needs('rake_tasks') - call s:push_chdir() - try - let lines = split(system("rake -T"),"\n") - finally - call s:pop_command() - endtry - if v:shell_error != 0 - return [] - endif - call map(lines,'matchstr(v:val,"^rake\\s\\+\\zs\\S*")') - call filter(lines,'v:val != ""') - call self.cache.set('rake_tasks',lines) - endif - return self.cache.get('rake_tasks') -endfunction - -call s:add_methods('app', ['rake_tasks']) - -let s:efm_backtrace='%D(in\ %f),' - \.'%\\s%#from\ %f:%l:%m,' - \.'%\\s%#from\ %f:%l:,' - \.'%\\s#{RAILS_ROOT}/%f:%l:\ %#%m,' - \.'%\\s%#[%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:' - -function! s:makewithruby(arg,bang,...) - let old_make = &makeprg - try - let &l:makeprg = rails#app().ruby_shell_command(a:arg) - exe 'make'.(a:bang ? '!' : '') - if !a:bang - cwindow - endif - finally - let &l:makeprg = old_make - endtry -endfunction - -function! s:Rake(bang,lnum,arg) - let self = rails#app() - let lnum = a:lnum < 0 ? 0 : a:lnum - let old_makeprg = &l:makeprg - let old_errorformat = &l:errorformat - try - if &l:makeprg !~# 'rake' - let &l:makeprg = 'rake' - endif - let &l:errorformat = s:efm_backtrace - let t = RailsFileType() - let arg = a:arg - if &filetype == "ruby" && arg == '' && g:rails_modelines - let mnum = s:lastmethodline(lnum) - let str = getline(mnum)."\n".getline(mnum+1)."\n".getline(mnum+2)."\n" - let pat = '\s\+\zs.\{-\}\ze\%(\n\|\s\s\|#{\@!\|$\)' - let mat = matchstr(str,'#\s*rake'.pat) - let mat = s:sub(mat,'\s+$','') - if mat != "" - let arg = mat - endif - endif - if arg == '' - let opt = s:getopt('task','bl') - if opt != '' - let arg = opt - else - let arg = rails#buffer().default_rake_task(lnum) - endif - endif - let withrubyargs = '-r ./config/boot -r '.s:rquote(self.path('config/environment')).' -e "puts \%((in \#{Dir.getwd}))" ' - if arg =~# '^notes\>' - let &l:errorformat = '%-P%f:,\ \ *\ [%*[\ ]%l]\ [%t%*[^]]] %m,\ \ *\ [%*[\ ]%l] %m,%-Q' - " %D to chdir is apparently incompatible with %P multiline messages - call s:push_chdir(1) - exe 'make! '.arg - call s:pop_command() - if !a:bang - cwindow - endif - elseif arg =~# '^\%(stats\|routes\|secret\|time:zones\|db:\%(charset\|collation\|fixtures:identify\>.*\|version\)\)\%([: ]\|$\)' - let &l:errorformat = '%D(in\ %f),%+G%.%#' - exe 'make! '.arg - if !a:bang - copen - endif - elseif arg =~ '^preview\>' - exe (lnum == 0 ? '' : lnum).'R'.s:gsub(arg,':','/') - elseif arg =~ '^runner:' - let arg = s:sub(arg,'^runner:','') - let root = matchstr(arg,'%\%(:\w\)*') - let file = expand(root).matchstr(arg,'%\%(:\w\)*\zs.*') - if file =~ '#.*$' - let extra = " -- -n ".matchstr(file,'#\zs.*') - let file = s:sub(file,'#.*','') - else - let extra = '' - endif - if self.has_file(file) || self.has_file(file.'.rb') - call s:makewithruby(withrubyargs.'-r"'.file.'"'.extra,a:bang,file !~# '_\%(spec\|test\)\%(\.rb\)\=$') - else - call s:makewithruby(withrubyargs.'-e '.s:esccmd(s:rquote(arg)),a:bang) - endif - elseif arg == 'run' || arg == 'runner' - call s:makewithruby(withrubyargs.'-r"'.RailsFilePath().'"',a:bang,RailsFilePath() !~# '_\%(spec\|test\)\%(\.rb\)\=$') - elseif arg =~ '^run:' - let arg = s:sub(arg,'^run:','') - let arg = s:sub(arg,'^\%:h',expand('%:h')) - let arg = s:sub(arg,'^%(\%|$|#@=)',expand('%')) - let arg = s:sub(arg,'#(\w+[?!=]=)$',' -- -n\1') - call s:makewithruby(withrubyargs.'-r'.arg,a:bang,arg !~# '_\%(spec\|test\)\.rb$') - else - exe 'make! '.arg - if !a:bang - cwindow - endif - endif - finally - let &l:errorformat = old_errorformat - let &l:makeprg = old_makeprg - endtry -endfunction - -function! s:readable_default_rake_task(lnum) dict abort - let app = self.app() - let t = self.type_name() - let lnum = a:lnum < 0 ? 0 : a:lnum - if self.getline(lnum) =~# '# rake ' - return matchstr(self.getline(lnum),'\C# rake \zs.*') - elseif self.getline(self.last_method_line(lnum)-1) =~# '# rake ' - return matchstr(self.getline(self.last_method_line(lnum)-1),'\C# rake \zs.*') - elseif self.getline(self.last_method_line(lnum)) =~# '# rake ' - return matchstr(self.getline(self.last_method_line(lnum)),'\C# rake \zs.*') - elseif self.getline(1) =~# '# rake ' && !lnum - return matchstr(self.getline(1),'\C# rake \zs.*') - elseif t =~ '^config-routes\>' - return 'routes' - elseif t =~ '^fixtures-yaml\>' && lnum - return "db:fixtures:identify LABEL=".self.last_method(lnum) - elseif t =~ '^fixtures\>' && lnum == 0 - return "db:fixtures:load FIXTURES=".s:sub(fnamemodify(self.name(),':r'),'^.{-}/fixtures/','') - elseif t =~ '^task\>' - let mnum = self.last_method_line(lnum) - let line = getline(mnum) - " We can't grab the namespace so only run tasks at the start of the line - if line =~# '^\%(task\|file\)\>' - return self.last_method(a:lnum) - else - return matchstr(self.getline(1),'\C# rake \zs.*') - endif - elseif t =~ '^spec\>' - if self.name() =~# '\' - let meth = self.last_method(lnum) - if meth =~ '^test_' - let call = " -n".meth."" - else - let call = "" - endif - if t =~ '^test-\%(unit\|functional\|integration\)$' - return s:sub(s:gsub(t,'-',':'),'unit$|functional$','&s')." TEST=\"%:p\"".s:sub(call,'^ ',' TESTOPTS=') - elseif self.name() =~# '\' && self.name() !~# '\' - return 'test:units TEST="%:p:r:s?[\/]app[\/]models[\/]?/test/unit/?_test.rb"' - elseif t=~ '^api\>' - return 'test:units TEST="%:p:r:s?[\/]app[\/]apis[\/]?/test/functional/?_test.rb"' - elseif t=~ '^\<\%(controller\|helper\|view\)\>' - if self.name() =~ '\' - if lnum > 0 - return 'cucumber FEATURE="%:p":'.lnum - else - return 'cucumber FEATURE="%:p"' - endif - elseif t =~ '^cucumber\>' - return 'cucumber' - else - return '' - endif -endfunction - -function! s:Complete_rake(A,L,P) - return s:completion_filter(rails#app().rake_tasks(),a:A) -endfunction - -call s:add_methods('readable',['default_rake_task']) - -" }}}1 -" Preview {{{1 - -function! s:initOpenURL() - if !exists(":OpenURL") - if has("gui_mac") || has("gui_macvim") || exists("$SECURITYSESSIONID") - command -bar -nargs=1 OpenURL :!open - elseif has("gui_win32") - command -bar -nargs=1 OpenURL :!start cmd /cstart /b - elseif executable("sensible-browser") - command -bar -nargs=1 OpenURL :!sensible-browser - endif - endif -endfunction - -function! s:scanlineforuris(line) - let url = matchstr(a:line,"\\v\\C%(%(GET|PUT|POST|DELETE)\\s+|\w+:/)/[^ \n\r\t<>\"]*[^] .,;\n\r\t<>\":]") - if url =~ '\C^\u\+\s\+' - let method = matchstr(url,'^\u\+') - let url = matchstr(url,'\s\+\zs.*') - if method !=? "GET" - let url .= (url =~ '?' ? '&' : '?') . '_method='.tolower(method) - endif - endif - if url != "" - return [url] - else - return [] - endif -endfunction - -function! s:readable_preview_urls(lnum) dict abort - let urls = [] - let start = self.last_method_line(a:lnum) - 1 - while start > 0 && self.getline(start) =~ '^\s*\%(\%(-\=\|<%\)#.*\)\=$' - let urls = s:scanlineforuris(self.getline(start)) + urls - let start -= 1 - endwhile - let start = 1 - while start < self.line_count() && self.getline(start) =~ '^\s*\%(\%(-\=\|<%\)#.*\)\=$' - let urls += s:scanlineforuris(self.getline(start)) - let start += 1 - endwhile - if has_key(self,'getvar') && self.getvar('rails_preview') != '' - let url += [self.getvar('rails_preview')] - end - if self.name() =~ '^public/stylesheets/sass/' - let urls = urls + [s:sub(s:sub(self.name(),'^public/stylesheets/sass/','/stylesheets/'),'\.sass$','.css')] - elseif self.name() =~ '^public/' - let urls = urls + [s:sub(self.name(),'^public','')] - elseif self.controller_name() != '' && self.controller_name() != 'application' - if self.type_name('controller') && self.last_method(a:lnum) != '' - let urls += ['/'.self.controller_name().'/'.self.last_method(a:lnum).'/'] - elseif self.type_name('controller','view-layout','view-partial') - let urls += ['/'.self.controller_name().'/'] - elseif self.type_name('view') - let urls += ['/'.s:controller().'/'.fnamemodify(self.name(),':t:r:r').'/'] - endif - endif - return urls -endfunction - -call s:add_methods('readable',['preview_urls']) - -function! s:Preview(bang,lnum,arg) - let root = s:getopt("root_url") - if root == '' - let root = s:getopt("url") - endif - let root = s:sub(root,'/$','') - if a:arg =~ '://' - let uri = a:arg - elseif a:arg != '' - let uri = root.'/'.s:sub(a:arg,'^/','') - else - let uri = get(rails#buffer().preview_urls(a:lnum),0,'') - let uri = root.'/'.s:sub(s:sub(uri,'^/',''),'/$','') - endif - call s:initOpenURL() - if exists(':OpenURL') && !a:bang - exe 'OpenURL '.uri - else - " Work around bug where URLs ending in / get handled as FTP - let url = uri.(uri =~ '/$' ? '?' : '') - silent exe 'pedit '.url - wincmd w - if &filetype == '' - if uri =~ '\.css$' - setlocal filetype=css - elseif uri =~ '\.js$' - setlocal filetype=javascript - elseif getline(1) =~ '^\s*<' - setlocal filetype=xhtml - endif - endif - call RailsBufInit(rails#app().path()) - map q :bwipe - wincmd p - if !a:bang - call s:warn("Define a :OpenURL command to use a browser") - endif - endif -endfunction - -function! s:Complete_preview(A,L,P) - return rails#buffer().preview_urls(a:L =~ '^\d' ? matchstr(a:L,'^\d\+') : line('.')) -endfunction - -" }}}1 -" Script Wrappers {{{1 - -function! s:BufScriptWrappers() - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_script Rscript :call rails#app().script_command(0,) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_generate Rgenerate :call rails#app().generate_command(0,) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_destroy Rdestroy :call rails#app().destroy_command(0,) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_server Rserver :call rails#app().server_command(0,) - command! -buffer -bang -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rrunner :call rails#app().runner_command(0 ? -2 : (==?:-1),) - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rp :call rails#app().runner_command(==?:-1,'p begin '..' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rpp :call rails#app().runner_command(==?:-1,'require %{pp}; pp begin '..' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Ry :call rails#app().runner_command(==?:-1,'y begin '..' end') -endfunction - -function! s:app_generators() dict - if self.cache.needs('generators') - let generators = self.relglob("vendor/plugins/","*/generators/*") - let generators += self.relglob("","lib/generators/*") - call filter(generators,'v:val =~ "/$"') - let generators += split(glob(expand("~/.rails/generators")."/*"),"\n") - call map(generators,'s:sub(v:val,"^.*[\\\\/]generators[\\\\/]\\ze.","")') - call map(generators,'s:sub(v:val,"[\\\\/]$","")') - call self.cache.set('generators',generators) - endif - return sort(split(g:rails_generators,"\n") + self.cache.get('generators')) -endfunction - -function! s:app_script_command(bang,...) dict - let str = "" - let cmd = a:0 ? a:1 : "console" - let c = 2 - while c <= a:0 - let str .= " " . s:rquote(a:{c}) - let c += 1 - endwhile - if cmd ==# "plugin" - call self.cache.clear('generators') - endif - if a:bang || cmd =~# 'console' - return self.background_ruby_command(s:rquote("script/".cmd).str) - else - return self.execute_ruby_command(s:rquote("script/".cmd).str) - endif -endfunction - -function! s:app_runner_command(count,args) dict - if a:count == -2 - return self.script_command(a:bang,"runner",a:args) - else - let str = self.ruby_shell_command('-r./config/boot -e "require '."'commands/runner'".'" '.s:rquote(a:args)) - let res = s:sub(system(str),'\n$','') - if a:count < 0 - echo res - else - exe a:count.'put =res' - endif - endif -endfunction - -function! s:getpidfor(bind,port) - if has("win32") || has("win64") - let netstat = system("netstat -anop tcp") - let pid = matchstr(netstat,'\<'.a:bind.':'.a:port.'\>.\{-\}LISTENING\s\+\zs\d\+') - elseif executable('lsof') - let pid = system("lsof -i 4tcp@".a:bind.':'.a:port."|grep LISTEN|awk '{print $2}'") - let pid = s:sub(pid,'\n','') - else - let pid = "" - endif - return pid -endfunction - -function! s:app_server_command(bang,arg) dict - let port = matchstr(a:arg,'\%(-p\|--port=\=\)\s*\zs\d\+') - if port == '' - let port = "3000" - endif - " TODO: Extract bind argument - let bind = "0.0.0.0" - if a:bang && executable("ruby") - let pid = s:getpidfor(bind,port) - if pid =~ '^\d\+$' - echo "Killing server with pid ".pid - if !has("win32") - call system("ruby -e 'Process.kill(:TERM,".pid.")'") - sleep 100m - endif - call system("ruby -e 'Process.kill(9,".pid.")'") - sleep 100m - endif - if a:arg == "-" - return - endif - endif - if has_key(self,'options') && has_key(self.options,'gnu_screen') - let screen = self.options.gnu_screen - else - let screen = g:rails_gnu_screen - endif - if has("win32") || has("win64") || (exists("$STY") && !has("gui_running") && screen && executable("screen")) - call self.background_ruby_command(s:rquote("script/server")." ".a:arg) - else - "--daemon would be more descriptive but lighttpd does not support it - call self.execute_ruby_command(s:rquote("script/server")." ".a:arg." -d") - endif - call s:setopt('a:root_url','http://'.(bind=='0.0.0.0'?'localhost': bind).':'.port.'/') -endfunction - -function! s:app_destroy_command(bang,...) dict - if a:0 == 0 - return self.execute_ruby_command("script/destroy") - elseif a:0 == 1 - return self.execute_ruby_command("script/destroy ".s:rquote(a:1)) - endif - let str = "" - let c = 1 - while c <= a:0 - let str .= " " . s:rquote(a:{c}) - let c += 1 - endwhile - call self.execute_ruby_command(s:rquote("script/destroy").str) - call self.cache.clear('user_classes') -endfunction - -function! s:app_generate_command(bang,...) dict - if a:0 == 0 - return self.execute_ruby_command("script/generate") - elseif a:0 == 1 - return self.execute_ruby_command("script/generate ".s:rquote(a:1)) - endif - let target = s:rquote(a:1) - let str = "" - let c = 2 - while c <= a:0 - let str .= " " . s:rquote(a:{c}) - let c += 1 - endwhile - if str !~ '-p\>' && str !~ '--pretend\>' - let execstr = self.ruby_shell_command('-r./config/boot -e "require '."'commands/generate'".'" -- '.target." -p -f".str) - let res = system(execstr) - let file = matchstr(res,'\s\+\%(create\|force\)\s\+\zs\f\+\.rb\ze\n') - if file == "" - let file = matchstr(res,'\s\+\%(exists\)\s\+\zs\f\+\.rb\ze\n') - endif - else - let file = "" - endif - if !self.execute_ruby_command("script/generate ".target.str) && file != "" - call self.cache.clear('user_classes') - call self.cache.clear('features') - if file =~ '^db/migrate/\d\d\d\d' - let file = get(self.relglob('',s:sub(file,'\d+','[0-9]*[0-9]')),-1,file) - endif - edit `=self.path(file)` - endif -endfunction - -call s:add_methods('app', ['generators','script_command','runner_command','server_command','destroy_command','generate_command']) - -function! s:Complete_script(ArgLead,CmdLine,P) - let cmd = s:sub(a:CmdLine,'^\u\w*\s+','') - "let P = a:P - strlen(a:CmdLine)+strlen(cmd) - if cmd !~ '^[ A-Za-z0-9_=:-]*$' - return [] - elseif cmd =~# '^\w*$' - return s:completion_filter(rails#app().relglob("script/","**/*"),a:ArgLead) - elseif cmd =~# '^\%(plugin\)\s\+'.a:ArgLead.'$' - return s:completion_filter(["discover","list","install","update","remove","source","unsource","sources"],a:ArgLead) - elseif cmd =~# '\%(plugin\)\s\+\%(install\|remove\)\s\+'.a:ArgLead.'$' || cmd =~ '\%(generate\|destroy\)\s\+plugin\s\+'.a:ArgLead.'$' - return s:pluginList(a:ArgLead,a:CmdLine,a:P) - elseif cmd =~# '^\%(generate\|destroy\)\s\+'.a:ArgLead.'$' - return s:completion_filter(rails#app().generators(),a:ArgLead) - elseif cmd =~# '^\%(generate\|destroy\)\s\+\w\+\s\+'.a:ArgLead.'$' - let target = matchstr(cmd,'^\w\+\s\+\zs\w\+\ze\s\+') - if target =~# '^\%(\w*_\)\=controller$' - return filter(s:controllerList(a:ArgLead,"",""),'v:val !=# "application"') - elseif target =~# '^\%(\w*_\)\=model$' || target =~# '^scaffold\%(_resource\)\=$' || target ==# 'mailer' - return s:modelList(a:ArgLead,"","") - elseif target ==# 'migration' || target ==# 'session_migration' - return s:migrationList(a:ArgLead,"","") - elseif target ==# 'integration_test' || target ==# 'integration_spec' || target ==# 'feature' - return s:integrationtestList(a:ArgLead,"","") - elseif target ==# 'observer' - let observers = s:observerList("","","") - let models = s:modelList("","","") - if cmd =~# '^destroy\>' - let models = [] - endif - call filter(models,'index(observers,v:val) < 0') - return s:completion_filter(observers + models,a:ArgLead) - elseif target ==# 'web_service' - return s:apiList(a:ArgLead,"","") - else - return [] - endif - elseif cmd =~# '^\%(generate\|destroy\)\s\+scaffold\s\+\w\+\s\+'.a:ArgLead.'$' - return filter(s:controllerList(a:ArgLead,"",""),'v:val !=# "application"') - return s:completion_filter(rails#app().environments()) - elseif cmd =~# '^\%(console\)\s\+\(--\=\w\+\s\+\)\='.a:ArgLead."$" - return s:completion_filter(rails#app().environments()+["-s","--sandbox"],a:ArgLead) - elseif cmd =~# '^\%(server\)\s\+.*-e\s\+'.a:ArgLead."$" - return s:completion_filter(rails#app().environments(),a:ArgLead) - elseif cmd =~# '^\%(server\)\s\+' - if a:ArgLead =~# '^--environment=' - return s:completion_filter(map(copy(rails#app().environments()),'"--environment=".v:val'),a:ArgLead) - else - return filter(["-p","-b","-e","-m","-d","-u","-c","-h","--port=","--binding=","--environment=","--mime-types=","--daemon","--debugger","--charset=","--help"],'s:startswith(v:val,a:ArgLead)') - endif - endif - return "" -endfunction - -function! s:CustomComplete(A,L,P,cmd) - let L = "Rscript ".a:cmd." ".s:sub(a:L,'^\h\w*\s+','') - let P = a:P - strlen(a:L) + strlen(L) - return s:Complete_script(a:A,L,P) -endfunction - -function! s:Complete_server(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"server") -endfunction - -function! s:Complete_console(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"console") -endfunction - -function! s:Complete_generate(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"generate") -endfunction - -function! s:Complete_destroy(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"destroy") -endfunction - -function! s:Complete_ruby(A,L,P) - return s:completion_filter(rails#app().user_classes()+["ActiveRecord::Base"],a:A) -endfunction - -" }}}1 -" Navigation {{{1 - -function! s:BufNavCommands() - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rcd :cd `=rails#app().path()` - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rlcd :lcd `=rails#app().path()` - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rfind :call s:Find(,'' ,) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find REfind :call s:Find(,'E',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RSfind :call s:Find(,'S',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RVfind :call s:Find(,'V',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RTfind :call s:Find(,'T',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rsfind :RSfind - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rtabfind :RTfind - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit Redit :call s:Edit(,'' ,) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit REedit :call s:Edit(,'E',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RSedit :call s:Edit(,'S',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RVedit :call s:Edit(,'V',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RTedit :call s:Edit(,'T',) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_edit RDedit :call s:Edit(,'D',) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related A :call s:Alternate('', ,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AE :call s:Alternate('E',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AS :call s:Alternate('S',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AV :call s:Alternate('V',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AT :call s:Alternate('T',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AD :call s:Alternate('D',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AN :call s:Related('' ,,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related R :call s:Related('' ,,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RE :call s:Related('E',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RS :call s:Related('S',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RV :call s:Related('V',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RT :call s:Related('T',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RD :call s:Related('D',,,,) -endfunction - -function! s:djump(def) - let def = s:sub(a:def,'^[#:]','') - if def =~ '^\d\+$' - exe def - elseif def =~ '^!' - if expand('%') !~ '://' && !isdirectory(expand('%:p:h')) - call mkdir(expand('%:p:h'),'p') - endif - elseif def != '' - let ext = matchstr(def,'\.\zs.*') - let def = matchstr(def,'[^.]*') - let v:errmsg = '' - silent! exe "djump ".def - if ext != '' && (v:errmsg == '' || v:errmsg =~ '^E387') - let rpat = '\C^\s*respond_to\s*\%(\ 0 - let variable = matchstr(getline(rline),rpat) - let success = search('\C^\s*'.variable.'\s*\.\s*\zs'.ext.'\>','',end) - if !success - silent! exe "djump ".def - endif - endif - endif - endif -endfunction - -function! s:Find(count,cmd,...) - let str = "" - if a:0 - let i = 1 - while i < a:0 - let str .= s:escarg(a:{i}) . " " - let i += 1 - endwhile - let file = a:{i} - let tail = matchstr(file,'[#!].*$\|:\d*\%(:in\>.*\)\=$') - if tail != "" - let file = s:sub(file,'[#!].*$|:\d*%(:in>.*)=$','') - endif - if file != "" - let file = s:RailsIncludefind(file) - endif - else - let file = s:RailsFind() - let tail = "" - endif - call s:findedit((a:count==1?'' : a:count).a:cmd,file.tail,str) -endfunction - -function! s:Edit(count,cmd,...) - if a:0 - let str = "" - let i = 1 - while i < a:0 - let str .= "`=a:".i."` " - let i += 1 - endwhile - let file = a:{i} - call s:findedit(s:editcmdfor(a:cmd),file,str) - else - exe s:editcmdfor(a:cmd) - endif -endfunction - -function! s:fuzzyglob(arg) - return '*'.s:gsub(s:gsub(a:arg,'[^/]','[&]*'),'/','/*') -endfunction - -function! s:Complete_find(ArgLead, CmdLine, CursorPos) - let paths = s:pathsplit(&l:path) - let seen = {} - for path in paths - if s:startswith(path,rails#app().path()) && path !~ '[][*]' - let path = path[strlen(rails#app().path()) + 1 : ] - for file in rails#app().relglob(path == '' ? '' : path.'/',s:fuzzyglob(rails#underscore(a:ArgLead)), a:ArgLead =~# '\u' ? '.rb' : '') - let seen[file] = 1 - endfor - endif - endfor - let results = sort(map(keys(seen),'s:sub(v:val,"[.]rb$","")')) - return s:autocamelize(results,a:ArgLead) -endfunction - -function! s:Complete_edit(ArgLead, CmdLine, CursorPos) - return s:completion_filter(rails#app().relglob("",s:fuzzyglob(a:ArgLead)),a:ArgLead) -endfunction - -function! s:Complete_cd(ArgLead, CmdLine, CursorPos) - let all = rails#app().relglob("",a:ArgLead."*") - call filter(all,'v:val =~ "/$"') - return filter(all,'s:startswith(v:val,a:ArgLead)') -endfunction - -function! RailsIncludeexpr() - " Is this foolproof? - if mode() =~ '[iR]' || expand("") != v:fname - return s:RailsIncludefind(v:fname) - else - return s:RailsIncludefind(v:fname,1) - endif -endfunction - -function! s:linepeak() - let line = getline(line(".")) - let line = s:sub(line,'^(.{'.col(".").'}).*','\1') - let line = s:sub(line,'([:"'."'".']|\%[qQ]=[[({<])=\f*$','') - return line -endfunction - -function! s:matchcursor(pat) - let line = getline(".") - let lastend = 0 - while lastend >= 0 - let beg = match(line,'\C'.a:pat,lastend) - let end = matchend(line,'\C'.a:pat,lastend) - if beg < col(".") && end >= col(".") - return matchstr(line,'\C'.a:pat,lastend) - endif - let lastend = end - endwhile - return "" -endfunction - -function! s:findit(pat,repl) - let res = s:matchcursor(a:pat) - if res != "" - return substitute(res,'\C'.a:pat,a:repl,'') - else - return "" - endif -endfunction - -function! s:findamethod(func,repl) - return s:findit('\s*\<\%('.a:func.'\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>.\=',a:repl) -endfunction - -function! s:findasymbol(sym,repl) - return s:findit('\s*:\%('.a:sym.'\)\s*=>\s*(\=\s*[@:'."'".'"]\(\f\+\)\>.\=',a:repl) -endfunction - -function! s:findfromview(func,repl) - return s:findit('\s*\%(<%\)\==\=\s*\<\%('.a:func.'\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>['."'".'"]\=\s*\%(%>\s*\)\=',a:repl) -endfunction - -function! s:RailsFind() - if filereadable(expand("")) - return expand("") - endif - " UGH - let format = s:format('html') - let res = s:findit('\v\s*.=',expand('%:h').'/\1') - if res != ""|return res.(fnamemodify(res,':e') == '' ? '.rb' : '')|endif - let res = s:findit('\v['."'".'"]=',expand('%:h').'\1') - if res != ""|return res|endif - let res = rails#underscore(s:findit('\v\s*<%(include|extend)\(=\s*<(\f+)>','\1')) - if res != ""|return res.".rb"|endif - let res = s:findamethod('require','\1') - if res != ""|return res.(fnamemodify(res,':e') == '' ? '.rb' : '')|endif - let res = s:findamethod('belongs_to\|has_one\|composed_of\|validates_associated\|scaffold','app/models/\1.rb') - if res != ""|return res|endif - let res = rails#singularize(s:findamethod('has_many\|has_and_belongs_to_many','app/models/\1')) - if res != ""|return res.".rb"|endif - let res = rails#singularize(s:findamethod('create_table\|change_table\|drop_table\|add_column\|rename_column\|remove_column\|add_index','app/models/\1')) - if res != ""|return res.".rb"|endif - let res = rails#singularize(s:findasymbol('through','app/models/\1')) - if res != ""|return res.".rb"|endif - let res = s:findamethod('fixtures','fixtures/\1') - if res != "" - return RailsFilePath() =~ '\\s*','\1'),'^/',''),'\k+$','_&') - if res != ""|return res."\n".s:findview(res)|endif - let res = s:findamethod('render\s*:\%(template\|action\)\s\+=>\s*','\1.'.format.'\n\1') - if res != ""|return res|endif - let res = s:sub(s:findfromview('render','\1'),'^/','') - if RailsFileType() =~ '^view\>' | let res = s:sub(res,'[^/]+$','_&') | endif - if res != ""|return res."\n".s:findview(res)|endif - let res = s:findamethod('redirect_to\s*(\=\s*:action\s\+=>\s*','\1') - if res != ""|return res|endif - let res = s:findfromview('stylesheet_link_tag','public/stylesheets/\1.css') - if res != ""|return res|endif - let res = s:sub(s:findfromview('javascript_include_tag','public/javascripts/\1.js'),'/defaults>','/application') - if res != ""|return res|endif - if RailsFileType() =~ '^controller\>' - let contr = s:controller() - let view = s:findit('\s*\(\=','/\1') - let res = s:findview(contr.'/'.view) - if res != ""|return res|endif - endif - let old_isfname = &isfname - try - set isfname=@,48-57,/,-,_,: ",\",' - " TODO: grab visual selection in visual mode - let cfile = expand("") - finally - let &isfname = old_isfname - endtry - let res = s:RailsIncludefind(cfile,1) - return res -endfunction - -function! s:app_named_route_file(route) dict - call self.route_names() - if self.cache.has("named_routes") && has_key(self.cache.get("named_routes"),a:route) - return self.cache.get("named_routes")[a:route] - endif - return "" -endfunction - -function! s:app_route_names() dict - if self.cache.needs("named_routes") - let exec = "ActionController::Routing::Routes.named_routes.each {|n,r| puts %{#{n} app/controllers/#{r.requirements[:controller]}_controller.rb##{r.requirements[:action]}}}" - let string = self.eval(exec) - let routes = {} - for line in split(string,"\n") - let route = split(line," ") - let name = route[0] - let routes[name] = route[1] - endfor - call self.cache.set("named_routes",routes) - endif - - return keys(self.cache.get("named_routes")) -endfunction - -call s:add_methods('app', ['route_names','named_route_file']) - -function! RailsNamedRoutes() - return rails#app().route_names() -endfunction - -function! s:RailsIncludefind(str,...) - if a:str ==# "ApplicationController" - return "application_controller.rb\napp/controllers/application.rb" - elseif a:str ==# "Test::Unit::TestCase" - return "test/unit/testcase.rb" - endif - let str = a:str - if a:0 == 1 - " Get the text before the filename under the cursor. - " We'll cheat and peak at this in a bit - let line = s:linepeak() - let line = s:sub(line,'([:"'."'".']|\%[qQ]=[[({<])=\f*$','') - else - let line = "" - endif - let str = s:sub(str,'^\s*','') - let str = s:sub(str,'\s*$','') - let str = s:sub(str,'^:=[:@]','') - let str = s:sub(str,':0x\x+$','') " For # style output - let str = s:gsub(str,"[\"']",'') - if line =~# '\<\(require\|load\)\s*(\s*$' - return str - endif - let str = rails#underscore(str) - let fpat = '\(\s*\%("\f*"\|:\f*\|'."'\\f*'".'\)\s*,\s*\)*' - if a:str =~# '\u' - " Classes should always be in .rb files - let str .= '.rb' - elseif line =~# ':partial\s*=>\s*' - let str = s:sub(str,'([^/]+)$','_\1') - let str = s:findview(str) - elseif line =~# '\\s*' - let str = s:findview(s:sub(str,'^/=','layouts/')) - elseif line =~# ':controller\s*=>\s*' - let str = 'app/controllers/'.str.'_controller.rb' - elseif line =~# '\' : '').cmd.'",)' - let cmd = strpart(cmds,0,1) - let cmds = strpart(cmds,1) - endwhile -endfunction - -function! s:BufFinderCommands() - command! -buffer -bar -nargs=+ Rnavcommand :call s:Navcommand(0,) - call s:addfilecmds("metal") - call s:addfilecmds("model") - call s:addfilecmds("view") - call s:addfilecmds("controller") - call s:addfilecmds("migration") - call s:addfilecmds("observer") - call s:addfilecmds("helper") - call s:addfilecmds("layout") - call s:addfilecmds("fixtures") - call s:addfilecmds("locale") - if rails#app().has('test') || rails#app().has('spec') - call s:addfilecmds("unittest") - call s:addfilecmds("functionaltest") - endif - if rails#app().has('test') || rails#app().has('spec') || rails#app().has('cucumber') - call s:addfilecmds("integrationtest") - endif - if rails#app().has('spec') - call s:addfilecmds("spec") - endif - call s:addfilecmds("stylesheet") - call s:addfilecmds("javascript") - call s:addfilecmds("plugin") - call s:addfilecmds("task") - call s:addfilecmds("lib") - call s:addfilecmds("environment") - call s:addfilecmds("initializer") -endfunction - -function! s:completion_filter(results,A) - let results = sort(type(a:results) == type("") ? split(a:results,"\n") : copy(a:results)) - call filter(results,'v:val !~# "\\~$"') - let filtered = filter(copy(results),'s:startswith(v:val,a:A)') - if !empty(filtered) | return filtered | endif - let regex = s:gsub(a:A,'[^/]','[&].*') - let filtered = filter(copy(results),'v:val =~# "^".regex') - if !empty(filtered) | return filtered | endif - let regex = s:gsub(a:A,'.','[&].*') - let filtered = filter(copy(results),'v:val =~# regex') - return filtered -endfunction - -function! s:autocamelize(files,test) - if a:test =~# '^\u' - return s:completion_filter(map(copy(a:files),'rails#camelize(v:val)'),a:test) - else - return s:completion_filter(a:files,a:test) - endif -endfunction - -function! s:app_relglob(path,glob,...) dict - if exists("+shellslash") && ! &shellslash - let old_ss = &shellslash - let &shellslash = 1 - endif - let path = a:path - if path !~ '^/' && path !~ '^\w:' - let path = self.path(path) - endif - let suffix = a:0 ? a:1 : '' - let full_paths = split(glob(path.a:glob.suffix),"\n") - let relative_paths = [] - for entry in full_paths - if suffix == '' && isdirectory(entry) && entry !~ '/$' - let entry .= '/' - endif - let relative_paths += [entry[strlen(path) : -strlen(suffix)-1]] - endfor - if exists("old_ss") - let &shellslash = old_ss - endif - return relative_paths -endfunction - -call s:add_methods('app', ['relglob']) - -function! s:relglob(...) - return join(call(rails#app().relglob,a:000,rails#app()),"\n") -endfunction - -function! s:helperList(A,L,P) - return s:autocamelize(rails#app().relglob("app/helpers/","**/*","_helper.rb"),a:A) -endfunction - -function! s:controllerList(A,L,P) - let con = rails#app().relglob("app/controllers/","**/*",".rb") - call map(con,'s:sub(v:val,"_controller$","")') - return s:autocamelize(con,a:A) -endfunction - -function! s:viewList(A,L,P) - let c = s:controller(1) - let top = rails#app().relglob("app/views/",s:fuzzyglob(a:A)) - call filter(top,'v:val !~# "\\~$"') - if c != '' && a:A !~ '/' - let local = rails#app().relglob("app/views/".c."/","*.*[^~]") - return s:completion_filter(local+top,a:A) - endif - return s:completion_filter(top,a:A) -endfunction - -function! s:layoutList(A,L,P) - return s:completion_filter(rails#app().relglob("app/views/layouts/","*"),a:A) -endfunction - -function! s:stylesheetList(A,L,P) - return s:completion_filter(rails#app().relglob("public/stylesheets/","**/*",".css"),a:A) -endfunction - -function! s:javascriptList(A,L,P) - return s:completion_filter(rails#app().relglob("public/javascripts/","**/*",".js"),a:A) -endfunction - -function! s:metalList(A,L,P) - return s:autocamelize(rails#app().relglob("app/metal/","**/*",".rb"),a:A) -endfunction - -function! s:modelList(A,L,P) - let models = rails#app().relglob("app/models/","**/*",".rb") - call filter(models,'v:val !~# "_observer$"') - return s:autocamelize(models,a:A) -endfunction - -function! s:observerList(A,L,P) - return s:autocamelize(rails#app().relglob("app/models/","**/*","_observer.rb"),a:A) -endfunction - -function! s:fixturesList(A,L,P) - return s:completion_filter(rails#app().relglob("test/fixtures/","**/*")+rails#app().relglob("spec/fixtures/","**/*"),a:A) -endfunction - -function! s:localeList(A,L,P) - return s:completion_filter(rails#app().relglob("config/locales/","**/*"),a:A) -endfunction - -function! s:migrationList(A,L,P) - if a:A =~ '^\d' - let migrations = rails#app().relglob("db/migrate/",a:A."[0-9_]*",".rb") - return map(migrations,'matchstr(v:val,"^[0-9]*")') - else - let migrations = rails#app().relglob("db/migrate/","[0-9]*[0-9]_*",".rb") - call map(migrations,'s:sub(v:val,"^[0-9]*_","")') - return s:autocamelize(migrations,a:A) - endif -endfunction - -function! s:unittestList(A,L,P) - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/unit/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/models/","**/*","_spec.rb") - endif - return s:autocamelize(found,a:A) -endfunction - -function! s:functionaltestList(A,L,P) - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/functional/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/controllers/","**/*","_spec.rb") - endif - return s:autocamelize(found,a:A) -endfunction - -function! s:integrationtestList(A,L,P) - if a:A =~# '^\u' - return s:autocamelize(rails#app().relglob("test/integration/","**/*","_test.rb"),a:A) - endif - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/integration/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/integration/","**/*","_spec.rb") - endif - if rails#app().has('cucumber') - let found += rails#app().relglob("features/","**/*",".feature") - endif - return s:completion_filter(found,a:A) -endfunction - -function! s:specList(A,L,P) - return s:completion_filter(rails#app().relglob("spec/","**/*","_spec.rb"),a:A) -endfunction - -function! s:pluginList(A,L,P) - if a:A =~ '/' - return s:completion_filter(rails#app().relglob('vendor/plugins/',matchstr(a:A,'.\{-\}/').'**/*'),a:A) - else - return s:completion_filter(rails#app().relglob('vendor/plugins/',"*","/init.rb"),a:A) - endif -endfunction - -" Task files, not actual rake tasks -function! s:taskList(A,L,P) - let all = rails#app().relglob("lib/tasks/","**/*",".rake") - if RailsFilePath() =~ '\','".name."',\"".prefix."\",".string(suffix).",".string(filter).",".string(default).",)" - let cmd = strpart(cmds,0,1) - let cmds = strpart(cmds,1) - endwhile -endfunction - -function! s:CommandList(A,L,P) - let cmd = matchstr(a:L,'\CR[A-Z]\=\w\+') - exe cmd." &" - let lp = s:last_prefix . "\n" - let res = [] - while lp != "" - let p = matchstr(lp,'.\{-\}\ze\n') - let lp = s:sub(lp,'.{-}\n','') - let res += rails#app().relglob(p,s:last_filter,s:last_suffix) - endwhile - if s:last_camelize - return s:autocamelize(res,a:A) - else - return s:completion_filter(res,a:A) - endif -endfunction - -function! s:CommandEdit(cmd,name,prefix,suffix,filter,default,...) - if a:0 && a:1 == "&" - let s:last_prefix = a:prefix - let s:last_suffix = a:suffix - let s:last_filter = a:filter - let s:last_camelize = (a:suffix =~# '\.rb$') - else - if a:default == "both()" - if s:model() != "" - let default = s:model() - else - let default = s:controller() - endif - elseif a:default == "model()" - let default = s:model(1) - elseif a:default == "controller()" - let default = s:controller(1) - else - let default = a:default - endif - call s:EditSimpleRb(a:cmd,a:name,a:0 ? a:1 : default,a:prefix,a:suffix) - endif -endfunction - -function! s:EditSimpleRb(cmd,name,target,prefix,suffix,...) - let cmd = s:findcmdfor(a:cmd) - if a:target == "" - " Good idea to emulate error numbers like this? - return s:error("E471: Argument required") - endif - let f = a:0 ? a:target : rails#underscore(a:target) - let jump = matchstr(f,'[#!].*\|:\d*\%(:in\)\=$') - let f = s:sub(f,'[#!].*|:\d*%(:in)=$','') - if jump =~ '^!' - let cmd = s:editcmdfor(cmd) - endif - if f == '.' - let f = s:sub(f,'\.$','') - else - let f .= a:suffix.jump - endif - let f = s:gsub(a:prefix,'\n',f.'\n').f - return s:findedit(cmd,f) -endfunction - -function! s:app_migration(file) dict - let arg = a:file - if arg =~ '^0$\|^0\=[#:]' - let suffix = s:sub(arg,'^0*','') - if self.has_file('db/schema.rb') - return 'db/schema.rb'.suffix - elseif self.has_file('db/'.s:environment().'_structure.sql') - return 'db/'.s:environment().'_structure.sql'.suffix - else - return 'db/schema.rb'.suffix - endif - elseif arg =~ '^\d$' - let glob = '00'.arg.'_*.rb' - elseif arg =~ '^\d\d$' - let glob = '0'.arg.'_*.rb' - elseif arg =~ '^\d\d\d$' - let glob = ''.arg.'_*.rb' - elseif arg == '' - let glob = '*.rb' - else - let glob = '*'.rails#underscore(arg).'*rb' - endif - let migr = s:sub(glob(self.path('db/migrate/').glob),'.*\n','') - if s:startswith(migr,self.path()) - let migr = strpart(migr,1+strlen(self.path())) - endif - return migr -endfunction - -call s:add_methods('app', ['migration']) - -function! s:migrationEdit(cmd,...) - let cmd = s:findcmdfor(a:cmd) - let arg = a:0 ? a:1 : '' - let migr = arg == "." ? "db/migrate" : rails#app().migration(arg) - if migr != '' - call s:findedit(cmd,migr) - else - return s:error("Migration not found".(arg=='' ? '' : ': '.arg)) - endif -endfunction - -function! s:fixturesEdit(cmd,...) - if a:0 - let c = rails#underscore(a:1) - else - let c = rails#pluralize(s:model(1)) - endif - if c == "" - return s:error("E471: Argument required") - endif - let e = fnamemodify(c,':e') - let e = e == '' ? e : '.'.e - let c = fnamemodify(c,':r') - let file = get(rails#app().test_suites(),0,'test').'/fixtures/'.c.e - if file =~ '\.\w\+$' && rails#app().find_file(c.e,["test/fixtures","spec/fixtures"]) ==# '' - call s:edit(a:cmd,file) - else - call s:findedit(a:cmd,rails#app().find_file(c.e,["test/fixtures","spec/fixtures"],[".yml",".csv"],file)) - endif -endfunction - -function! s:localeEdit(cmd,...) - let c = a:0 ? a:1 : rails#app().default_locale() - if c =~# '\.' - call s:edit(a:cmd,rails#app().find_file(c,'config/locales',[],'config/locales/'.c)) - else - call s:findedit(a:cmd,rails#app().find_file(c,'config/locales',['.yml','.rb'],'config/locales/'.c)) - endif -endfunction - -function! s:metalEdit(cmd,...) - if a:0 - call s:EditSimpleRb(a:cmd,"metal",a:1,"app/metal/",".rb") - else - call s:EditSimpleRb(a:cmd,"metal",'config/boot',"",".rb") - endif -endfunction - -function! s:modelEdit(cmd,...) - call s:EditSimpleRb(a:cmd,"model",a:0? a:1 : s:model(1),"app/models/",".rb") -endfunction - -function! s:observerEdit(cmd,...) - call s:EditSimpleRb(a:cmd,"observer",a:0? a:1 : s:model(1),"app/models/","_observer.rb") -endfunction - -function! s:viewEdit(cmd,...) - if a:0 && a:1 =~ '^[^!#:]' - let view = matchstr(a:1,'[^!#:]*') - elseif RailsFileType() == 'controller' - let view = s:lastmethod(line('.')) - else - let view = '' - endif - if view == '' - return s:error("No view name given") - elseif view == '.' - return s:edit(a:cmd,'app/views') - elseif view !~ '/' && s:controller(1) != '' - let view = s:controller(1) . '/' . view - endif - if view !~ '/' - return s:error("Cannot find view without controller") - endif - let file = "app/views/".view - let found = s:findview(view) - if found != '' - let dir = fnamemodify(rails#app().path(found),':h') - if !isdirectory(dir) - if a:0 && a:1 =~ '!' - call mkdir(dir) - else - return s:error('No such directory') - endif - endif - call s:edit(a:cmd,found) - elseif file =~ '\.\w\+$' - call s:findedit(a:cmd,file) - else - let format = s:format('html') - if glob(rails#app().path(file.'.'.format).'.*[^~]') != '' - let file .= '.' . format - endif - call s:findedit(a:cmd,file) - endif -endfunction - -function! s:findview(name) - " TODO: full support of nested extensions - let c = a:name - let pre = "app/views/" - let file = "" - if c !~ '/' - let controller = s:controller(1) - if controller != '' - let c = controller.'/'.c - endif - endif - if c =~ '\.\w\+\.\w\+$' || c =~ '\.'.s:viewspattern().'$' - return pre.c - elseif rails#app().has_file(pre.c.".rhtml") - let file = pre.c.".rhtml" - elseif rails#app().has_file(pre.c.".rxml") - let file = pre.c.".rxml" - else - let format = "." . s:format('html') - let vt = s:view_types."," - while 1 - while vt != "" - let t = matchstr(vt,'[^,]*') - let vt = s:sub(vt,'[^,]*,','') - if rails#app().has_file(pre.c.format.".".t) - let file = pre.c.format.".".t - break - endif - endwhile - if format == '' || file != '' - break - else - let format = '' - endif - endwhile - endif - return file -endfunction - -function! s:findlayout(name) - return s:findview("layouts/".(a:name == '' ? 'application' : a:name)) -endfunction - -function! s:layoutEdit(cmd,...) - if a:0 - return s:viewEdit(a:cmd,"layouts/".a:1) - endif - let file = s:findlayout(s:controller(1)) - if file == "" - let file = s:findlayout("application") - endif - if file == "" - let file = "app/views/layouts/application.html.erb" - endif - call s:edit(a:cmd,s:sub(file,'^/','')) -endfunction - -function! s:controllerEdit(cmd,...) - let suffix = '.rb' - if a:0 == 0 - let controller = s:controller(1) - if RailsFileType() =~ '^view\%(-layout\|-partial\)\@!' - let suffix .= '#'.expand('%:t:r') - endif - else - let controller = a:1 - endif - if rails#app().has_file("app/controllers/".controller."_controller.rb") || !rails#app().has_file("app/controllers/".controller.".rb") - let suffix = "_controller".suffix - endif - return s:EditSimpleRb(a:cmd,"controller",controller,"app/controllers/",suffix) -endfunction - -function! s:helperEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"helper",a:0? a:1 : s:controller(1),"app/helpers/","_helper.rb") -endfunction - -function! s:stylesheetEdit(cmd,...) - let name = a:0 ? a:1 : s:controller(1) - if rails#app().has('sass') && rails#app().has_file('public/stylesheets/sass/'.name.'.sass') - return s:EditSimpleRb(a:cmd,"stylesheet",name,"public/stylesheets/sass/",".sass",1) - else - return s:EditSimpleRb(a:cmd,"stylesheet",name,"public/stylesheets/",".css",1) - endif -endfunction - -function! s:javascriptEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"javascript",a:0? a:1 : "application","public/javascripts/",".js",1) -endfunction - -function! s:unittestEdit(cmd,...) - let f = rails#underscore(a:0 ? matchstr(a:1,'[^!#:]*') : s:model(1)) - let jump = a:0 ? matchstr(a:1,'[!#:].*') : '' - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/unit/','_test.rb'], 'spec': ['spec/models/','_spec.rb']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping['test']] - endif - for [prefix, suffix] in tests - if !a:0 && RailsFileType() =~# '^model-aro\>' && f != '' && f !~# '_observer$' - if rails#app().has_file(prefix.f.'_observer'.suffix) - return s:findedit(cmd,prefix.f.'_observer'.suffix.jump) - endif - endif - endfor - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"unittest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:functionaltestEdit(cmd,...) - let f = rails#underscore(a:0 ? matchstr(a:1,'[^!#:]*') : s:controller(1)) - let jump = a:0 ? matchstr(a:1,'[!#:].*') : '' - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/functional/','_test.rb'], 'spec': ['spec/controllers/','_spec.rb']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping[tests]] - endif - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - elseif rails#app().has_file(prefix.f.'_controller'.suffix) - return s:findedit(cmd,prefix.f.'_controller'.suffix.jump) - elseif rails#app().has_file(prefix.f.'_api'.suffix) - return s:findedit(cmd,prefix.f.'_api'.suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"functionaltest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:integrationtestEdit(cmd,...) - if !a:0 - return s:EditSimpleRb(a:cmd,"integrationtest","test/test_helper\nfeatures/support/env\nspec/spec_helper","",".rb") - endif - let f = rails#underscore(matchstr(a:1,'[^!#:]*')) - let jump = matchstr(a:1,'[!#:].*') - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/integration/','_test.rb'], 'spec': ['spec/integration/','_spec.rb'], 'cucumber': ['features/','.feature']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping['test']] - endif - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - elseif rails#app().has_file(prefix.rails#underscore(f).suffix) - return s:findedit(cmd,prefix.rails#underscore(f).suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"integrationtest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:specEdit(cmd,...) - if a:0 - return s:EditSimpleRb(a:cmd,"spec",a:1,"spec/","_spec.rb") - else - call s:EditSimpleRb(a:cmd,"spec","spec_helper","spec/",".rb") - endif -endfunction - -function! s:pluginEdit(cmd,...) - let cmd = s:findcmdfor(a:cmd) - let plugin = "" - let extra = "" - if RailsFilePath() =~ '\','split') - let cmd = s:sub(cmd,'find>','edit') - return cmd -endfunction - -function! s:try(cmd) abort - if !exists(":try") - " I've seen at least one weird setup without :try - exe a:cmd - else - try - exe a:cmd - catch - call s:error(s:sub(v:exception,'^.{-}:\zeE','')) - return 0 - endtry - endif - return 1 -endfunction - -function! s:findedit(cmd,files,...) abort - let cmd = s:findcmdfor(a:cmd) - let files = type(a:files) == type([]) ? copy(a:files) : split(a:files,"\n") - if len(files) == 1 - let file = files[0] - else - let file = get(filter(copy(files),'rails#app().has_file(s:sub(v:val,"#.*|:\\d*$",""))'),0,get(files,0,'')) - endif - if file =~ '[#!]\|:\d*\%(:in\)\=$' - let djump = matchstr(file,'!.*\|#\zs.*\|:\zs\d*\ze\%(:in\)\=$') - let file = s:sub(file,'[#!].*|:\d*%(:in)=$','') - else - let djump = '' - endif - if file == '' - let testcmd = "edit" - elseif isdirectory(rails#app().path(file)) - let arg = file == "." ? rails#app().path() : rails#app().path(file) - let testcmd = s:editcmdfor(cmd).' '.(a:0 ? a:1 . ' ' : '').s:escarg(arg) - exe testcmd - return - elseif rails#app().path() =~ '://' || cmd =~ 'edit' || cmd =~ 'split' - if file !~ '^/' && file !~ '^\w:' && file !~ '://' - let file = s:escarg(rails#app().path(file)) - endif - let testcmd = s:editcmdfor(cmd).' '.(a:0 ? a:1 . ' ' : '').file - else - let testcmd = cmd.' '.(a:0 ? a:1 . ' ' : '').file - endif - if s:try(testcmd) - call s:djump(djump) - endif -endfunction - -function! s:edit(cmd,file,...) - let cmd = s:editcmdfor(a:cmd) - let cmd .= ' '.(a:0 ? a:1 . ' ' : '') - let file = a:file - if file !~ '^/' && file !~ '^\w:' && file !~ '://' - exe cmd."`=fnamemodify(rails#app().path(file),':.')`" - else - exe cmd.file - endif -endfunction - -function! s:Alternate(cmd,line1,line2,count,...) - if a:0 - if a:count && a:cmd !~# 'D' - return call('s:Find',[1,a:line1.a:cmd]+a:000) - elseif a:count - return call('s:Edit',[1,a:line1.a:cmd]+a:000) - else - return call('s:Edit',[1,a:cmd]+a:000) - endif - else - let file = s:getopt(a:count ? 'related' : 'alternate', 'bl') - if file == '' - let file = rails#buffer().related(a:count) - endif - if file != '' - call s:findedit(a:cmd,file) - else - call s:warn("No alternate file is defined") - endif - endif -endfunction - -function! s:Related(cmd,line1,line2,count,...) - if a:count == 0 && a:0 == 0 - return s:Alternate(a:cmd,a:line1,a:line1,a:line1) - else - return call('s:Alternate',[a:cmd,a:line1,a:line2,a:count]+a:000) - endif -endfunction - -function! s:Complete_related(A,L,P) - if a:L =~# '^[[:alpha:]]' - return s:Complete_edit(a:A,a:L,a:P) - else - return s:Complete_find(a:A,a:L,a:P) - endif -endfunction - -function! s:readable_related(...) dict abort - let f = self.name() - let t = self.type_name() - if a:0 && a:1 - let lastmethod = self.last_method(a:1) - if t =~ '^\%(controller\|model-mailer\)\>' && lastmethod != "" - let root = s:sub(s:sub(s:sub(f,'/application\.rb$','/shared_controller.rb'),'/%(controllers|models)/','/views/'),'%(_controller)=\.rb$','/'.lastmethod) - let format = self.last_format(a:1) - if format == '' | let format = 'html' | endif - if glob(self.app().path().'/'.root.'.'.format.'.*[^~]') != '' - return root . '.' . format - else - return root - endif - elseif f =~ '\' - return s:sub(s:sub(s:sub(f,'/views/','/controllers/'),'/layouts/(\k+)\..*$','/\1_controller.rb'),'' - let controller = s:sub(s:sub(f,'/views/','/controllers/'),'/(\k+%(\.\k+)=)\..*$','_controller.rb#\1') - let controller2 = s:sub(s:sub(f,'/views/','/controllers/'),'/(\k+%(\.\k+)=)\..*$','.rb#\1') - let model = s:sub(s:sub(f,'/views/','/models/'),'/(\k+)\..*$','.rb#\1') - if self.app().has_file(s:sub(controller,'#.{-}$','')) - return controller - elseif self.app().has_file(s:sub(controller2,'#.{-}$','')) - return controller2 - elseif self.app().has_file(s:sub(model,'#.{-}$','')) || model =~ '_mailer\.rb#' - return model - else - return controller - endif - elseif t =~ '^controller\>' - return s:sub(s:sub(f,'/controllers/','/helpers/'),'%(_controller)=\.rb$','_helper.rb') - " elseif t=~ '^helper\>' - " return s:findlayout(s:controller()) - elseif t =~ '^model-arb\>' - let table_name = matchstr(join(self.getline(1,50),"\n"),'\n\s*set_table_name\s*[:"'']\zs\w\+') - if table_name == '' - let table_name = rails#pluralize(s:gsub(s:sub(fnamemodify(f,':r'),'.{-}' - return s:sub(f,'_observer\.rb$','.rb') - elseif f =~ '\ me') - let migration = "db/migrate/".get(candidates,0,migrations[0]).".rb" - endif - return migration . (exists('l:lastmethod') && lastmethod != '' ? '#'.lastmethod : '') - elseif f =~ '\' - return "public/javascripts/application.js" - elseif f =~ '\' - let spec1 = fnamemodify(f,':s?\' - let dest = fnamemodify(f,':r:s?/layouts\>??').'/layout.'.fnamemodify(f,':e') - else - let dest = f - endif - return s:sub(s:sub(dest,'' - let api = s:sub(s:sub(f,'/controllers/','/apis/'),'_controller\.rb$','_api.rb') - return api - elseif t =~ '^api\>' - return s:sub(s:sub(f,'/apis/','/controllers/'),'_api\.rb$','_controller.rb') - elseif t =~ '^helper\>' - let controller = s:sub(s:sub(f,'/helpers/','/controllers/'),'_helper\.rb$','_controller.rb') - let controller = s:sub(controller,'application_controller','application') - let spec = s:sub(s:sub(f,'' && f =~ '\' - let file = rails#singularize(fnamemodify(f,":t:r")).'_test.rb' - return file - elseif f == '' - call s:warn("No filename present") - elseif f =~ '\' - return s:sub(s:sub(f,'' - return s:sub(file,'app/models/','test/unit/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'app/models/','spec/models/') - elseif t =~ '^controller\>' - return s:sub(file,'' - return s:sub(file,'test/unit/','app/models/')."\n".s:sub(file,'test/unit/','lib/') - elseif t =~ '^test-functional\>' - if file =~ '_api\.rb' - return s:sub(file,'test/functional/','app/apis/') - elseif file =~ '_controller\.rb' - return s:sub(file,'test/functional/','app/controllers/') - else - return s:sub(file,'test/functional/','') - endif - elseif t == 'spec-lib' - return s:sub(file,'' - return s:sub(file,' 1 - return s:error("Incorrect number of arguments") - endif - if a:1 =~ '[^a-z0-9_/.]' - return s:error("Invalid partial name") - endif - let rails_root = rails#app().path() - let ext = expand("%:e") - let file = s:sub(a:1,'%(/|^)\zs_\ze[^/]*$','') - let first = a:firstline - let last = a:lastline - let range = first.",".last - if RailsFileType() =~ '^view-layout\>' - if RailsFilePath() =~ '\' - let curdir = 'app/views/shared' - if file !~ '/' - let file = "shared/" .file - endif - else - let curdir = s:sub(RailsFilePath(),'.* 0 - if bufloaded(out) - return s:error("Partial already open in buffer ".bufnr(out)) - else - exe "bwipeout ".bufnr(out) - endif - endif - " No tabs, they'll just complicate things - if ext =~? '^\%(rhtml\|erb\|dryml\)$' - let erub1 = '\<\%\s*' - let erub2 = '\s*-=\%\>' - else - let erub1 = '' - let erub2 = '' - endif - let spaces = matchstr(getline(first),"^ *") - if getline(last+1) =~ '\v^\s*'.erub1.'end'.erub2.'\s*$' - let fspaces = matchstr(getline(last+1),"^ *") - if getline(first-1) =~ '\v^'.fspaces.erub1.'for\s+(\k+)\s+in\s+([^ %>]+)'.erub2.'\s*$' - let collection = s:sub(getline(first-1),'^'.fspaces.erub1.'for\s+(\k+)\s+in\s+([^ >]+)'.erub2.'\s*$','\1>\2') - elseif getline(first-1) =~ '\v^'.fspaces.erub1.'([^ %>]+)\.each\s+do\s+\|\s*(\k+)\s*\|'.erub2.'\s*$' - let collection = s:sub(getline(first-1),'^'.fspaces.erub1.'([^ %>]+)\.each\s+do\s+\|\s*(\k+)\s*\|'.erub2.'\s*$','\2>\1') - endif - if collection != '' - let var = matchstr(collection,'^\k\+') - let collection = s:sub(collection,'^\k+\>','') - let first -= 1 - let last += 1 - endif - else - let fspaces = spaces - endif - let renderstr = "render :partial => '".fnamemodify(file,":r:r")."'" - if collection != "" - let renderstr .= ", :collection => ".collection - elseif "@".name != var - let renderstr .= ", :object => ".var - endif - if ext =~? '^\%(rhtml\|erb\|dryml\)$' - let renderstr = "<%= ".renderstr." %>" - elseif ext == "rxml" || ext == "builder" - let renderstr = "xml << ".s:sub(renderstr,"render ","render(").")" - elseif ext == "rjs" - let renderstr = "page << ".s:sub(renderstr,"render ","render(").")" - elseif ext == "haml" - let renderstr = "= ".renderstr - elseif ext == "mn" - let renderstr = "_".renderstr - endif - let buf = @@ - silent exe range."yank" - let partial = @@ - let @@ = buf - let old_ai = &ai - try - let &ai = 0 - silent exe "norm! :".first.",".last."change\".fspaces.renderstr."\.\" - finally - let &ai = old_ai - endtry - if renderstr =~ '<%' - norm ^6w - else - norm ^5w - endif - let ft = &ft - if &hidden - enew - else - new - endif - let shortout = fnamemodify(out,':.') - silent file `=shortout` - let &ft = ft - let @@ = partial - silent put - 0delete - let @@ = buf - if spaces != "" - silent! exe '%substitute/^'.spaces.'//' - endif - silent! exe '%substitute?\%(\w\|[@:"'."'".'-]\)\@?'.name.'?g' - 1 - call RailsBufInit(rails_root) - if exists("l:partial_warn") - call s:warn("Warning: partial exists!") - endif -endfunction - -" }}}1 -" Migration Inversion {{{1 - -function! s:mkeep(str) - " Things to keep (like comments) from a migration statement - return matchstr(a:str,' #[^{].*') -endfunction - -function! s:mextargs(str,num) - if a:str =~ '^\s*\w\+\s*(' - return s:sub(matchstr(a:str,'^\s*\w\+\s*\zs(\%([^,)]\+[,)]\)\{,'.a:num.'\}'),',$',')') - else - return s:sub(s:sub(matchstr(a:str,'\w\+\>\zs\s*\%([^,){ ]*[, ]*\)\{,'.a:num.'\}'),'[, ]*$',''),'^\s+',' ') - endif -endfunction - -function! s:migspc(line) - return matchstr(a:line,'^\s*') -endfunction - -function! s:invertrange(beg,end) - let str = "" - let lnum = a:beg - while lnum <= a:end - let line = getline(lnum) - let add = "" - if line == '' - let add = ' ' - elseif line =~ '^\s*\(#[^{].*\)\=$' - let add = line - elseif line =~ '\' - let add = s:migspc(line)."drop_table".s:mextargs(line,1).s:mkeep(line) - let lnum = s:endof(lnum) - elseif line =~ '\' - let add = s:sub(line,'\s*\(=\s*([^,){ ]*).*','create_table \1 do |t|'."\n".matchstr(line,'^\s*').'end').s:mkeep(line) - elseif line =~ '\' - let add = s:migspc(line).'remove_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\' - let add = s:sub(line,'','add_column') - elseif line =~ '\' - let add = s:migspc(line).'remove_index'.s:mextargs(line,1) - let mat = matchstr(line,':name\s*=>\s*\zs[^ ,)]*') - if mat != '' - let add = s:sub(add,'\)=$',', :name => '.mat.'&') - else - let mat = matchstr(line,'\[^,]*,\s*\zs\%(\[[^]]*\]\|[:"'."'".']\w*["'."'".']\=\)') - if mat != '' - let add = s:sub(add,'\)=$',', :column => '.mat.'&') - endif - endif - let add .= s:mkeep(line) - elseif line =~ '\' - let add = s:sub(s:sub(line,'\s*','') - elseif line =~ '\' - let add = s:sub(line,'' - let add = s:migspc(line).'change_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\' - let add = s:migspc(line).'change_column_default'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\.update_all(\(["'."'".']\).*\1)$' || line =~ '\.update_all \(["'."'".']\).*\1$' - " .update_all('a = b') => .update_all('b = a') - let pre = matchstr(line,'^.*\.update_all[( ][}'."'".'"]') - let post = matchstr(line,'["'."'".'])\=$') - let mat = strpart(line,strlen(pre),strlen(line)-strlen(pre)-strlen(post)) - let mat = s:gsub(','.mat.',','%(,\s*)@<=([^ ,=]{-})(\s*\=\s*)([^,=]{-})%(\s*,)@=','\3\2\1') - let add = pre.s:sub(s:sub(mat,'^,',''),',$','').post - elseif line =~ '^s\*\%(if\|unless\|while\|until\|for\)\>' - let lnum = s:endof(lnum) - endif - if lnum == 0 - return -1 - endif - if add == "" - let add = s:sub(line,'^\s*\zs.*','raise ActiveRecord::IrreversibleMigration') - elseif add == " " - let add = "" - endif - let str = add."\n".str - let lnum += 1 - endwhile - let str = s:gsub(str,'(\s*raise ActiveRecord::IrreversibleMigration\n)+','\1') - return str -endfunction - -function! s:Invert(bang) - let err = "Could not parse method" - let src = "up" - let dst = "down" - let beg = search('\%('.&l:define.'\).*'.src.'\>',"w") - let end = s:endof(beg) - if beg + 1 == end - let src = "down" - let dst = "up" - let beg = search('\%('.&l:define.'\).*'.src.'\>',"w") - let end = s:endof(beg) - endif - if !beg || !end - return s:error(err) - endif - let str = s:invertrange(beg+1,end-1) - if str == -1 - return s:error(err) - endif - let beg = search('\%('.&l:define.'\).*'.dst.'\>',"w") - let end = s:endof(beg) - if !beg || !end - return s:error(err) - endif - if foldclosed(beg) > 0 - exe beg."foldopen!" - endif - if beg + 1 < end - exe (beg+1).",".(end-1)."delete _" - endif - if str != '' - exe beg.'put =str' - exe 1+beg - endif -endfunction - -" }}}1 -" Cache {{{1 - -let s:cache_prototype = {'dict': {}} - -function! s:cache_clear(...) dict - if a:0 == 0 - let self.dict = {} - elseif has_key(self,'dict') && has_key(self.dict,a:1) - unlet! self.dict[a:1] - endif -endfunction - -function! rails#cache_clear(...) - if exists('b:rails_root') - return call(rails#app().cache.clear,a:000,rails#app().cache) - endif -endfunction - -function! s:cache_get(...) dict - if a:0 == 1 - return self.dict[a:1] - else - return self.dict - endif -endfunction - -function! s:cache_has(key) dict - return has_key(self.dict,a:key) -endfunction - -function! s:cache_needs(key) dict - return !has_key(self.dict,a:key) -endfunction - -function! s:cache_set(key,value) dict - let self.dict[a:key] = a:value -endfunction - -call s:add_methods('cache', ['clear','needs','has','get','set']) - -let s:app_prototype.cache = s:cache_prototype - -" }}}1 -" Syntax {{{1 - -function! s:resetomnicomplete() - if exists("+completefunc") && &completefunc == 'syntaxcomplete#Complete' - if exists("g:loaded_syntax_completion") - " Ugly but necessary, until we have our own completion - unlet g:loaded_syntax_completion - silent! delfunction syntaxcomplete#Complete - endif - endif -endfunction - -function! s:helpermethods() - return "" - \."atom_feed auto_discovery_link_tag auto_link " - \."benchmark button_to button_to_function button_to_remote " - \."cache capture cdata_section check_box check_box_tag collection_select concat content_for content_tag content_tag_for current_cycle cycle " - \."date_select datetime_select debug distance_of_time_in_words distance_of_time_in_words_to_now div_for dom_class dom_id draggable_element draggable_element_js drop_receiving_element drop_receiving_element_js " - \."error_message_on error_messages_for escape_javascript escape_once evaluate_remote_response excerpt " - \."field_set_tag fields_for file_field file_field_tag form form_for form_remote_for form_remote_tag form_tag " - \."grouped_collection_select grouped_options_for_select " - \."hidden_field hidden_field_tag highlight " - \."image_path image_submit_tag image_tag input " - \."javascript_cdata_section javascript_include_tag javascript_path javascript_tag " - \."l label label_tag link_to link_to_function link_to_if link_to_remote link_to_unless link_to_unless_current localize " - \."mail_to markdown " - \."number_to_currency number_to_human_size number_to_percentage number_to_phone number_with_delimiter number_with_precision " - \."observe_field observe_form option_groups_from_collection_for_select options_for_select options_from_collection_for_select " - \."partial_path password_field password_field_tag path_to_image path_to_javascript path_to_stylesheet periodically_call_remote pluralize " - \."radio_button radio_button_tag remote_form_for remote_function reset_cycle " - \."sanitize sanitize_css select select_date select_datetime select_day select_hour select_minute select_month select_second select_tag select_time select_year simple_format sortable_element sortable_element_js strip_links strip_tags stylesheet_link_tag stylesheet_path submit_tag submit_to_remote " - \."t tag text_area text_area_tag text_field text_field_tag textilize textilize_without_paragraph time_ago_in_words time_select time_zone_options_for_select time_zone_select translate truncate " - \."update_page update_page_tag url_for " - \."visual_effect " - \."word_wrap" -endfunction - -function! s:app_user_classes() dict - if self.cache.needs("user_classes") - let controllers = self.relglob("app/controllers/","**/*",".rb") - call map(controllers,'v:val == "application" ? v:val."_controller" : v:val') - let classes = - \ self.relglob("app/models/","**/*",".rb") + - \ controllers + - \ self.relglob("app/helpers/","**/*",".rb") + - \ self.relglob("lib/","**/*",".rb") - call map(classes,'rails#camelize(v:val)') - call self.cache.set("user_classes",classes) - endif - return self.cache.get('user_classes') -endfunction - -function! s:app_user_assertions() dict - if self.cache.needs("user_assertions") - if self.has_file("test/test_helper.rb") - let assertions = map(filter(s:readfile(self.path("test/test_helper.rb")),'v:val =~ "^ def assert_"'),'matchstr(v:val,"^ def \\zsassert_\\w\\+")') - else - let assertions = [] - endif - call self.cache.set("user_assertions",assertions) - endif - return self.cache.get('user_assertions') -endfunction - -call s:add_methods('app', ['user_classes','user_assertions']) - -function! s:BufSyntax() - if (!exists("g:rails_syntax") || g:rails_syntax) - let t = RailsFileType() - let s:javascript_functions = "$ $$ $A $F $H $R $w jQuery" - let rails_helper_methods = '+\.\@+' - let classes = s:gsub(join(rails#app().user_classes(),' '),'::',' ') - if &syntax == 'ruby' - if classes != '' - exe "syn keyword rubyRailsUserClass ".classes." containedin=rubyClassDeclaration,rubyModuleDeclaration,rubyClass,rubyModule" - endif - if t == '' - syn keyword rubyRailsMethod params request response session headers cookies flash - endif - if t =~ '^api\>' - syn keyword rubyRailsAPIMethod api_method inflect_names - endif - if t =~ '^model$' || t =~ '^model-arb\>' - syn keyword rubyRailsARMethod default_scope named_scope serialize - syn keyword rubyRailsARAssociationMethod belongs_to has_one has_many has_and_belongs_to_many composed_of accepts_nested_attributes_for - syn keyword rubyRailsARCallbackMethod before_create before_destroy before_save before_update before_validation before_validation_on_create before_validation_on_update - syn keyword rubyRailsARCallbackMethod after_create after_destroy after_save after_update after_validation after_validation_on_create after_validation_on_update - syn keyword rubyRailsARClassMethod attr_accessible attr_protected establish_connection set_inheritance_column set_locking_column set_primary_key set_sequence_name set_table_name - syn keyword rubyRailsARValidationMethod validate validate_on_create validate_on_update validates_acceptance_of validates_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of - syn keyword rubyRailsMethod logger - endif - if t =~ '^model-aro\>' - syn keyword rubyRailsARMethod observe - endif - if t =~ '^model-mailer\>' - syn keyword rubyRailsMethod logger - syn keyword rubyRailsControllerMethod helper helper_attr helper_method - endif - if t =~ '^controller\>' || t =~ '^view\>' || t=~ '^helper\>' - syn keyword rubyRailsMethod params request response session headers cookies flash - syn keyword rubyRailsRenderMethod render - syn keyword rubyRailsMethod logger - endif - if t =~ '^helper\>' || t=~ '^view\>' - exe "syn keyword rubyRailsHelperMethod ".s:sub(s:helpermethods(),'\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!' - syn match rubyRailsViewMethod '\.\@' - if t =~ '\' - syn keyword rubyRailsMethod local_assigns - endif - elseif t =~ '^controller\>' - syn keyword rubyRailsControllerMethod helper helper_attr helper_method filter layout url_for serialize exempt_from_layout filter_parameter_logging hide_action cache_sweeper protect_from_forgery caches_page cache_page caches_action expire_page expire_action - syn keyword rubyRailsRenderMethod render_to_string redirect_to head - syn match rubyRailsRenderMethod '\?\@!' - syn keyword rubyRailsFilterMethod before_filter append_before_filter prepend_before_filter after_filter append_after_filter prepend_after_filter around_filter append_around_filter prepend_around_filter skip_before_filter skip_after_filter - syn keyword rubyRailsFilterMethod verify - endif - if t =~ '^\%(db-\)\=\%(migration\|schema\)\>' - syn keyword rubyRailsMigrationMethod create_table change_table drop_table rename_table add_column rename_column change_column change_column_default remove_column add_index remove_index - endif - if t =~ '^test\>' - if !empty(rails#app().user_assertions()) - exe "syn keyword rubyRailsUserMethod ".join(rails#app().user_assertions()) - endif - syn keyword rubyRailsTestMethod add_assertion assert assert_block assert_equal assert_in_delta assert_instance_of assert_kind_of assert_match assert_nil assert_no_match assert_not_equal assert_not_nil assert_not_same assert_nothing_raised assert_nothing_thrown assert_operator assert_raise assert_respond_to assert_same assert_send assert_throws assert_recognizes assert_generates assert_routing flunk fixtures fixture_path use_transactional_fixtures use_instantiated_fixtures assert_difference assert_no_difference assert_valid - syn keyword rubyRailsTestMethod test setup teardown - if t !~ '^test-unit\>' - syn match rubyRailsTestControllerMethod '\.\@' - syn keyword rubyRailsTestControllerMethod assert_response assert_redirected_to assert_template assert_recognizes assert_generates assert_routing assert_dom_equal assert_dom_not_equal assert_select assert_select_rjs assert_select_encoded assert_select_email assert_tag assert_no_tag - endif - elseif t=~ '^spec\>' - syn keyword rubyRailsTestMethod describe context it specify it_should_behave_like before after subject fixtures controller_name helper_name - syn keyword rubyRailsTestMethod violated pending mock mock_model stub_model - syn match rubyRailsTestMethod '\.\@!\@!' - if t !~ '^spec-model\>' - syn match rubyRailsTestControllerMethod '\.\@' - syn keyword rubyRailsTestControllerMethod integrate_views - syn keyword rubyRailsMethod params request response session flash - endif - endif - if t =~ '^task\>' - syn match rubyRailsRakeMethod '^\s*\zs\%(task\|file\|namespace\|desc\|before\|after\|on\)\>\%(\s*=\)\@!' - endif - if t =~ '^model-awss\>' - syn keyword rubyRailsMethod member - endif - if t =~ '^config-routes\>' - syn match rubyRailsMethod '\.\zs\%(connect\|resources\=\|root\|named_route\|namespace\)\>' - endif - syn keyword rubyRailsMethod debugger - syn keyword rubyRailsMethod alias_attribute alias_method_chain attr_accessor_with_default attr_internal attr_internal_accessor attr_internal_reader attr_internal_writer delegate mattr_accessor mattr_reader mattr_writer superclass_delegating_accessor superclass_delegating_reader superclass_delegating_writer - syn keyword rubyRailsMethod cattr_accessor cattr_reader cattr_writer class_inheritable_accessor class_inheritable_array class_inheritable_array_writer class_inheritable_hash class_inheritable_hash_writer class_inheritable_option class_inheritable_reader class_inheritable_writer inheritable_attributes read_inheritable_attribute reset_inheritable_attributes write_inheritable_array write_inheritable_attribute write_inheritable_hash - syn keyword rubyRailsInclude require_dependency gem - - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:order\s*=>\s*\)\@<="+ skip=+\\\\\|\\"+ end=+"+ contains=@rubyStringSpecial,railsOrderSpecial - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:order\s*=>\s*\)\@<='+ skip=+\\\\\|\\'+ end=+'+ contains=@rubyStringSpecial,railsOrderSpecial - syn match railsOrderSpecial +\c\<\%(DE\|A\)SC\>+ contained - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:conditions\s*=>\s*\[\s*\)\@<="+ skip=+\\\\\|\\"+ end=+"+ contains=@rubyStringSpecial,railsConditionsSpecial - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:conditions\s*=>\s*\[\s*\)\@<='+ skip=+\\\\\|\\'+ end=+'+ contains=@rubyStringSpecial,railsConditionsSpecial - syn match railsConditionsSpecial +?\|:\h\w*+ contained - syn cluster rubyNotTop add=railsOrderSpecial,railsConditionsSpecial - - " XHTML highlighting inside %Q<> - unlet! b:current_syntax - let removenorend = !exists("g:html_no_rendering") - let g:html_no_rendering = 1 - syn include @htmlTop syntax/xhtml.vim - if removenorend - unlet! g:html_no_rendering - endif - let b:current_syntax = "ruby" - " Restore syn sync, as best we can - if !exists("g:ruby_minlines") - let g:ruby_minlines = 50 - endif - syn sync fromstart - exe "syn sync minlines=" . g:ruby_minlines - syn case match - syn region rubyString matchgroup=rubyStringDelimiter start=+%Q\=<+ end=+>+ contains=@htmlTop,@rubyStringSpecial - syn cluster htmlArgCluster add=@rubyStringSpecial - syn cluster htmlPreProc add=@rubyStringSpecial - - elseif &syntax == "eruby" || &syntax == "haml" - syn case match - if classes != '' - exe "syn keyword erubyRailsUserClass ".classes." contained containedin=@erubyRailsRegions" - endif - if &syntax == "haml" - syn cluster erubyRailsRegions contains=hamlRubyCodeIncluded,hamlRubyCode,hamlRubyHash,@hamlEmbeddedRuby,rubyInterpolation - else - syn cluster erubyRailsRegions contains=erubyOneLiner,erubyBlock,erubyExpression,rubyInterpolation - endif - exe "syn keyword erubyRailsHelperMethod ".s:sub(s:helpermethods(),'\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!' contained containedin=@erubyRailsRegions - syn keyword erubyRailsMethod debugger logger contained containedin=@erubyRailsRegions - syn keyword erubyRailsMethod params request response session headers cookies flash contained containedin=@erubyRailsRegions - syn match erubyRailsViewMethod '\.\@' contained containedin=@erubyRailsRegions - if t =~ '\' - syn keyword erubyRailsMethod local_assigns contained containedin=@erubyRailsRegions - endif - syn keyword erubyRailsRenderMethod render contained containedin=@erubyRailsRegions - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction contained ".s:javascript_functions - syn cluster htmlJavaScript add=javascriptRailsFunction - elseif &syntax == "yaml" - syn case match - " Modeled after syntax/eruby.vim - unlet! b:current_syntax - let g:main_syntax = 'eruby' - syn include @rubyTop syntax/ruby.vim - unlet g:main_syntax - syn cluster yamlRailsRegions contains=yamlRailsOneLiner,yamlRailsBlock,yamlRailsExpression - syn region yamlRailsOneLiner matchgroup=yamlRailsDelimiter start="^%%\@!" end="$" contains=@rubyRailsTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment keepend oneline - syn region yamlRailsBlock matchgroup=yamlRailsDelimiter start="<%%\@!" end="%>" contains=@rubyTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment - syn region yamlRailsExpression matchgroup=yamlRailsDelimiter start="<%=" end="%>" contains=@rubyTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment - syn region yamlRailsComment matchgroup=yamlRailsDelimiter start="<%#" end="%>" contains=rubyTodo,@Spell containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment keepend - syn match yamlRailsMethod '\.\@' contained containedin=@yamlRailsRegions - if classes != '' - exe "syn keyword yamlRailsUserClass ".classes." contained containedin=@yamlRailsRegions" - endif - let b:current_syntax = "yaml" - elseif &syntax == "html" - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction contained ".s:javascript_functions - syn cluster htmlJavaScript add=javascriptRailsFunction - elseif &syntax == "javascript" - " The syntax file included with Vim incorrectly sets syn case ignore. - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction ".s:javascript_functions - - endif - endif - call s:HiDefaults() -endfunction - -function! s:HiDefaults() - hi def link rubyRailsAPIMethod rubyRailsMethod - hi def link rubyRailsARAssociationMethod rubyRailsARMethod - hi def link rubyRailsARCallbackMethod rubyRailsARMethod - hi def link rubyRailsARClassMethod rubyRailsARMethod - hi def link rubyRailsARValidationMethod rubyRailsARMethod - hi def link rubyRailsARMethod rubyRailsMethod - hi def link rubyRailsRenderMethod rubyRailsMethod - hi def link rubyRailsHelperMethod rubyRailsMethod - hi def link rubyRailsViewMethod rubyRailsMethod - hi def link rubyRailsMigrationMethod rubyRailsMethod - hi def link rubyRailsControllerMethod rubyRailsMethod - hi def link rubyRailsFilterMethod rubyRailsMethod - hi def link rubyRailsTestControllerMethod rubyRailsTestMethod - hi def link rubyRailsTestMethod rubyRailsMethod - hi def link rubyRailsRakeMethod rubyRailsMethod - hi def link rubyRailsMethod railsMethod - hi def link rubyRailsInclude rubyInclude - hi def link rubyRailsUserClass railsUserClass - hi def link rubyRailsUserMethod railsUserMethod - hi def link erubyRailsHelperMethod erubyRailsMethod - hi def link erubyRailsViewMethod erubyRailsMethod - hi def link erubyRailsRenderMethod erubyRailsMethod - hi def link erubyRailsMethod railsMethod - hi def link erubyRailsUserMethod railsUserMethod - hi def link railsUserMethod railsMethod - hi def link erubyRailsUserClass railsUserClass - hi def link yamlRailsDelimiter Delimiter - hi def link yamlRailsMethod railsMethod - hi def link yamlRailsComment Comment - hi def link yamlRailsUserClass railsUserClass - hi def link yamlRailsUserMethod railsUserMethod - hi def link javascriptRailsFunction railsMethod - hi def link railsUserClass railsClass - hi def link railsMethod Function - hi def link railsClass Type - hi def link railsOrderSpecial railsStringSpecial - hi def link railsConditionsSpecial railsStringSpecial - hi def link railsStringSpecial Identifier -endfunction - -function! rails#log_syntax() - syn match railslogRender '^\s*\<\%(Processing\|Rendering\|Rendered\|Redirected\|Completed\)\>' - syn match railslogComment '^\s*# .*' - syn match railslogModel '^\s*\u\%(\w\|:\)* \%(Load\%( Including Associations\| IDs For Limited Eager Loading\)\=\|Columns\|Count\|Create\|Update\|Destroy\|Delete all\)\>' skipwhite nextgroup=railslogModelNum - syn match railslogModel '^\s*SQL\>' skipwhite nextgroup=railslogModelNum - syn region railslogModelNum start='(' end=')' contains=railslogNumber contained skipwhite nextgroup=railslogSQL - syn match railslogSQL '\u.*$' contained - " Destroy generates multiline SQL, ugh - syn match railslogSQL '^ \%(FROM\|WHERE\|ON\|AND\|OR\|ORDER\) .*$' - syn match railslogNumber '\<\d\+\>%' - syn match railslogNumber '[ (]\@<=\<\d\+\.\d\+\>' - syn region railslogString start='"' skip='\\"' end='"' oneline contained - syn region railslogHash start='{' end='}' oneline contains=railslogHash,railslogString - syn match railslogIP '\<\d\{1,3\}\%(\.\d\{1,3}\)\{3\}\>' - syn match railslogTimestamp '\<\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\>' - syn match railslogSessionID '\<\x\{32\}\>' - syn match railslogIdentifier '^\s*\%(Session ID\|Parameters\)\ze:' - syn match railslogSuccess '\<2\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogRedirect '\<3\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogError '\<[45]\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogError '^DEPRECATION WARNING\>' - syn keyword railslogHTTP OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT - syn region railslogStackTrace start=":\d\+:in `\w\+'$" end="^\s*$" keepend fold - hi def link railslogComment Comment - hi def link railslogRender Keyword - hi def link railslogModel Type - hi def link railslogSQL PreProc - hi def link railslogNumber Number - hi def link railslogString String - hi def link railslogSessionID Constant - hi def link railslogIdentifier Identifier - hi def link railslogRedirect railslogSuccess - hi def link railslogSuccess Special - hi def link railslogError Error - hi def link railslogHTTP Special -endfunction - -" }}}1 -" Statusline {{{1 - -function! s:addtostatus(letter,status) - let status = a:status - if status !~ 'rails' && g:rails_statusline - let status=substitute(status,'\C%'.tolower(a:letter),'%'.tolower(a:letter).'%{rails#statusline()}','') - if status !~ 'rails' - let status=substitute(status,'\C%'.toupper(a:letter),'%'.toupper(a:letter).'%{rails#STATUSLINE()}','') - endif - endif - return status -endfunction - -function! s:BufInitStatusline() - if g:rails_statusline - if &l:statusline == '' - let &l:statusline = &g:statusline - endif - if &l:statusline == '' - let &l:statusline='%<%f %h%m%r%=' - if &ruler - let &l:statusline .= '%-16( %l,%c-%v %)%P' - endif - endif - let &l:statusline = s:InjectIntoStatusline(&l:statusline) - endif -endfunction - -function! s:InitStatusline() - if g:rails_statusline - if &g:statusline == '' - let &g:statusline='%<%f %h%m%r%=' - if &ruler - let &g:statusline .= '%-16( %l,%c-%v %)%P' - endif - endif - let &g:statusline = s:InjectIntoStatusline(&g:statusline) - endif -endfunction - -function! s:InjectIntoStatusline(status) - let status = a:status - if status !~ 'rails' - let status = s:addtostatus('y',status) - let status = s:addtostatus('r',status) - let status = s:addtostatus('m',status) - let status = s:addtostatus('w',status) - let status = s:addtostatus('h',status) - if status !~ 'rails' - let status=substitute(status,'%=','%{rails#statusline()}%=','') - endif - if status !~ 'rails' && status != '' - let status .= '%{rails#statusline()}' - endif - endif - return status -endfunction - -function! rails#statusline(...) - if exists("b:rails_root") - let t = RailsFileType() - if t != "" && a:0 && a:1 - return "[Rails-".t."]" - else - return "[Rails]" - endif - else - return "" - endif -endfunction - -function! rails#STATUSLINE(...) - if exists("b:rails_root") - let t = RailsFileType() - if t != "" && a:0 && a:1 - return ",RAILS-".toupper(t) - else - return ",RAILS" - endif - else - return "" - endif -endfunction - -" }}}1 -" Mappings {{{1 - -function! s:BufMappings() - nnoremap RailsAlternate :A - nnoremap RailsRelated :R - nnoremap RailsFind :REfind - nnoremap RailsSplitFind :RSfind - nnoremap RailsVSplitFind :RVfind - nnoremap RailsTabFind :RTfind - if g:rails_mappings - if !hasmapto("RailsFind") - nmap gf RailsFind - endif - if !hasmapto("RailsSplitFind") - nmap f RailsSplitFind - endif - if !hasmapto("RailsTabFind") - nmap gf RailsTabFind - endif - if !hasmapto("RailsAlternate") - nmap [f RailsAlternate - endif - if !hasmapto("RailsRelated") - nmap ]f RailsRelated - endif - if exists("$CREAM") - imap RailsFind - imap RailsAlternate - imap RailsRelated - endif - endif - " SelectBuf you're a dirty hack - let v:errmsg = "" -endfunction - -" }}}1 -" Project {{{ - -function! s:Project(bang,arg) - let rr = rails#app().path() - exe "Project ".a:arg - let line = search('^[^ =]*="'.s:gsub(rr,'[\/]','[\\/]').'"') - let projname = s:gsub(fnamemodify(rr,':t'),'\=','-') " .'_on_rails' - if line && a:bang - let projname = matchstr(getline('.'),'^[^=]*') - " Most of this would be unnecessary if the project.vim author had just put - " the newlines AFTER each project rather than before. Ugh. - norm zR0"_d% - if line('.') > 2 - delete _ - endif - if line('.') != line('$') - .-2 - endif - let line = 0 - elseif !line - $ - endif - if !line - if line('.') > 1 - append - -. - endif - let line = line('.')+1 - call s:NewProject(projname,rr) - endif - normal! zMzo - if search("^ app=app {","W",line+10) - normal! zo - exe line - endif - normal! 0zt -endfunction - -function! s:NewProject(proj,rr) - let line = line('.')+1 - let template = s:NewProjectTemplate(a:proj,a:rr) - silent put =template - exe line - " Ugh. how else can I force detecting folds? - setlocal foldmethod=manual - norm! $% - silent exe "doautocmd User ".s:escarg(a:rr)."/Rproject" - let newline = line('.') - exe line - norm! $% - if line('.') != newline - call s:warn("Warning: Rproject autocommand failed to leave cursor at end of project") - endif - exe line - setlocal foldmethod=marker - setlocal nomodified - " FIXME: make undo stop here - if !exists("g:maplocalleader") - silent! normal \R - else " Needs to be tested - exe 'silent! normal '.g:maplocalleader.'R' - endif -endfunction - -function! s:NewProjectTemplate(proj,rr) - let str = a:proj.'="'.a:rr."\" CD=. filter=\"*\" {\n" - let str .= " app=app {\n" - for dir in ['apis','controllers','helpers','models','views'] - let str .= s:addprojectdir(a:rr,'app',dir) - endfor - let str .= " }\n" - let str .= " config=config {\n environments=environments {\n }\n }\n" - let str .= " db=db {\n" - let str .= s:addprojectdir(a:rr,'db','migrate') - let str .= " }\n" - let str .= " lib=lib filter=\"* */**/*.rb \" {\n tasks=tasks filter=\"**/*.rake\" {\n }\n }\n" - let str .= " public=public {\n images=images {\n }\n javascripts=javascripts {\n }\n stylesheets=stylesheets {\n }\n }\n" - if isdirectory(a:rr.'/spec') - let str .= " spec=spec {\n" - for dir in ['controllers','fixtures','helpers','models','views'] - let str .= s:addprojectdir(a:rr,'spec',dir) - endfor - let str .= " }\n" - endif - if isdirectory(a:rr.'/test') - let str .= " test=test {\n" - for dir in ['fixtures','functional','integration','mocks','unit'] - let str .= s:addprojectdir(a:rr,'test',dir) - endfor - let str .= " }\n" - end - let str .= "}\n" - return str -endfunction - -function! s:addprojectdir(rr,parentdir,dir) - if isdirectory(a:rr.'/'.a:parentdir.'/'.a:dir) - return ' '.a:dir.'='.a:dir." filter=\"**\" {\n }\n" - else - return '' - endif -endfunction - -" }}}1 -" Database {{{1 - -function! s:extractdbvar(str,arg) - return matchstr("\n".a:str."\n",'\n'.a:arg.'=\zs.\{-\}\ze\n') -endfunction - -function! s:app_dbext_settings(environment) dict - if self.cache.needs('dbext_settings') - call self.cache.set('dbext_settings',{}) - endif - let cache = self.cache.get('dbext_settings') - if !has_key(cache,a:environment) - let dict = {} - if self.has_file("config/database.yml") - let cmdb = 'require %{yaml}; File.open(%q{'.self.path().'/config/database.yml}) {|f| y = YAML::load(f); e = y[%{' - let cmde = '}]; i=0; e=y[e] while e.respond_to?(:to_str) && (i+=1)<16; e.each{|k,v|puts k.to_s+%{=}+v.to_s}}' - let out = self.lightweight_ruby_eval(cmdb.a:environment.cmde) - let adapter = s:extractdbvar(out,'adapter') - let adapter = get({'postgresql': 'pgsql', 'sqlite3': 'sqlite', 'sqlserver': 'sqlsrv', 'sybase': 'asa', 'oci': 'ora'},adapter,adapter) - let dict['type'] = toupper(adapter) - let dict['user'] = s:extractdbvar(out,'username') - let dict['passwd'] = s:extractdbvar(out,'password') - if dict['passwd'] == '' && adapter == 'mysql' - " Hack to override password from .my.cnf - let dict['extra'] = ' --password=' - else - let dict['extra'] = '' - endif - let dict['dbname'] = s:extractdbvar(out,'database') - if dict['dbname'] == '' - let dict['dbname'] = s:extractdbvar(out,'dbfile') - endif - if dict['dbname'] != '' && dict['dbname'] !~ '^:' && adapter =~? '^sqlite' - let dict['dbname'] = self.path(dict['dbname']) - endif - let dict['profile'] = '' - let dict['srvname'] = s:extractdbvar(out,'host') - let dict['host'] = s:extractdbvar(out,'host') - let dict['port'] = s:extractdbvar(out,'port') - let dict['dsnname'] = s:extractdbvar(out,'dsn') - if dict['host'] =~? '^\cDBI:' - if dict['host'] =~? '\c\' - let dict['integratedlogin'] = 1 - endif - let dict['host'] = matchstr(dict['host'],'\c\<\%(Server\|Data Source\)\s*=\s*\zs[^;]*') - endif - call filter(dict,'v:val != ""') - endif - let cache[a:environment] = dict - endif - return cache[a:environment] -endfunction - -function! s:BufDatabase(...) - if exists("s:lock_database") || !exists('g:loaded_dbext') || !exists('b:rails_root') - return - endif - let self = rails#app() - let s:lock_database = 1 - if (a:0 && a:1 > 1) - call self.cache.clear('dbext_settings') - endif - if (a:0 > 1 && a:2 != '') - let env = a:2 - else - let env = s:environment() - endif - if (!self.cache.has('dbext_settings') || !has_key(self.cache.get('dbext_settings'),env)) && (g:rails_dbext + (a:0 ? a:1 : 0)) <= 0 - unlet! s:lock_database - return - endif - let dict = self.dbext_settings(env) - for key in ['type', 'profile', 'bin', 'user', 'passwd', 'dbname', 'srvname', 'host', 'port', 'dsnname', 'extra', 'integratedlogin'] - let b:dbext_{key} = get(dict,key,'') - endfor - if b:dbext_type == 'PGSQL' - let $PGPASSWORD = b:dbext_passwd - elseif exists('$PGPASSWORD') - let $PGPASSWORD = '' - endif - unlet! s:lock_database -endfunction - -call s:add_methods('app', ['dbext_settings']) - -" }}}1 -" Abbreviations {{{1 - -function! s:selectiveexpand(pat,good,default,...) - if a:0 > 0 - let nd = a:1 - else - let nd = "" - endif - let c = nr2char(getchar(0)) - let good = a:good - if c == "" " ^] - return s:sub(good.(a:0 ? " ".a:1 : ''),'\s+$','') - elseif c == "\t" - return good.(a:0 ? " ".a:1 : '') - elseif c =~ a:pat - return good.c.(a:0 ? a:1 : '') - else - return a:default.c - endif -endfunction - -function! s:TheCWord() - let l = s:linepeak() - if l =~ '\<\%(find\|first\|last\|all\|paginate\)\>' - return s:selectiveexpand('..',':conditions => ',':c') - elseif l =~ '\\s*' - return s:selectiveexpand('..',':collection => ',':c') - elseif l =~ '\<\%(url_for\|link_to\|form_tag\)\>' || l =~ ':url\s*=>\s*{\s*' - return s:selectiveexpand('..',':controller => ',':c') - else - return s:selectiveexpand('..',':conditions => ',':c') - endif -endfunction - -function! s:AddSelectiveExpand(abbr,pat,expn,...) - let expn = s:gsub(s:gsub(a:expn ,'[\"|]','\\&'),'\<','\\') - let expn2 = s:gsub(s:gsub(a:0 ? a:1 : '','[\"|]','\\&'),'\<','\\') - if a:0 - exe "inoreabbrev ".a:abbr." =selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).",\"".expn2."\")" - else - exe "inoreabbrev ".a:abbr." =selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).")" - endif -endfunction - -function! s:AddTabExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'..',a:expn) -endfunction - -function! s:AddBracketExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'[[.]',a:expn) -endfunction - -function! s:AddColonExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'[:.]',a:expn) -endfunction - -function! s:AddParenExpand(abbr,expn,...) - if a:0 - call s:AddSelectiveExpand(a:abbr,'(',a:expn,a:1) - else - call s:AddSelectiveExpand(a:abbr,'(',a:expn,'') - endif -endfunction - -function! s:BufAbbreviations() - command! -buffer -bar -nargs=* -bang Rabbrev :call s:Abbrev(0,) - " Some of these were cherry picked from the TextMate snippets - if g:rails_abbreviations - let t = RailsFileType() - " Limit to the right filetypes. But error on the liberal side - if t =~ '^\(controller\|view\|helper\|test-functional\|test-integration\)\>' - Rabbrev pa[ params - Rabbrev rq[ request - Rabbrev rs[ response - Rabbrev se[ session - Rabbrev hd[ headers - Rabbrev co[ cookies - Rabbrev fl[ flash - Rabbrev rr( render - Rabbrev ra( render :action\ =>\ - Rabbrev rc( render :controller\ =>\ - Rabbrev rf( render :file\ =>\ - Rabbrev ri( render :inline\ =>\ - Rabbrev rj( render :json\ =>\ - Rabbrev rl( render :layout\ =>\ - Rabbrev rp( render :partial\ =>\ - Rabbrev rt( render :text\ =>\ - Rabbrev rx( render :xml\ =>\ - endif - if t =~ '^\%(view\|helper\)\>' - Rabbrev dotiw distance_of_time_in_words - Rabbrev taiw time_ago_in_words - endif - if t =~ '^controller\>' - Rabbrev re( redirect_to - Rabbrev rea( redirect_to :action\ =>\ - Rabbrev rec( redirect_to :controller\ =>\ - Rabbrev rst( respond_to - endif - if t =~ '^model-arb\>' || t =~ '^model$' - Rabbrev bt( belongs_to - Rabbrev ho( has_one - Rabbrev hm( has_many - Rabbrev habtm( has_and_belongs_to_many - Rabbrev co( composed_of - Rabbrev va( validates_associated - Rabbrev vb( validates_acceptance_of - Rabbrev vc( validates_confirmation_of - Rabbrev ve( validates_exclusion_of - Rabbrev vf( validates_format_of - Rabbrev vi( validates_inclusion_of - Rabbrev vl( validates_length_of - Rabbrev vn( validates_numericality_of - Rabbrev vp( validates_presence_of - Rabbrev vu( validates_uniqueness_of - endif - if t =~ '^\%(db-\)\=\%(migration\|schema\)\>' - Rabbrev mac( add_column - Rabbrev mrnc( rename_column - Rabbrev mrc( remove_column - Rabbrev mct( create_table - Rabbrev mcht( change_table - Rabbrev mrnt( rename_table - Rabbrev mdt( drop_table - Rabbrev mcc( t.column - endif - if t =~ '^test\>' - Rabbrev ase( assert_equal - Rabbrev asko( assert_kind_of - Rabbrev asnn( assert_not_nil - Rabbrev asr( assert_raise - Rabbrev asre( assert_response - Rabbrev art( assert_redirected_to - endif - Rabbrev :a :action\ =>\ - " hax - Rabbrev :c :co________\ =>\ - inoreabbrev :c =TheCWord() - Rabbrev :i :id\ =>\ - Rabbrev :o :object\ =>\ - Rabbrev :p :partial\ =>\ - Rabbrev logd( logger.debug - Rabbrev logi( logger.info - Rabbrev logw( logger.warn - Rabbrev loge( logger.error - Rabbrev logf( logger.fatal - Rabbrev fi( find - Rabbrev AR:: ActiveRecord - Rabbrev AV:: ActionView - Rabbrev AC:: ActionController - Rabbrev AS:: ActiveSupport - Rabbrev AM:: ActionMailer - Rabbrev AE:: ActiveResource - Rabbrev AWS:: ActionWebService - endif -endfunction - -function! s:Abbrev(bang,...) abort - if !exists("b:rails_abbreviations") - let b:rails_abbreviations = {} - endif - if a:0 > 3 || (a:bang && (a:0 != 1)) - return s:error("Rabbrev: invalid arguments") - endif - if a:0 == 0 - for key in sort(keys(b:rails_abbreviations)) - echo key . join(b:rails_abbreviations[key],"\t") - endfor - return - endif - let lhs = a:1 - let root = s:sub(lhs,'%(::|\(|\[)$','') - if a:bang - if has_key(b:rails_abbreviations,root) - call remove(b:rails_abbreviations,root) - endif - exe "iunabbrev ".root - return - endif - if a:0 > 3 || a:0 < 2 - return s:error("Rabbrev: invalid arguments") - endif - let rhs = a:2 - if has_key(b:rails_abbreviations,root) - call remove(b:rails_abbreviations,root) - endif - if lhs =~ '($' - let b:rails_abbreviations[root] = ["(", rhs . (a:0 > 2 ? "\t".a:3 : "")] - if a:0 > 2 - call s:AddParenExpand(root,rhs,a:3) - else - call s:AddParenExpand(root,rhs) - endif - return - endif - if a:0 > 2 - return s:error("Rabbrev: invalid arguments") - endif - if lhs =~ ':$' - call s:AddColonExpand(root,rhs) - elseif lhs =~ '\[$' - call s:AddBracketExpand(root,rhs) - elseif lhs =~ '\w$' - call s:AddTabExpand(lhs,rhs) - else - return s:error("Rabbrev: unimplemented") - endif - let b:rails_abbreviations[root] = [matchstr(lhs,'\W*$'),rhs] -endfunction - -" }}}1 -" Settings {{{1 - -function! s:Set(bang,...) - let c = 1 - let defscope = '' - for arg in a:000 - if arg =~? '^<[abgl]\=>$' - let defscope = (matchstr(arg,'<\zs.*\ze>')) - elseif arg !~ '=' - if defscope != '' && arg !~ '^\w:' - let arg = defscope.':'.opt - endif - let val = s:getopt(arg) - if val == '' && !has_key(s:opts(),arg) - call s:error("No such rails.vim option: ".arg) - else - echo arg."=".val - endif - else - let opt = matchstr(arg,'[^=]*') - let val = s:sub(arg,'^[^=]*\=','') - if defscope != '' && opt !~ '^\w:' - let opt = defscope.':'.opt - endif - call s:setopt(opt,val) - endif - endfor -endfunction - -function! s:getopt(opt,...) - let app = rails#app() - let opt = a:opt - if a:0 - let scope = a:1 - elseif opt =~ '^[abgl]:' - let scope = tolower(matchstr(opt,'^\w')) - let opt = s:sub(opt,'^\w:','') - else - let scope = 'abgl' - endif - let lnum = a:0 > 1 ? a:2 : line('.') - if scope =~ 'l' && &filetype != 'ruby' - let scope = s:sub(scope,'l','b') - endif - if scope =~ 'l' - call s:LocalModelines(lnum) - endif - let var = s:sname().'_'.opt - let lastmethod = s:lastmethod(lnum) - if lastmethod == '' | let lastmethod = ' ' | endif - " Get buffer option - if scope =~ 'l' && exists('b:_'.var) && has_key(b:_{var},lastmethod) - return b:_{var}[lastmethod] - elseif exists('b:'.var) && (scope =~ 'b' || (scope =~ 'l' && lastmethod == ' ')) - return b:{var} - elseif scope =~ 'a' && has_key(app,'options') && has_key(app.options,opt) - return app.options[opt] - elseif scope =~ 'g' && exists("g:".s:sname()."_".opt) - return g:{var} - else - return "" - endif -endfunction - -function! s:setopt(opt,val) - let app = rails#app() - if a:opt =~? '[abgl]:' - let scope = matchstr(a:opt,'^\w') - let opt = s:sub(a:opt,'^\w:','') - else - let scope = '' - let opt = a:opt - endif - let defscope = get(s:opts(),opt,'a') - if scope == '' - let scope = defscope - endif - if &filetype != 'ruby' && (scope ==# 'B' || scope ==# 'l') - let scope = 'b' - endif - let var = s:sname().'_'.opt - if opt =~ '\W' - return s:error("Invalid option ".a:opt) - elseif scope ==# 'B' && defscope == 'l' - if !exists('b:_'.var) | let b:_{var} = {} | endif - let b:_{var}[' '] = a:val - elseif scope =~? 'b' - let b:{var} = a:val - elseif scope =~? 'a' - if !has_key(app,'options') | let app.options = {} | endif - let app.options[opt] = a:val - elseif scope =~? 'g' - let g:{var} = a:val - elseif scope =~? 'l' - if !exists('b:_'.var) | let b:_{var} = {} | endif - let lastmethod = s:lastmethod(lnum) - let b:_{var}[lastmethod == '' ? ' ' : lastmethod] = a:val - else - return s:error("Invalid scope for ".a:opt) - endif -endfunction - -function! s:opts() - return {'alternate': 'b', 'controller': 'b', 'gnu_screen': 'a', 'model': 'b', 'preview': 'l', 'task': 'b', 'related': 'l', 'root_url': 'a'} -endfunction - -function! s:Complete_set(A,L,P) - if a:A =~ '=' - let opt = matchstr(a:A,'[^=]*') - return [opt."=".s:getopt(opt)] - else - let extra = matchstr(a:A,'^[abgl]:') - return filter(sort(map(keys(s:opts()),'extra.v:val')),'s:startswith(v:val,a:A)') - endif - return [] -endfunction - -function! s:BufModelines() - if !g:rails_modelines - return - endif - let lines = getline("$")."\n".getline(line("$")-1)."\n".getline(1)."\n".getline(2)."\n".getline(3)."\n" - let pat = '\s\+\zs.\{-\}\ze\%(\n\|\s\s\|#{\@!\|%>\|-->\|$\)' - let cnt = 1 - let mat = matchstr(lines,'\C\ ".mat - endif - let mat = matchstr(lines,'\C\ ".mat - endif - let mat = matchstr(lines,'\C\ 0 - if !exists("g:RAILS_HISTORY") - let g:RAILS_HISTORY = "" - endif - let path = a:path - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,path) - if has("win32") - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,s:gsub(path,'\\','/')) - endif - let path = fnamemodify(path,':p:~:h') - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,path) - if has("win32") - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,s:gsub(path,'\\','/')) - endif - let g:RAILS_HISTORY = path."\n".g:RAILS_HISTORY - let g:RAILS_HISTORY = s:sub(g:RAILS_HISTORY,'%(.{-}\n){,'.g:rails_history_size.'}\zs.*','') - endif - call app.source_callback("config/syntax.vim") - if &ft == "mason" - setlocal filetype=eruby - elseif &ft =~ '^\%(conf\|ruby\)\=$' && expand("%:e") =~ '^\%(rjs\|rxml\|builder\|rake\|mab\)$' - setlocal filetype=ruby - elseif &ft =~ '^\%(conf\|ruby\)\=$' && expand("%:t") =~ '^\%(Rake\|Cap\)file$' - setlocal filetype=ruby - elseif &ft =~ '^\%(liquid\)\=$' && expand("%:e") == "liquid" - setlocal filetype=liquid - elseif &ft =~ '^\%(haml\|x\=html\)\=$' && expand("%:e") == "haml" - setlocal filetype=haml - elseif &ft =~ '^\%(sass\|conf\)\=$' && expand("%:e") == "sass" - setlocal filetype=sass - elseif &ft =~ '^\%(dryml\)\=$' && expand("%:e") == "dryml" - setlocal filetype=dryml - elseif (&ft == "" || v:version < 701) && expand("%:e") =~ '^\%(rhtml\|erb\)$' - setlocal filetype=eruby - elseif (&ft == "" || v:version < 700) && expand("%:e") == 'yml' - setlocal filetype=yaml - elseif firsttime - " Activate custom syntax - let &syntax = &syntax - endif - if firsttime - call s:BufInitStatusline() - endif - if expand("%:e") == "log" - setlocal modifiable filetype=railslog - silent! %s/\%(\e\[[0-9;]*m\|\r$\)//g - setlocal readonly nomodifiable noswapfile autoread foldmethod=syntax - nnoremap R :checktime - nnoremap G :checktime$ - nnoremap q :bwipe - $ - endif - call s:BufSettings() - call s:BufCommands() - call s:BufAbbreviations() - if exists("g:loaded_dbext") && g:loaded_dbext < 800 - call s:BufDatabase() - endif - " snippetsEmu.vim - if exists('g:loaded_snippet') - silent! runtime! ftplugin/rails_snippets.vim - " filetype snippets need to come last for higher priority - exe "silent! runtime! ftplugin/".&filetype."_snippets.vim" - endif - let t = RailsFileType() - let t = "-".t - let f = '/'.RailsFilePath() - if f =~ '[ !#$%\,]' - let f = '' - endif - runtime! macros/rails.vim - silent doautocmd User Rails - if t != '-' - exe "silent doautocmd User Rails".s:gsub(t,'-','.') - endif - if f != '' - exe "silent doautocmd User Rails".f - endif - call app.source_callback("config/rails.vim") - call s:BufModelines() - call s:BufMappings() - return b:rails_root -endfunction - -function! s:SetBasePath() - let self = rails#buffer() - if self.app().path() =~ '://' - return - endif - let transformed_path = s:pathsplit(s:pathjoin([self.app().path()]))[0] - let old_path = s:pathsplit(s:sub(self.getvar('&path'),'^\.,=','')) - call filter(old_path,'!s:startswith(v:val,transformed_path)') - - let path = ['app', 'app/models', 'app/controllers', 'app/helpers', 'config', 'lib', 'app/views'] - if self.controller_name() != '' - let path += ['app/views/'.self.controller_name(), 'public'] - endif - if self.app().has('test') - let path += ['test', 'test/unit', 'test/functional', 'test/integration'] - endif - if self.app().has('spec') - let path += ['spec', 'spec/models', 'spec/controllers', 'spec/helpers', 'spec/views', 'spec/lib', 'spec/integration'] - endif - let path += ['app/*', 'vendor', 'vendor/plugins/*/lib', 'vendor/plugins/*/test', 'vendor/rails/*/lib', 'vendor/rails/*/test'] - call map(path,'self.app().path(v:val)') - call self.setvar('&path',s:pathjoin('.',[self.app().path()],path,old_path)) -endfunction - -function! s:BufSettings() - if !exists('b:rails_root') - return '' - endif - let self = rails#buffer() - call s:SetBasePath() - let rp = s:gsub(self.app().path(),'[ ,]','\\&') - if stridx(&tags,rp) == -1 - let &l:tags = rp . "/tmp/tags," . &tags . "," . rp . "/tags" - endif - if has("gui_win32") || has("gui_running") - let code = '*.rb;*.rake;Rakefile' - let templates = '*.'.s:gsub(s:view_types,',',';*.') - let fixtures = '*.yml;*.csv' - let statics = '*.html;*.css;*.js;*.xml;*.xsd;*.sql;.htaccess;README;README_FOR_APP' - let b:browsefilter = "" - \."All Rails Files\t".code.';'.templates.';'.fixtures.';'.statics."\n" - \."Source Code (*.rb, *.rake)\t".code."\n" - \."Templates (*.rhtml, *.rxml, *.rjs)\t".templates."\n" - \."Fixtures (*.yml, *.csv)\t".fixtures."\n" - \."Static Files (*.html, *.css, *.js)\t".statics."\n" - \."All Files (*.*)\t*.*\n" - endif - call self.setvar('&includeexpr','RailsIncludeexpr()') - call self.setvar('&suffixesadd', ".rb,.".s:gsub(s:view_types,',',',.').",.css,.js,.yml,.csv,.rake,.sql,.html,.xml") - let ft = self.getvar('&filetype') - if ft =~ '^\%(e\=ruby\|[yh]aml\|javascript\|css\|sass\)$' - call self.setvar('&shiftwidth',2) - call self.setvar('&softtabstop',2) - call self.setvar('&expandtab',1) - if exists('+completefunc') && self.getvar('&completefunc') == '' - call self.setvar('&completefunc','syntaxcomplete#Complete') - endif - endif - if ft == 'ruby' - call self.setvar('&suffixesadd',".rb,.".s:gsub(s:view_types,',',',.').",.yml,.csv,.rake,s.rb") - call self.setvar('&define',self.define_pattern()) - " This really belongs in after/ftplugin/ruby.vim but we'll be nice - if exists('g:loaded_surround') && self.getvar('surround_101') == '' - call self.setvar('surround_5', "\r\nend") - call self.setvar('surround_69', "\1expr: \1\rend") - call self.setvar('surround_101', "\r\nend") - endif - elseif ft == 'yaml' || fnamemodify(self.name(),':e') == 'yml' - call self.setvar('&define',self.define_pattern()) - call self.setvar('&suffixesadd',".yml,.csv,.rb,.".s:gsub(s:view_types,',',',.').",.rake,s.rb") - elseif ft == 'eruby' - call self.setvar('&suffixesadd',".".s:gsub(s:view_types,',',',.').",.rb,.css,.js,.html,.yml,.csv") - if exists("g:loaded_allml") - " allml is available on vim.org. - call self.setvar('allml_stylesheet_link_tag', "<%= stylesheet_link_tag '\r' %>") - call self.setvar('allml_javascript_include_tag', "<%= javascript_include_tag '\r' %>") - call self.setvar('allml_doctype_index', 10) - endif - endif - if ft == 'eruby' || ft == 'yaml' - " surround.vim - if exists("g:loaded_surround") - " The idea behind the || part here is that one can normally define the - " surrounding to omit the hyphen (since standard ERuby does not use it) - " but have it added in Rails ERuby files. Unfortunately, this makes it - " difficult if you really don't want a hyphen in Rails ERuby files. If - " this is your desire, you will need to accomplish it via a rails.vim - " autocommand. - if self.getvar('surround_45') == '' || self.getvar('surround_45') == "<% \r %>" " - - call self.setvar('surround_45', "<% \r -%>") - endif - if self.getvar('surround_61') == '' " = - call self.setvar('surround_61', "<%= \r %>") - endif - if self.getvar("surround_35") == '' " # - call self.setvar('surround_35', "<%# \r %>") - endif - if self.getvar('surround_101') == '' || self.getvar('surround_101')== "<% \r %>\n<% end %>" "e - call self.setvar('surround_5', "<% \r -%>\n<% end -%>") - call self.setvar('surround_69', "<% \1expr: \1 -%>\r<% end -%>") - call self.setvar('surround_101', "<% \r -%>\n<% end -%>") - endif - endif - endif -endfunction - -" }}}1 -" Autocommands {{{1 - -augroup railsPluginAuto - autocmd! - autocmd User BufEnterRails call s:RefreshBuffer() - autocmd User BufEnterRails call s:resetomnicomplete() - autocmd User BufEnterRails call s:BufDatabase(-1) - autocmd User dbextPreConnection call s:BufDatabase(1) - autocmd BufWritePost */config/database.yml call rails#cache_clear("dbext_settings") - autocmd BufWritePost */test/test_helper.rb call rails#cache_clear("user_assertions") - autocmd BufWritePost */config/routes.rb call rails#cache_clear("named_routes") - autocmd BufWritePost */config/environment.rb call rails#cache_clear("default_locale") - autocmd BufWritePost */config/environments/*.rb call rails#cache_clear("environments") - autocmd BufWritePost */tasks/**.rake call rails#cache_clear("rake_tasks") - autocmd BufWritePost */generators/** call rails#cache_clear("generators") - autocmd FileType * if exists("b:rails_root") | call s:BufSettings() | endif - autocmd Syntax ruby,eruby,yaml,haml,javascript,railslog if exists("b:rails_root") | call s:BufSyntax() | endif - autocmd QuickFixCmdPre make* call s:push_chdir() - autocmd QuickFixCmdPost make* call s:pop_command() -augroup END - -" }}}1 -" Initialization {{{1 - -map xx xx -let s:sid = s:sub(maparg("xx"),'xx$','') -unmap xx -let s:file = expand(':p') - -if !exists('s:apps') - let s:apps = {} -endif - -" }}}1 - -let &cpo = s:cpo_save - -" vim:set sw=2 sts=2: diff --git a/.vim/autoload/tabular.vim b/.vim/autoload/tabular.vim deleted file mode 100644 index f12ea34..0000000 --- a/.vim/autoload/tabular.vim +++ /dev/null @@ -1,327 +0,0 @@ -" Tabular: Align columnar data using regex-designated column boundaries -" Maintainer: Matthew Wozniski (mjw@drexel.edu) -" Date: Thu, 11 Oct 2007 00:35:34 -0400 -" Version: 0.1 - -" Stupid vimscript crap {{{1 -let s:savecpo = &cpo -set cpo&vim - -" Private Functions {{{1 - -" Return the number of bytes in a string after expanding tabs to spaces. {{{2 -" This expansion is done based on the current value of 'tabstop' -function! s:Strlen(string) - let rv = 0 - let i = 0 - - for char in split(a:string, '\zs') - if char == "\t" - let rv += &ts - i - let i = 0 - else - let rv += 1 - let i = (i + 1) % &ts - endif - endfor - - return rv -endfunction - -" Align a string within a field {{{2 -" These functions do not trim leading and trailing spaces. - -" Right align 'string' in a field of size 'fieldwidth' -function! s:Right(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - return matchstr(a:string, '^\s*') . repeat(" ", spaces) . substitute(a:string, '^\s*', '', '') -endfunction - -" Left align 'string' in a field of size 'fieldwidth' -function! s:Left(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - return a:string . repeat(" ", spaces) -endfunction - -" Center align 'string' in a field of size 'fieldwidth' -function! s:Center(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - let right = spaces / 2 - let left = right + (right * 2 != spaces) - return repeat(" ", left) . a:string . repeat(" ", right) -endfunction - -" Remove spaces around a string {{{2 - -" Remove all trailing spaces from a string. -function! s:StripTrailingSpaces(string) - return matchstr(a:string, '^.\{-}\ze\s*$') -endfunction - -" Remove all leading spaces from a string. -function! s:StripLeadingSpaces(string) - return matchstr(a:string, '^\s*\zs.*$') -endfunction - -" Split a string into fields and delimiters {{{2 -" Like split(), but include the delimiters as elements -" All odd numbered elements are delimiters -" All even numbered elements are non-delimiters (including zero) -function! s:SplitDelim(string, delim) - let rv = [] - let beg = 0 - - let len = len(a:string) - let searchoff = 0 - - while 1 - let mid = match(a:string, a:delim, beg + searchoff, 1) - if mid == -1 || mid == len - break - endif - - let matchstr = matchstr(a:string, a:delim, beg + searchoff, 1) - let length = strlen(matchstr) - - if length == 0 && beg == mid - " Zero-length match for a zero-length delimiter - advance past it - let searchoff += 1 - continue - endif - - if beg == mid - let rv += [ "" ] - else - let rv += [ a:string[beg : mid-1] ] - endif - - let rv += [ matchstr ] - - let beg = mid + length - let searchoff = 0 - endwhile - - let rv += [ strpart(a:string, beg) ] - - return rv -endfunction - -" Replace lines from `start' to `start + len - 1' with the given strings. {{{2 -" If more lines are needed to show all strings, they will be added. -" If there are too few strings to fill all lines, lines will be removed. -function! s:SetLines(start, len, strings) - if a:start > line('$') + 1 || a:start < 1 - throw "Invalid start line!" - endif - - if len(a:strings) > a:len - let fensave = &fen - let view = winsaveview() - call append(a:start + a:len - 1, repeat([''], len(a:strings) - a:len)) - call winrestview(view) - let &fen = fensave - elseif len(a:strings) < a:len - let fensave = &fen - let view = winsaveview() - sil exe (a:start + len(a:strings)) . ',' . (a:start + a:len - 1) . 'd_' - call winrestview(view) - let &fen = fensave - endif - - call setline(a:start, a:strings) -endfunction - -" Runs the given commandstring argument as an expression. {{{2 -" The commandstring expression is expected to reference the a:lines argument. -" If the commandstring expression returns a list the items of that list will -" replace the items in a:lines, otherwise the expression is assumed to have -" modified a:lines itself. -function! s:FilterString(lines, commandstring) - exe 'let rv = ' . a:commandstring - - if type(rv) == type(a:lines) && rv isnot a:lines - call filter(a:lines, 0) - call extend(a:lines, rv) - endif -endfunction - -" Public API {{{1 - -if !exists("g:tabular_default_format") - let g:tabular_default_format = "l1" -endif - -let s:formatelempat = '\%([lrc]\d\+\)' - -function! tabular#ElementFormatPattern() - return s:formatelempat -endfunction - -" Given a list of strings and a delimiter, split each string on every -" occurrence of the delimiter pattern, format each element according to either -" the provided format (optional) or the default format, and join them back -" together with enough space padding to guarantee that the nth delimiter of -" each string is aligned. -function! tabular#TabularizeStrings(strings, delim, ...) - if a:0 > 1 - echoerr "TabularizeStrings accepts only 2 or 3 arguments (got ".(a:0+2).")" - return 1 - endif - - let formatstr = (a:0 ? a:1 : g:tabular_default_format) - - if formatstr !~? s:formatelempat . '\+' - echoerr "Tabular: Invalid format \"" . formatstr . "\" specified!" - return 1 - endif - - let format = split(formatstr, s:formatelempat . '\zs') - - let lines = map(a:strings, 's:SplitDelim(v:val, a:delim)') - - " Strip spaces - " - Only from non-delimiters; spaces in delimiters must have been matched - " intentionally - " - Don't strip leading spaces from the first element; we like indenting. - for line in lines - if line[0] !~ '^\s*$' - let line[0] = s:StripTrailingSpaces(line[0]) - endif - if len(line) >= 3 - for i in range(2, len(line)-1, 2) - let line[i] = s:StripLeadingSpaces(s:StripTrailingSpaces(line[i])) - endfor - endif - endfor - - " Find the max length of each field - let maxes = [] - for line in lines - for i in range(len(line)) - if i == len(maxes) - let maxes += [ s:Strlen(line[i]) ] - else - let maxes[i] = max( [ maxes[i], s:Strlen(line[i]) ] ) - endif - endfor - endfor - - let lead_blank = empty(filter(copy(lines), 'v:val[0] =~ "\\S"')) - - " Concatenate the fields, according to the format pattern. - for idx in range(len(lines)) - let line = lines[idx] - for i in range(len(line)) - let how = format[i % len(format)][0] - let pad = format[i % len(format)][1:-1] - - if how =~? 'l' - let field = s:Left(line[i], maxes[i]) - elseif how =~? 'r' - let field = s:Right(line[i], maxes[i]) - elseif how =~? 'c' - let field = s:Center(line[i], maxes[i]) - endif - - let line[i] = field . (lead_blank && i == 0 ? '' : repeat(" ", pad)) - endfor - - let lines[idx] = s:StripTrailingSpaces(join(line, '')) - endfor -endfunction - -" Apply 0 or more filters, in sequence, to selected text in the buffer {{{2 -" The lines to be filtered are determined as follows: -" If the function is called with a range containing multiple lines, then -" those lines will be used as the range. -" If the function is called with no range or with a range of 1 line, then -" if "includepat" is not specified, -" that 1 line will be filtered, -" if "includepat" is specified and that line does not match it, -" no lines will be filtered -" if "includepat" is specified and that line does match it, -" all contiguous lines above and below the specified line matching the -" pattern will be filtered. -" -" The remaining arguments must each be a filter to apply to the text. -" Each filter must either be a String evaluating to a function to be called. -function! tabular#PipeRange(includepat, ...) range - let top = a:firstline - let bot = a:lastline - - if a:includepat != '' && top == bot - if top < 0 || top > line('$') || getline(top) !~ a:includepat - return - endif - while top > 1 && getline(top-1) =~ a:includepat - let top -= 1 - endwhile - while bot < line('$') && getline(bot+1) =~ a:includepat - let bot += 1 - endwhile - endif - - let lines = map(range(top, bot), 'getline(v:val)') - - for filter in a:000 - if type(filter) != type("") - echoerr "PipeRange: Bad filter: " . string(filter) - endif - - call s:FilterString(lines, filter) - - unlet filter - endfor - - call s:SetLines(top, bot - top + 1, lines) -endfunction - -function! s:SplitDelimTest(string, delim, expected) - let result = s:SplitDelim(a:string, a:delim) - - if result !=# a:expected - echomsg 'Test failed!' - echomsg ' string=' . string(a:string) . ' delim=' . string(a:delim) - echomsg ' Returned=' . string(result) - echomsg ' Expected=' . string(a:expected) - endif -endfunction - -function! tabular#SplitDelimUnitTest() - let assignment = '[|&+*/%<>=!~-]\@!=]=\|=\~\)\@![|&+*/%<>=!~-]*=' - let two_spaces = ' ' - let ternary_operator = '^.\{-}\zs?\|:' - let cpp_io = '<<\|>>' - let pascal_assign = ':=' - let trailing_c_comments = '\/\*\|\*\/\|\/\/' - - call s:SplitDelimTest('a+=b', assignment, ['a', '+=', 'b']) - call s:SplitDelimTest('a-=b', assignment, ['a', '-=', 'b']) - call s:SplitDelimTest('a!=b', assignment, ['a!=b']) - call s:SplitDelimTest('a==b', assignment, ['a==b']) - call s:SplitDelimTest('a&=b', assignment, ['a', '&=', 'b']) - call s:SplitDelimTest('a|=b', assignment, ['a', '|=', 'b']) - call s:SplitDelimTest('a=b=c', assignment, ['a', '=', 'b', '=', 'c']) - - call s:SplitDelimTest('a b c', two_spaces, ['a', ' ', 'b', ' ', 'c']) - call s:SplitDelimTest('a b c', two_spaces, ['a b', ' ', ' c']) - call s:SplitDelimTest('ab c', two_spaces, ['ab', ' ', '', ' ', 'c']) - - call s:SplitDelimTest('a?b:c', ternary_operator, ['a', '?', 'b', ':', 'c']) - - call s:SplitDelimTest('a<