diff options
| author | Ben Beltran <ben@freshout.us> | 2013-06-05 10:50:57 -0500 |
|---|---|---|
| committer | Ben Beltran <ben@freshout.us> | 2013-06-05 10:50:57 -0500 |
| commit | fe337504f2fb3ded76326b1e3d4d02787a27d853 (patch) | |
| tree | b84891d78de37ae078ea9850a541799b5bca8085 /vim | |
| parent | e23d7a9f7363bdc69e95a1df31e093db15459fcf (diff) | |
Aand that's all the plugins.
Diffstat (limited to 'vim')
107 files changed, 0 insertions, 31567 deletions
diff --git a/vim/after/plugin/snipMate.vim b/vim/after/plugin/snipMate.vim deleted file mode 100644 index bdbe199..0000000 --- a/vim/after/plugin/snipMate.vim +++ /dev/null @@ -1,40 +0,0 @@ -" These are the mappings for snipMate.vim. Putting it here ensures that it -" will be mapped after other plugins such as supertab.vim. -if !exists('loaded_snips') || exists('s:did_snips_mappings') - finish -endif -let s:did_snips_mappings = 1 - -" This is put here in the 'after' directory in order for snipMate to override -" other plugin mappings (e.g., supertab). -" -" You can safely adjust these mappings to your preferences (as explained in -" :help snipMate-remap). -ino <silent> <tab> <c-r>=TriggerSnippet()<cr> -snor <silent> <tab> <esc>i<right><c-r>=TriggerSnippet()<cr> -ino <silent> <s-tab> <c-r>=BackwardsSnippet()<cr> -snor <silent> <s-tab> <esc>i<right><c-r>=BackwardsSnippet()<cr> -ino <silent> <c-r><tab> <c-r>=ShowAvailableSnips()<cr> - -" The default mappings for these are annoying & sometimes break snipMate. -" You can change them back if you want, I've put them here for convenience. -snor <bs> b<bs> -snor <right> <esc>a -snor <left> <esc>bi -snor ' b<bs>' -snor ` b<bs>` -snor % b<bs>% -snor U b<bs>U -snor ^ b<bs>^ -snor \ b<bs>\ -snor <c-x> b<bs><c-x> - -" By default load snippets in snippets_dir -if empty(snippets_dir) - finish -endif - -call GetSnippets(snippets_dir, '_') " Get global snippets - -au FileType * if &ft != 'help' | call GetSnippets(snippets_dir, &ft) | endif -" vim:noet:sw=4:ts=4:ft=vim diff --git a/vim/autoload/conque_term.vim b/vim/autoload/conque_term.vim deleted file mode 100644 index 2780c7d..0000000 --- a/vim/autoload/conque_term.vim +++ /dev/null @@ -1,1590 +0,0 @@ -" FILE: plugin/conque_term.vim {{{ -" -" AUTHOR: Nico Raffo <nicoraffo@gmail.com> -" MODIFIED: 2010-05-27 -" VERSION: 1.1, for Vim 7.0 -" LICENSE: -" Conque - pty interaction in Vim -" Copyright (C) 2009-2010 Nico Raffo -" -" MIT License -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to deal -" in the Software without restriction, including without limitation the rights -" to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -" copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -" THE SOFTWARE. -" }}} - - -" ********************************************************************************************************** -" **** VIM FUNCTIONS *************************************************************************************** -" ********************************************************************************************************** - -" launch conque -function! conque_term#open(...) "{{{ - let command = get(a:000, 0, '') - let hooks = get(a:000, 1, []) - - " bare minimum validation - if has('python') != 1 - echohl WarningMsg | echomsg "Conque requires the Python interface to be installed" | echohl None - return 0 - endif - if empty(command) - echohl WarningMsg | echomsg "No command found" | echohl None - return 0 - else - let l:cargs = split(command, '\s') - if !executable(l:cargs[0]) - echohl WarningMsg | echomsg "Not an executable: " . l:cargs[0] | echohl None - return 0 - endif - endif - - " set buffer window options - let g:ConqueTerm_BufName = substitute(command, ' ', '\\ ', 'g') . "\\ -\\ " . g:ConqueTerm_Idx - call conque_term#set_buffer_settings(command, hooks) - let b:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx - let g:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx - let g:ConqueTerm_Idx += 1 - - " open command - try - let l:config = '{"color":' . string(g:ConqueTerm_Color) . ',"TERM":"' . g:ConqueTerm_TERM . '"}' - execute 'python ' . b:ConqueTerm_Var . ' = Conque()' - execute "python " . b:ConqueTerm_Var . ".open('" . conque_term#python_escape(command) . "', " . l:config . ")" - catch - echohl WarningMsg | echomsg "Unable to open command: " . command | echohl None - return 0 - endtry - - " set buffer mappings and auto commands - call conque_term#set_mappings('start') - - startinsert! - return 1 -endfunction "}}} - -" set buffer options -function! conque_term#set_buffer_settings(command, pre_hooks) "{{{ - - " optional hooks to execute, e.g. 'split' - for h in a:pre_hooks - sil exe h - endfor - sil exe "edit " . g:ConqueTerm_BufName - - " buffer settings - setlocal nocompatible " conque won't work in compatible mode - setlocal nopaste " conque won't work in paste mode - setlocal buftype=nofile " this buffer is not a file, you can't save it - setlocal nonumber " hide line numbers - setlocal foldcolumn=0 " reasonable left margin - setlocal nowrap " default to no wrap (esp with MySQL) - setlocal noswapfile " don't bother creating a .swp file - setlocal updatetime=50 " trigger cursorhold event after 50ms / XXX - global - setlocal scrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescroll=1 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal foldmethod=manual " don't fold on {{{}}} and stuff - setlocal bufhidden=hide " when buffer is no longer displayed, don't wipe it out - setfiletype conque_term " useful - sil exe "setlocal syntax=" . g:ConqueTerm_Syntax - -endfunction " }}} - -" set key mappings and auto commands -function! conque_term#set_mappings(action) "{{{ - - " set action - if a:action == 'toggle' - if exists('b:conque_on') && b:conque_on == 1 - let l:action = 'stop' - echohl WarningMsg | echomsg "Terminal is paused" | echohl None - else - let l:action = 'start' - echohl WarningMsg | echomsg "Terminal is resumed" | echohl None - endif - else - let l:action = a:action - endif - - " if mappings are being removed, add 'un' - let map_modifier = 'nore' - if l:action == 'stop' - let map_modifier = 'un' - endif - - " remove all auto commands - if l:action == 'stop' - execute 'autocmd! ' . b:ConqueTerm_Var - - else - execute 'augroup ' . b:ConqueTerm_Var - - " handle unexpected closing of shell, passes HUP to parent and all child processes - execute 'autocmd ' . b:ConqueTerm_Var . ' BufUnload <buffer> python ' . b:ConqueTerm_Var . '.proc.signal(1)' - - " check for resized/scrolled buffer when entering buffer - execute 'autocmd ' . b:ConqueTerm_Var . ' BufEnter <buffer> python ' . b:ConqueTerm_Var . '.update_window_size()' - execute 'autocmd ' . b:ConqueTerm_Var . ' VimResized python ' . b:ConqueTerm_Var . '.update_window_size()' - - " set/reset updatetime on entering/exiting buffer - autocmd BufEnter <buffer> set updatetime=50 - autocmd BufLeave <buffer> set updatetime=2000 - - " check for resized/scrolled buffer when entering insert mode - " XXX - messed up since we enter insert mode at each updatetime - "execute 'autocmd InsertEnter <buffer> python ' . b:ConqueTerm_Var . '.screen.align()' - - " read more output when this isn't the current buffer - if g:ConqueTerm_ReadUnfocused == 1 - execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHold * call conque_term#read_all()' - endif - - " poll for more output - sil execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHoldI <buffer> python ' . b:ConqueTerm_Var . '.auto_read()' - endif - - " use F22 key to get more input - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F22> "\<left>\<right>"' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F23> "\<right>\<left>"' - else - sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F22>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F23>' - endif - - " map ASCII 1-31 - for c in range(1, 31) - " <Esc> - if c == 27 - continue - endif - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <C-' . nr2char(64 + c) . '> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(' . c . '))<CR>' - else - sil exe 'i' . map_modifier . 'map <silent> <buffer> <C-' . nr2char(64 + c) . '>' - endif - endfor - if l:action == 'start' - sil exe 'n' . map_modifier . 'map <silent> <buffer> <C-c> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(3))<CR>' - else - sil exe 'n' . map_modifier . 'map <silent> <buffer> <C-c>' - endif - - " leave insert mode - if !exists('g:ConqueTerm_EscKey') || g:ConqueTerm_EscKey == '<Esc>' - " use <Esc><Esc> to send <Esc> to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc><Esc> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(27))<CR>' - else - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc><Esc>' - endif - else - " use <Esc> to send <Esc> to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <silent> <buffer> ' . g:ConqueTerm_EscKey . ' <Esc>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(27))<CR>' - else - sil exe 'i' . map_modifier . 'map <silent> <buffer> ' . g:ConqueTerm_EscKey - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc>' - endif - endif - - " Map <C-w> in insert mode - if exists('g:ConqueTerm_CWInsert') && g:ConqueTerm_CWInsert == 1 - inoremap <silent> <buffer> <C-w>j <Esc><C-w>j - inoremap <silent> <buffer> <C-w>k <Esc><C-w>k - inoremap <silent> <buffer> <C-w>h <Esc><C-w>h - inoremap <silent> <buffer> <C-w>l <Esc><C-w>l - inoremap <silent> <buffer> <C-w>w <Esc><C-w>w - endif - - " map ASCII 33-127 - for i in range(33, 127) - " <Bar> - if i == 124 - if l:action == 'start' - sil exe "i" . map_modifier . "map <silent> <buffer> <Bar> <C-o>:python " . b:ConqueTerm_Var . ".write(chr(124))<CR>" - else - sil exe "i" . map_modifier . "map <silent> <buffer> <Bar>" - endif - continue - endif - if l:action == 'start' - sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) . " <C-o>:python " . b:ConqueTerm_Var . ".write(chr(" . i . "))<CR>" - else - sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) - endif - endfor - - " map ASCII 128-255 - for i in range(128, 255) - if l:action == 'start' - sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) . " <C-o>:python " . b:ConqueTerm_Var . ".write('" . nr2char(i) . "')<CR>" - else - sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) - endif - endfor - - " Special cases - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <BS> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u0008")<CR>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Space> <C-o>:python ' . b:ConqueTerm_Var . '.write(" ")<CR>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Up> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[A")<CR>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Down> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[B")<CR>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Right> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[C")<CR>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Left> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[D")<CR>' - else - sil exe 'i' . map_modifier . 'map <silent> <buffer> <BS>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Space>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Up>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Down>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Right>' - sil exe 'i' . map_modifier . 'map <silent> <buffer> <Left>' - endif - - " send selected text into conque - if l:action == 'start' - sil exe 'v' . map_modifier . 'map <silent> <F9> :<C-u>call conque_term#send_selected(visualmode())<CR>' - else - sil exe 'v' . map_modifier . 'map <silent> <F9>' - endif - - " remap paste keys - if l:action == 'start' - sil exe 'n' . map_modifier . 'map <silent> <buffer> p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a' - sil exe 'n' . map_modifier . 'map <silent> <buffer> P :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a' - sil exe 'n' . map_modifier . 'map <silent> <buffer> ]p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a' - sil exe 'n' . map_modifier . 'map <silent> <buffer> [p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a' - else - sil exe 'n' . map_modifier . 'map <silent> <buffer> p' - sil exe 'n' . map_modifier . 'map <silent> <buffer> P' - sil exe 'n' . map_modifier . 'map <silent> <buffer> ]p' - sil exe 'n' . map_modifier . 'map <silent> <buffer> [p' - endif - if has('gui_running') - if l:action == 'start' - sil exe 'i' . map_modifier . 'map <buffer> <S-Insert> <Esc>:<C-u>python ' . b:ConqueTerm_Var . ".write(vim.eval('@+'))<CR>a" - else - sil exe 'i' . map_modifier . 'map <buffer> <S-Insert>' - endif - endif - - " disable other normal mode keys which insert text - if l:action == 'start' - sil exe 'n' . map_modifier . 'map <silent> <buffer> r :echo "Replace mode disabled in shell."<CR>' - sil exe 'n' . map_modifier . 'map <silent> <buffer> R :echo "Replace mode disabled in shell."<CR>' - sil exe 'n' . map_modifier . 'map <silent> <buffer> c :echo "Change mode disabled in shell."<CR>' - sil exe 'n' . map_modifier . 'map <silent> <buffer> C :echo "Change mode disabled in shell."<CR>' - sil exe 'n' . map_modifier . 'map <silent> <buffer> s :echo "Change mode disabled in shell."<CR>' - sil exe 'n' . map_modifier . 'map <silent> <buffer> S :echo "Change mode disabled in shell."<CR>' - else - sil exe 'n' . map_modifier . 'map <silent> <buffer> r' - sil exe 'n' . map_modifier . 'map <silent> <buffer> R' - sil exe 'n' . map_modifier . 'map <silent> <buffer> c' - sil exe 'n' . map_modifier . 'map <silent> <buffer> C' - sil exe 'n' . map_modifier . 'map <silent> <buffer> s' - sil exe 'n' . map_modifier . 'map <silent> <buffer> S' - endif - - " set conque as on or off - if l:action == 'start' - let b:conque_on = 1 - else - let b:conque_on = 0 - endif - - " map command to start stop the shell - if a:action == 'start' - nnoremap <F5> :<C-u>call conque_term#set_mappings('toggle')<CR> - endif - -endfunction " }}} - - -" send selected text from another buffer -function! conque_term#send_selected(type) "{{{ - let reg_save = @@ - - " save user's sb settings - let sb_save = &switchbuf - set switchbuf=usetab - - " yank current selection - sil exe "normal! `<" . a:type . "`>y" - - " format yanked text - let @@ = substitute(@@, '^[\r\n]*', '', '') - let @@ = substitute(@@, '[\r\n]*$', '', '') - - " execute yanked text - sil exe ":sb " . g:ConqueTerm_BufName - sil exe 'python ' . g:ConqueTerm_Var . '.paste_selection()' - - " reset original values - let @@ = reg_save - sil exe 'set switchbuf=' . sb_save - - " scroll buffer left - startinsert! - normal 0zH -endfunction "}}} - -" read from all known conque buffers -function! conque_term#read_all() "{{{ - " don't run this if we're in a conque buffer - if exists('b:ConqueTerm_Var') - return - endif - - try - for i in range(1, g:ConqueTerm_Idx - 1) - execute 'python ConqueTerm_' . string(i) . '.read(1)' - endfor - catch - " probably a deleted buffer - endtry - - " restart updatetime - call feedkeys("f\e") -endfunction "}}} - -" util function to add enough \s to pass a string to python -function! conque_term#python_escape(input) "{{{ - let l:cleaned = a:input - let l:cleaned = substitute(l:cleaned, '\\', '\\\\', 'g') - let l:cleaned = substitute(l:cleaned, '\n', '\\n', 'g') - let l:cleaned = substitute(l:cleaned, '\r', '\\r', 'g') - let l:cleaned = substitute(l:cleaned, "'", "\\\\'", 'g') - return l:cleaned -endfunction "}}} - -" ********************************************************************************************************** -" **** PYTHON ********************************************************************************************** -" ********************************************************************************************************** - -if has('python') - -python << EOF - -import vim, re, time, math - -# CONFIG CONSTANTS {{{ - -CONQUE_CTL = { - 7:'bel', # bell - 8:'bs', # backspace - 9:'tab', # tab - 10:'nl', # new line - 13:'cr' # carriage return -} -# 11 : 'vt', # vertical tab -# 12 : 'ff', # form feed -# 14 : 'so', # shift out -# 15 : 'si' # shift in - -# Escape sequences -CONQUE_ESCAPE = { - 'm':'font', - 'J':'clear_screen', - 'K':'clear_line', - '@':'add_spaces', - 'A':'cursor_up', - 'B':'cursor_down', - 'C':'cursor_right', - 'D':'cursor_left', - 'G':'cursor_to_column', - 'H':'cursor', - 'P':'delete_chars', - 'f':'cursor', - 'g':'tab_clear', - 'r':'set_coords', - 'h':'set', - 'l':'reset' -} -# 'L':'insert_lines', -# 'M':'delete_lines', -# 'd':'cusor_vpos', - -# Alternate escape sequences, no [ -CONQUE_ESCAPE_PLAIN = { - 'D':'scroll_up', - 'E':'next_line', - 'H':'set_tab', - 'M':'scroll_down' -} -# 'N':'single_shift_2', -# 'O':'single_shift_3', -# '=':'alternate_keypad', -# '>':'numeric_keypad', -# '7':'save_cursor', -# '8':'restore_cursor', - -# Uber alternate escape sequences, with # or ? -CONQUE_ESCAPE_QUESTION = { - '1h':'new_line_mode', - '3h':'132_cols', - '4h':'smooth_scrolling', - '5h':'reverse_video', - '6h':'relative_origin', - '7h':'set_auto_wrap', - '8h':'set_auto_repeat', - '9h':'set_interlacing_mode', - '1l':'set_cursor_key', - '2l':'set_vt52', - '3l':'80_cols', - '4l':'set_jump_scrolling', - '5l':'normal_video', - '6l':'absolute_origin', - '7l':'reset_auto_wrap', - '8l':'reset_auto_repeat', - '9l':'reset_interlacing_mode' -} - -CONQUE_ESCAPE_HASH = { - '8':'screen_alignment_test' -} -# '3':'double_height_top', -# '4':'double_height_bottom', -# '5':'single_height_single_width', -# '6':'single_height_double_width', - -# Font codes {{{ -CONQUE_FONT = { - 0: {'description':'Normal (default)', 'attributes': {'cterm':'NONE','ctermfg':'NONE','ctermbg':'NONE','gui':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True}, - 1: {'description':'Bold', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False}, - 4: {'description':'Underlined', 'attributes': {'cterm':'UNDERLINE','gui':'UNDERLINE'}, 'normal':False}, - 5: {'description':'Blink (appears as Bold)', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False}, - 7: {'description':'Inverse', 'attributes': {'cterm':'REVERSE','gui':'REVERSE'}, 'normal':False}, - 8: {'description':'Invisible (hidden)', 'attributes': {'ctermfg':'0','ctermbg':'0','guifg':'#000000','guibg':'#000000'}, 'normal':False}, - 22: {'description':'Normal (neither bold nor faint)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 24: {'description':'Not underlined', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 25: {'description':'Steady (not blinking)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 27: {'description':'Positive (not inverse)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 28: {'description':'Visible (not hidden)', 'attributes': {'ctermfg':'NONE','ctermbg':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True}, - 30: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'16','guifg':'#000000'}, 'normal':False}, - 31: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'1','guifg':'#ff0000'}, 'normal':False}, - 32: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'2','guifg':'#00ff00'}, 'normal':False}, - 33: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'3','guifg':'#ffff00'}, 'normal':False}, - 34: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'4','guifg':'#0000ff'}, 'normal':False}, - 35: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'5','guifg':'#990099'}, 'normal':False}, - 36: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'6','guifg':'#009999'}, 'normal':False}, - 37: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'7','guifg':'#ffffff'}, 'normal':False}, - 39: {'description':'Set foreground color to default (original)', 'attributes': {'ctermfg':'NONE','guifg':'NONE'}, 'normal':True}, - 40: {'description':'Set background color to Black', 'attributes': {'ctermbg':'16','guibg':'#000000'}, 'normal':False}, - 41: {'description':'Set background color to Red', 'attributes': {'ctermbg':'1','guibg':'#ff0000'}, 'normal':False}, - 42: {'description':'Set background color to Green', 'attributes': {'ctermbg':'2','guibg':'#00ff00'}, 'normal':False}, - 43: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'3','guibg':'#ffff00'}, 'normal':False}, - 44: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'4','guibg':'#0000ff'}, 'normal':False}, - 45: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'5','guibg':'#990099'}, 'normal':False}, - 46: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'6','guibg':'#009999'}, 'normal':False}, - 47: {'description':'Set background color to White', 'attributes': {'ctermbg':'7','guibg':'#ffffff'}, 'normal':False}, - 49: {'description':'Set background color to default (original).', 'attributes': {'ctermbg':'NONE','guibg':'NONE'}, 'normal':True}, - 90: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'8','guifg':'#000000'}, 'normal':False}, - 91: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'9','guifg':'#ff0000'}, 'normal':False}, - 92: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'10','guifg':'#00ff00'}, 'normal':False}, - 93: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'11','guifg':'#ffff00'}, 'normal':False}, - 94: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'12','guifg':'#0000ff'}, 'normal':False}, - 95: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'13','guifg':'#990099'}, 'normal':False}, - 96: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'14','guifg':'#009999'}, 'normal':False}, - 97: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'15','guifg':'#ffffff'}, 'normal':False}, - 100: {'description':'Set background color to Black', 'attributes': {'ctermbg':'8','guibg':'#000000'}, 'normal':False}, - 101: {'description':'Set background color to Red', 'attributes': {'ctermbg':'9','guibg':'#ff0000'}, 'normal':False}, - 102: {'description':'Set background color to Green', 'attributes': {'ctermbg':'10','guibg':'#00ff00'}, 'normal':False}, - 103: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'11','guibg':'#ffff00'}, 'normal':False}, - 104: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'12','guibg':'#0000ff'}, 'normal':False}, - 105: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'13','guibg':'#990099'}, 'normal':False}, - 106: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'14','guibg':'#009999'}, 'normal':False}, - 107: {'description':'Set background color to White', 'attributes': {'ctermbg':'15','guibg':'#ffffff'}, 'normal':False} -} -# }}} - -# regular expression matching (almost) all control sequences -CONQUE_SEQ_REGEX = re.compile(ur"(\u001b\[?\??#?[0-9;]*[a-zA-Z@]|\u001b\][0-9];.*?\u0007|[\u0007-\u000f])", re.UNICODE) -CONQUE_SEQ_REGEX_CTL = re.compile(ur"^[\u0007-\u000f]$", re.UNICODE) -CONQUE_SEQ_REGEX_CSI = re.compile(ur"^\u001b\[", re.UNICODE) -CONQUE_SEQ_REGEX_TITLE = re.compile(ur"^\u001b\]", re.UNICODE) -CONQUE_SEQ_REGEX_HASH = re.compile(ur"^\u001b#", re.UNICODE) -CONQUE_SEQ_REGEX_ESC = re.compile(ur"^\u001b", re.UNICODE) - -# match table output -CONQUE_TABLE_OUTPUT = re.compile("^\s*\|\s.*\s\|\s*$|^\s*\+[=+-]+\+\s*$") - -# }}} - -################################################################################################### -class Conque: - - # CLASS PROPERTIES {{{ - - # screen object - screen = None - - # subprocess object - proc = None - - # terminal dimensions and scrolling region - columns = 80 # same as $COLUMNS - lines = 24 # same as $LINES - working_columns = 80 # can be changed by CSI ? 3 l/h - working_lines = 24 # can be changed by CSI r - - # top/bottom of the scroll region - top = 1 # relative to top of screen - bottom = 24 # relative to top of screen - - # cursor position - l = 1 # current cursor line - c = 1 # current cursor column - - # autowrap mode - autowrap = True - - # absolute coordinate mode - absolute_coords = True - - # tabstop positions - tabstops = [] - - # enable colors - enable_colors = True - - # color changes - color_changes = {} - - # color history - color_history = {} - - # don't wrap table output - unwrap_tables = True - - # wrap CUF/CUB around line breaks - wrap_cursor = False - - # }}} - - # constructor - def __init__(self): # {{{ - self.screen = ConqueScreen() - # }}} - - # start program and initialize this instance - def open(self, command, options): # {{{ - - # int vars - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # init color - self.enable_colors = options['color'] - - # init tabstops - self.init_tabstops() - - # open command - self.proc = ConqueSubprocess() - self.proc.open(command, { 'TERM' : options['TERM'], 'CONQUE' : '1', 'LINES' : str(self.lines), 'COLUMNS' : str(self.columns)}) - # }}} - - # write to pty - def write(self, input): # {{{ - - - # check if window size has changed - self.update_window_size() - - # write and read - self.proc.write(input) - self.read(1) - # }}} - - # read from pty, and update buffer - def read(self, timeout = 1): # {{{ - # read from subprocess - output = self.proc.read(timeout) - # and strip null chars - output = output.replace(chr(0), '') - - if output == '': - return - - - - - - chunks = CONQUE_SEQ_REGEX.split(output) - - - - - - # don't go through all the csi regex if length is one (no matches) - if len(chunks) == 1: - - self.plain_text(chunks[0]) - - else: - for s in chunks: - if s == '': - continue - - - - - - - # Check for control character match {{{ - if CONQUE_SEQ_REGEX_CTL.match(s[0]): - - nr = ord(s[0]) - if nr in CONQUE_CTL: - getattr(self, 'ctl_' + CONQUE_CTL[nr])() - else: - - pass - # }}} - - # check for escape sequence match {{{ - elif CONQUE_SEQ_REGEX_CSI.match(s): - - if s[-1] in CONQUE_ESCAPE: - csi = self.parse_csi(s[2:]) - - getattr(self, 'csi_' + CONQUE_ESCAPE[s[-1]])(csi) - else: - - pass - # }}} - - # check for title match {{{ - elif CONQUE_SEQ_REGEX_TITLE.match(s): - - self.change_title(s[2], s[4:-1]) - # }}} - - # check for hash match {{{ - elif CONQUE_SEQ_REGEX_HASH.match(s): - - if s[-1] in CONQUE_ESCAPE_HASH: - getattr(self, 'hash_' + CONQUE_ESCAPE_HASH[s[-1]])() - else: - - pass - # }}} - - # check for other escape match {{{ - elif CONQUE_SEQ_REGEX_ESC.match(s): - - if s[-1] in CONQUE_ESCAPE_PLAIN: - getattr(self, 'esc_' + CONQUE_ESCAPE_PLAIN[s[-1]])() - else: - - pass - # }}} - - # else process plain text {{{ - else: - self.plain_text(s) - # }}} - - # set cursor position - self.screen.set_cursor(self.l, self.c) - - vim.command('redraw') - - - # }}} - - # for polling - def auto_read(self): # {{{ - self.read(1) - if self.c == 1: - vim.command('call feedkeys("\<F23>", "t")') - else: - vim.command('call feedkeys("\<F22>", "t")') - self.screen.set_cursor(self.l, self.c) - # }}} - - ############################################################################################### - # Plain text # {{{ - - def plain_text(self, input): - - current_line = self.screen[self.l] - - if len(current_line) < self.working_columns: - current_line = current_line + ' ' * (self.c - len(current_line)) - - # if line is wider than screen - if self.c + len(input) - 1 > self.working_columns: - # Table formatting hack - if self.unwrap_tables and CONQUE_TABLE_OUTPUT.match(input): - self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - return - - diff = self.c + len(input) - self.working_columns - 1 - # if autowrap is enabled - if self.autowrap: - self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff ] - self.apply_color(self.c, self.working_columns) - self.ctl_nl() - self.ctl_cr() - remaining = input[ -1 * diff : ] - - self.plain_text(remaining) - else: - self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff - 1 ] + input[-1] - self.apply_color(self.c, self.working_columns) - self.c = self.working_columns - - # no autowrap - else: - self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - - def apply_color(self, start, end): - - - # stop here if coloration is disabled - if not self.enable_colors: - return - - real_line = self.screen.get_real_line(self.l) - - # check for previous overlapping coloration - - to_del = [] - if self.color_history.has_key(real_line): - for i in range(len(self.color_history[real_line])): - syn = self.color_history[real_line][i] - - if syn['start'] >= start and syn['start'] < end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['end'] > end: - - self.exec_highlight(real_line, end, syn['end'], syn['highlight']) - elif syn['end'] > start and syn['end'] <= end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['start'] < start: - - self.exec_highlight(real_line, syn['start'], start, syn['highlight']) - - if len(to_del) > 0: - to_del.reverse() - for di in to_del: - del self.color_history[real_line][di] - - # if there are no new colors - if len(self.color_changes) == 0: - return - - highlight = '' - for attr in self.color_changes.keys(): - highlight = highlight + ' ' + attr + '=' + self.color_changes[attr] - - # execute the highlight - self.exec_highlight(real_line, start, end, highlight) - - def exec_highlight(self, real_line, start, end, highlight): - unique_key = str(self.proc.pid) - - syntax_name = 'EscapeSequenceAt_' + unique_key + '_' + str(self.l) + '_' + str(start) + '_' + str(len(self.color_history) + 1) - syntax_options = ' contains=ALLBUT,ConqueString,MySQLString,MySQLKeyword oneline' - syntax_region = 'syntax match ' + syntax_name + ' /\%' + str(real_line) + 'l\%>' + str(start - 1) + 'c.*\%<' + str(end + 1) + 'c/' + syntax_options - syntax_highlight = 'highlight ' + syntax_name + highlight - - vim.command(syntax_region) - vim.command(syntax_highlight) - - # add syntax name to history - if not self.color_history.has_key(real_line): - self.color_history[real_line] = [] - - self.color_history[real_line].append({'name':syntax_name, 'start':start, 'end':end, 'highlight':highlight}) - - # }}} - - ############################################################################################### - # Control functions {{{ - - def ctl_nl(self): - # if we're in a scrolling region, scroll instead of moving cursor down - if self.lines != self.working_lines and self.l == self.bottom: - del self.screen[self.top] - self.screen.insert(self.bottom, '') - elif self.l == self.bottom: - self.screen.append('') - else: - self.l += 1 - - self.color_changes = {} - - def ctl_cr(self): - self.c = 1 - - self.color_changes = {} - - def ctl_bs(self): - if self.c > 1: - self.c += -1 - - def ctl_bel(self): - print 'BELL' - - def ctl_tab(self): - # default tabstop location - ts = self.working_columns - - # check set tabstops - for i in range(self.c, len(self.tabstops)): - if self.tabstops[i]: - ts = i + 1 - break - - - - self.c = ts - - # }}} - - ############################################################################################### - # CSI functions {{{ - - def csi_font(self, csi): # {{{ - if not self.enable_colors: - return - - # defaults to 0 - if len(csi['vals']) == 0: - csi['vals'] = [0] - - # 256 xterm color foreground - if len(csi['vals']) == 3 and csi['vals'][0] == 38 and csi['vals'][1] == 5: - self.color_changes['ctermfg'] = str(csi['vals'][2]) - self.color_changes['guifg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 256 xterm color background - elif len(csi['vals']) == 3 and csi['vals'][0] == 48 and csi['vals'][1] == 5: - self.color_changes['ctermbg'] = str(csi['vals'][2]) - self.color_changes['guibg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 16 colors - else: - for val in csi['vals']: - if CONQUE_FONT.has_key(val): - - # ignore starting normal colors - if CONQUE_FONT[val]['normal'] and len(self.color_changes) == 0: - - continue - # clear color changes - elif CONQUE_FONT[val]['normal']: - - self.color_changes = {} - # save these color attributes for next plain_text() call - else: - - for attr in CONQUE_FONT[val]['attributes'].keys(): - if self.color_changes.has_key(attr) and (attr == 'cterm' or attr == 'gui'): - self.color_changes[attr] += ',' + CONQUE_FONT[val]['attributes'][attr] - else: - self.color_changes[attr] = CONQUE_FONT[val]['attributes'][attr] - # }}} - - def csi_clear_line(self, csi): # {{{ - - - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - - # 0 means cursor right - if csi['val'] == 0: - self.screen[self.l] = self.screen[self.l][0 : self.c - 1] - - # 1 means cursor left - elif csi['val'] == 1: - self.screen[self.l] = ' ' * (self.c) + self.screen[self.l][self.c : ] - - # clear entire line - elif csi['val'] == 2: - self.screen[self.l] = '' - - # clear colors - if csi['val'] == 2 or (csi['val'] == 0 and self.c == 1): - real_line = self.screen.get_real_line(self.l) - if self.color_history.has_key(real_line): - for syn in self.color_history[real_line]: - vim.command('syn clear ' + syn['name']) - - - - # }}} - - def csi_cursor_right(self, csi): # {{{ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - - - - if self.wrap_cursor and self.c + csi['val'] > self.working_columns: - self.l += int(math.floor( (self.c + csi['val']) / self.working_columns )) - self.c = (self.c + csi['val']) % self.working_columns - return - - self.c = self.bound(self.c + csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_left(self, csi): # {{{ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - if self.wrap_cursor and csi['val'] >= self.c: - self.l += int(math.floor( (self.c - csi['val']) / self.working_columns )) - self.c = self.working_columns - (csi['val'] - self.c) % self.working_columns - return - - self.c = self.bound(self.c - csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_to_column(self, csi): # {{{ - self.c = self.bound(csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_up(self, csi): # {{{ - self.l = self.bound(self.l - csi['val'], self.top, self.bottom) - - self.color_changes = {} - # }}} - - def csi_cursor_down(self, csi): # {{{ - self.l = self.bound(self.l + csi['val'], self.top, self.bottom) - - self.color_changes = {} - # }}} - - def csi_clear_screen(self, csi): # {{{ - # default to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - # 2 == clear entire screen - if csi['val'] == 2: - self.l = 1 - self.c = 1 - self.screen.clear() - - # 0 == clear down - elif csi['val'] == 0: - for l in range(self.bound(self.l + 1, 1, self.lines), self.lines + 1): - self.screen[l] = '' - - # clear end of current line - self.csi_clear_line(self.parse_csi('K')) - - # 1 == clear up - elif csi['val'] == 1: - for l in range(1, self.bound(self.l, 1, self.lines + 1)): - self.screen[l] = '' - - # clear beginning of current line - self.csi_clear_line(self.parse_csi('1K')) - - # clear coloration - if csi['val'] == 2 or csi['val'] == 0: - real_line = self.screen.get_real_line(self.l) - for line in self.color_history.keys(): - if line >= real_line: - for syn in self.color_history[line]: - vim.command('syn clear ' + syn['name']) - - self.color_changes = {} - # }}} - - def csi_delete_chars(self, csi): # {{{ - self.screen[self.l] = self.screen[self.l][ : self.c ] + self.screen[self.l][ self.c + csi['val'] : ] - # }}} - - def csi_add_spaces(self, csi): # {{{ - self.screen[self.l] = self.screen[self.l][ : self.c - 1] + ' ' * csi['val'] + self.screen[self.l][self.c : ] - # }}} - - def csi_cursor(self, csi): # {{{ - if len(csi['vals']) == 2: - new_line = csi['vals'][0] - new_col = csi['vals'][1] - else: - new_line = 1 - new_col = 1 - - if self.absolute_coords: - self.l = self.bound(new_line, 1, self.lines) - else: - self.l = self.bound(self.top + new_line - 1, self.top, self.bottom) - - self.c = self.bound(new_col, 1, self.working_columns) - if self.c > len(self.screen[self.l]): - self.screen[self.l] = self.screen[self.l] + ' ' * (self.c - len(self.screen[self.l])) - - # }}} - - def csi_set_coords(self, csi): # {{{ - if len(csi['vals']) == 2: - new_start = csi['vals'][0] - new_end = csi['vals'][1] - else: - new_start = 1 - new_end = vim.current.window.height - - self.top = new_start - self.bottom = new_end - self.working_lines = new_end - new_start + 1 - - # if cursor is outside scrolling region, reset it - if self.l < self.top: - self.l = self.top - elif self.l > self.bottom: - self.l = self.bottom - - self.color_changes = {} - # }}} - - def csi_tab_clear(self, csi): # {{{ - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - if csi['val'] == 0: - self.tabstops[self.c - 1] = False - elif csi['val'] == 3: - for i in range(0, self.columns + 1): - self.tabstops[i] = False - # }}} - - def csi_set(self, csi): # {{{ - # 132 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 132 - - # relative_origin - elif csi['val'] == 6: - self.absolute_coords = False - - # set auto wrap - elif csi['val'] == 7: - self.autowrap = True - - - self.color_changes = {} - # }}} - - def csi_reset(self, csi): # {{{ - # 80 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 80 - - # absolute origin - elif csi['val'] == 6: - self.absolute_coords = True - - # reset auto wrap - elif csi['val'] == 7: - self.autowrap = False - - - self.color_changes = {} - # }}} - - # }}} - - ############################################################################################### - # ESC functions {{{ - - def esc_scroll_up(self): # {{{ - self.ctl_nl() - - self.color_changes = {} - # }}} - - def esc_next_line(self): # {{{ - self.ctl_nl() - self.c = 1 - # }}} - - def esc_set_tab(self): # {{{ - - if self.c <= len(self.tabstops): - self.tabstops[self.c - 1] = True - # }}} - - def esc_scroll_down(self): # {{{ - if self.l == self.top: - del self.screen[self.bottom] - self.screen.insert(self.top, '') - else: - self.l += -1 - - self.color_changes = {} - # }}} - - # }}} - - ############################################################################################### - # HASH functions {{{ - - def hash_screen_alignment_test(self): # {{{ - self.csi_clear_screen(self.parse_csi('2J')) - self.working_lines = self.lines - for l in range(1, self.lines + 1): - self.screen[l] = 'E' * self.working_columns - # }}} - - # }}} - - ############################################################################################### - # Random stuff {{{ - - def change_title(self, key, val): - - - if key == '0' or key == '2': - - vim.command('setlocal statusline=' + re.escape(val)) - - def paste(self): - self.write(vim.eval('@@')) - self.read(50) - - def paste_selection(self): - self.write(vim.eval('@@')) - - def update_window_size(self): - # resize if needed - if vim.current.window.width != self.columns or vim.current.window.height != self.lines: - - # reset all window size attributes to default - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # reset screen object attributes - self.l = self.screen.reset_size(self.l) - - # reset tabstops - self.init_tabstops() - - - - # signal process that screen size has changed - self.proc.window_resize(self.lines, self.columns) - - def init_tabstops(self): - for i in range(0, self.columns + 1): - if i % 8 == 0: - self.tabstops.append(True) - else: - self.tabstops.append(False) - - # }}} - - ############################################################################################### - # Utility {{{ - - def parse_csi(self, s): # {{{ - attr = { 'key' : s[-1], 'flag' : '', 'val' : 1, 'vals' : [] } - - if len(s) == 1: - return attr - - full = s[0:-1] - - if full[0] == '?': - full = full[1:] - attr['flag'] = '?' - - if full != '': - vals = full.split(';') - for val in vals: - - val = re.sub("\D", "", val) - - if val != '': - attr['vals'].append(int(val)) - - if len(attr['vals']) == 1: - attr['val'] = int(attr['vals'][0]) - - return attr - # }}} - - def bound(self, val, min, max): # {{{ - if val > max: - return max - - if val < min: - return min - - return val - # }}} - - def xterm_to_rgb(self, color_code): # {{{ - if color_code < 16: - ascii_colors = ['000000', 'CD0000', '00CD00', 'CDCD00', '0000EE', 'CD00CD', '00CDCD', 'E5E5E5', - '7F7F7F', 'FF0000', '00FF00', 'FFFF00', '5C5CFF', 'FF00FF', '00FFFF', 'FFFFFF'] - return ascii_colors[color_code] - - elif color_code < 232: - cc = int(color_code) - 16 - - p1 = "%02x" % (math.floor(cc / 36) * (255/5)) - p2 = "%02x" % (math.floor((cc % 36) / 6) * (255/5)) - p3 = "%02x" % (math.floor(cc % 6) * (255/5)) - - return p1 + p2 + p3 - else: - grey_tone = "%02x" % math.floor((255/24) * (color_code - 232)) - return grey_tone + grey_tone + grey_tone - # }}} - - # }}} - - -import os, signal, pty, tty, select, fcntl, termios, struct - -################################################################################################### -class ConqueSubprocess: - - # process id - pid = 0 - - # stdout+stderr file descriptor - fd = None - - # constructor - def __init__(self): # {{{ - self.pid = 0 - # }}} - - # create the pty or whatever (whatever == windows) - def open(self, command, env = {}): # {{{ - command_arr = command.split() - executable = command_arr[0] - args = command_arr - - try: - self.pid, self.fd = pty.fork() - - except: - pass - - - # child proc, replace with command after altering terminal attributes - if self.pid == 0: - - # set requested environment variables - for k in env.keys(): - os.environ[k] = env[k] - - # set some attributes - try: - attrs = tty.tcgetattr(1) - attrs[0] = attrs[0] ^ tty.IGNBRK - attrs[0] = attrs[0] | tty.BRKINT | tty.IXANY | tty.IMAXBEL - attrs[2] = attrs[2] | tty.HUPCL - attrs[3] = attrs[3] | tty.ICANON | tty.ECHO | tty.ISIG | tty.ECHOKE - attrs[6][tty.VMIN] = 1 - attrs[6][tty.VTIME] = 0 - tty.tcsetattr(1, tty.TCSANOW, attrs) - except: - pass - - os.execvp(executable, args) - - # else master, do nothing - else: - pass - - # }}} - - # read from pty - # XXX - select.poll() doesn't work in OS X!!!!!!! - def read(self, timeout = 1): # {{{ - - output = '' - read_timeout = float(timeout) / 1000 - - try: - # what, no do/while? - while 1: - s_read, s_write, s_error = select.select( [ self.fd ], [], [], read_timeout) - - lines = '' - for s_fd in s_read: - try: - lines = os.read( self.fd, 32 ) - except: - pass - output = output + lines - - if lines == '': - break - except: - pass - - return output - # }}} - - # I guess this one's not bad - def write(self, input): # {{{ - try: - os.write(self.fd, input) - except: - pass - # }}} - - # signal process - def signal(self, signum): # {{{ - try: - os.kill(self.pid, signum) - except: - pass - # }}} - - # get process status - def get_status(self): #{{{ - - p_status = True - - try: - if os.waitpid( self.pid, os.WNOHANG )[0]: - p_status = False - except: - p_status = False - - return p_status - - # }}} - - # update window size in kernel, then send SIGWINCH to fg process - def window_resize(self, lines, columns): # {{{ - try: - fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack("HHHH", lines, columns, 0, 0)) - os.kill(self.pid, signal.SIGWINCH) - except: - pass - - # }}} - - -################################################################################################### -# ConqueScreen is an extention of the vim.current.buffer object -# It restricts the working indices of the buffer object to the scroll region which pty is expecting -# It also uses 1-based indexes, to match escape sequence commands -# -# E.g.: -# s = ConqueScreen() -# ... -# s[5] = 'Set 5th line in terminal to this line' -# s.append('Add new line to terminal') -# s[5] = 'Since previous append() command scrolled the terminal down, this is a different line than first cb[5] call' -# - -import vim - -class ConqueScreen(object): - - # CLASS PROPERTIES {{{ - - # the buffer - buffer = None - - # screen and scrolling regions - screen_top = 1 - - # screen width - screen_width = 80 - screen_height = 80 - - # }}} - - def __init__(self): # {{{ - self.buffer = vim.current.buffer - - self.screen_top = 1 - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - # }}} - - ############################################################################################### - # List overload {{{ - def __len__(self): # {{{ - return len(self.buffer) - # }}} - - def __getitem__(self, key): # {{{ - real_line = self.get_real_idx(key) - - # if line is past buffer end, add lines to buffer - if real_line >= len(self.buffer): - for i in range(len(self.buffer), real_line + 1): - self.append(' ' * self.screen_width) - - return self.buffer[ real_line ] - # }}} - - def __setitem__(self, key, value): # {{{ - real_line = self.get_real_idx(key) - - # if line is past end of screen, append - if real_line == len(self.buffer): - self.buffer.append(value) - else: - self.buffer[ real_line ] = value - # }}} - - def __delitem__(self, key): # {{{ - del self.buffer[ self.screen_top + key - 2 ] - # }}} - - def append(self, value): # {{{ - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.buffer[len(self.buffer) - 1] = value - else: - self.buffer.append(value) - - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.screen_top += 1 - if vim.current.buffer.number == self.buffer.number: - vim.command('normal G') - # }}} - - def insert(self, line, value): # {{{ - - l = self.screen_top + line - 2 - self.buffer[l:l] = [ value ] - - # }}} - # }}} - - ############################################################################################### - # Util {{{ - def get_top(self): # {{{ - return self.screen_top - # }}} - - def get_real_idx(self, line): # {{{ - return (self.screen_top + line - 2) - # }}} - - def get_real_line(self, line): # {{{ - return (self.screen_top + line - 1) - # }}} - - def set_screen_width(self, width): # {{{ - self.screen_width = width - # }}} - - # }}} - - ############################################################################################### - def clear(self): # {{{ - self.buffer.append(' ') - vim.command('normal Gzt') - self.screen_top = len(self.buffer) - # }}} - - def set_cursor(self, line, column): # {{{ - # figure out line - real_line = self.screen_top + line - 1 - if real_line > len(self.buffer): - for l in range(len(self.buffer) - 1, real_line): - self.buffer.append('') - - # figure out column - real_column = column - if len(self.buffer[real_line - 1]) < real_column: - self.buffer[real_line - 1] = self.buffer[real_line - 1] + ' ' * (real_column - len(self.buffer[real_line - 1])) - - # python version is occasionally grumpy - try: - vim.current.window.cursor = (real_line, real_column - 1) - except: - vim.command('call cursor(' + str(real_line) + ', ' + str(real_column) + ')') - # }}} - - def reset_size(self, line): # {{{ - - - - - # save cursor line number - real_line = self.screen_top + line - - # reset screen size - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - self.screen_top = len(self.buffer) - vim.current.window.height + 1 - if self.screen_top < 1: - self.screen_top = 1 - - - # align bottom of buffer to bottom of screen - vim.command('normal ' + str(self.screen_height) + 'kG') - - # return new relative line number - return (real_line - self.screen_top) - # }}} - - def scroll_to_bottom(self): # {{{ - vim.current.window.cursor = (len(self.buffer) - 1, 1) - # }}} - - def align(self): # {{{ - # align bottom of buffer to bottom of screen - vim.command('normal ' + str(self.screen_height) + 'kG') - # }}} - - -EOF - -endif - diff --git a/vim/autoload/rails.vim b/vim/autoload/rails.vim deleted file mode 100644 index ca36075..0000000 --- a/vim/autoload/rails.vim +++ /dev/null @@ -1,4560 +0,0 @@ -" autoload/rails.vim -" Author: Tim Pope <http://tpo.pe/> - -" Install this file as autoload/rails.vim. - -if exists('g:autoloaded_rails') || &cp - finish -endif -let g:autoloaded_rails = '4.4' - -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('<sfile>'), '<SNR>\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:uniq(list) - let seen = {} - let i = 0 - while i < len(a:list) - if has_key(seen,a:list[i]) - call remove(a:list, i) - else - let seen[a:list[i]] = 1 - let i += 1 - endif - endwhile - return a:list -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,'\\\@<!\%(\\\\\)*\zs,') - return map(split,'substitute(v:val,''\\\([\\, ]\)'',''\1'',"g")') -endfunction - -" Convert a list to a path. From pathogen.vim -function! s:pathjoin(...) abort - let i = 0 - let path = "" - while i < a:0 - if type(a:000[i]) == type([]) - let list = a:000[i] - let j = 0 - while j < len(list) - let escaped = substitute(list[j],'[\\, ]','\\&','g') - if exists("+shellslash") && !&shellslash - let escaped = substitute(escaped,'^\(\w:\\\)\\','\1','') - endif - let path .= ',' . escaped - let j += 1 - endwhile - else - let path .= "," . a:000[i] - endif - let i += 1 - endwhile - return substitute(path,'^,','','') -endfunction - -function! s:readable_end_of(lnum) dict abort - if a:lnum == 0 - return 0 - endif - if self.name() =~# '\.yml$' - return -1 - endif - let cline = self.getline(a:lnum) - let spc = matchstr(cline,'^\s*') - let endpat = '\<end\>' - 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 - if self.type_name('test') - let define .= '\|^\s*test\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 lnum = self.last_method_line(a:start) - let line = self.getline(lnum) - if line =~# '^\s*test\s*\([''"]\).*\1' - let string = matchstr(line,'^\s*\w\+\s*\([''"]\)\zs.*\ze\1') - return 'test_'.s:gsub(string,' +','_') - elseif lnum - return s:sub(matchstr(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 - if self.type_name('view') - let format = fnamemodify(self.path(),':r:e') - if format == '' - return get({'rhtml': 'html', 'rxml': 'xml', 'rjs': 'js', 'haml': 'html'},fnamemodify(self.path(),':e'),'') - else - return format - endif - endif - let rline = self.last_opening_line(a:start,'\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\<do\|{\)\s*|\zs\h\k*\ze|',self.last_method_line(a:start)) - if rline - let variable = matchstr(self.getline(rline),'\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\<do\|{\)\s*|\zs\h\k*\ze|') - let line = a:start - while line > 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(...) - let format = rails#buffer().last_format(a:0 > 1 ? a:2 : line(".")) - return format ==# '' && a:0 ? a:1 : 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 = split('rhtml,erb,rxml,builder,rjs,mab,liquid,haml,dryml,mn,slim',',') - -function! s:viewspattern() - return '\%('.join(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 =~ '\<app/views/layouts/' - return s:sub(f,'.*<app/views/layouts/(.{-})\..*','\1') - elseif f =~ '\<app/views/' - return s:sub(f,'.*<app/views/(.{-})/\k+\.\k+%(\.\k+)=$','\1') - elseif f =~ '\<app/helpers/.*_helper\.rb$' - return s:sub(f,'.*<app/helpers/(.{-})_helper\.rb$','\1') - elseif f =~ '\<app/controllers/.*\.rb$' - return s:sub(f,'.*<app/controllers/(.{-})%(_controller)=\.rb$','\1') - elseif f =~ '\<app/mailers/.*\.rb$' - return s:sub(f,'.*<app/mailers/(.{-})\.rb$','\1') - elseif f =~ '\<app/apis/.*_api\.rb$' - return s:sub(f,'.*<app/apis/(.{-})_api\.rb$','\1') - elseif f =~ '\<test/functional/.*_test\.rb$' - return s:sub(f,'.*<test/functional/(.{-})%(_controller)=_test\.rb$','\1') - elseif f =~ '\<test/unit/helpers/.*_helper_test\.rb$' - return s:sub(f,'.*<test/unit/helpers/(.{-})_helper_test\.rb$','\1') - elseif f =~ '\<spec/controllers/.*_spec\.rb$' - return s:sub(f,'.*<spec/controllers/(.{-})%(_controller)=_spec\.rb$','\1') - elseif f =~ '\<spec/helpers/.*_helper_spec\.rb$' - return s:sub(f,'.*<spec/helpers/(.{-})_helper_spec\.rb$','\1') - elseif f =~ '\<spec/views/.*/\w\+_view_spec\.rb$' - return s:sub(f,'.*<spec/views/(.{-})/\w+_view_spec\.rb$','\1') - elseif f =~ '\<components/.*_controller\.rb$' - return s:sub(f,'.*<components/(.{-})_controller\.rb$','\1') - elseif f =~ '\<components/.*\.'.s:viewspattern().'$' - return s:sub(f,'.*<components/(.{-})/\k+\.\k+$','\1') - elseif f =~ '\<app/models/.*\.rb$' && self.type_name('mailer') - return s:sub(f,'.*<app/models/(.{-})\.rb$','\1') - elseif f =~ '\<\%(public\|app/assets\)/stylesheets/.*\.css\%(\.\w\+\)\=$' - return s:sub(f,'.*<%(public|app/assets)/stylesheets/(.{-})\.css%(\.\w+)=$','\1') - elseif f =~ '\<\%(public\|app/assets\)/javascripts/.*\.js\%(\.\w\+\)\=$' - return s:sub(f,'.*<%(public|app/assets)/javascripts/(.{-})\.js%(\.\w+)=$','\1') - elseif a:0 && a:1 - return rails#pluralize(self.model_name()) - endif - return "" -endfunction - -function! s:model(...) - return rails#buffer().model_name(a:0 ? a:1 : 0) -endfunction - -function! s:readable_model_name(...) dict abort - let f = self.name() - if has_key(self,'getvar') && self.getvar('rails_model') != '' - return self.getvar('rails_model') - elseif f =~ '\<app/models/.*_observer.rb$' - return s:sub(f,'.*<app/models/(.*)_observer\.rb$','\1') - elseif f =~ '\<app/models/.*\.rb$' - return s:sub(f,'.*<app/models/(.*)\.rb$','\1') - elseif f =~ '\<test/unit/.*_observer_test\.rb$' - return s:sub(f,'.*<test/unit/(.*)_observer_test\.rb$','\1') - elseif f =~ '\<test/unit/.*_test\.rb$' - return s:sub(f,'.*<test/unit/(.*)_test\.rb$','\1') - elseif f =~ '\<spec/models/.*_spec\.rb$' - return s:sub(f,'.*<spec/models/(.*)_spec\.rb$','\1') - elseif f =~ '\<\%(test\|spec\)/fixtures/.*\.\w*\~\=$' - return rails#singularize(s:sub(f,'.*<%(test|spec)/fixtures/(.*)\.\w*\~=$','\1')) - elseif f =~ '\<\%(test\|spec\)/blueprints/.*\.rb$' - return s:sub(f,'.*<%(test|spec)/blueprints/(.{-})%(_blueprint)=\.rb$','\1') - elseif f =~ '\<\%(test\|spec\)/exemplars/.*_exemplar\.rb$' - return s:sub(f,'.*<%(test|spec)/exemplars/(.*)_exemplar\.rb$','\1') - elseif f =~ '\<\%(test/\|spec/\)\=factories/.*\.rb$' - return s:sub(f,'.*<%(test/|spec/)=factories/(.{-})%(_factory)=\.rb$','\1') - elseif f =~ '\<\%(test/\|spec/\)\=fabricators/.*\.rb$' - return s:sub(f,'.*<%(test/|spec/)=fabricators/(.{-})%(_fabricator)=\.rb$','\1') - elseif a:0 && a:1 - return rails#singularize(self.controller_name()) - endif - return "" -endfunction - -call s:add_methods('readable',['controller_name','model_name']) - -function! s:readfile(path,...) - let nr = bufnr('^'.a:path.'$') - if nr < 0 && exists('+shellslash') && ! &shellslash - let nr = bufnr('^'.s:gsub(a:path,'/','\\').'$') - endif - if bufloaded(nr) - return getbufline(nr,1,a:0 ? a:1 : '$') - elseif !filereadable(a:path) - return [] - elseif a:0 - return readfile(a:path,'',a:1) - else - return readfile(a:path) - endif -endfunction - -function! s:file_lines() dict abort - let ftime = getftime(self.path) - if ftime > 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,'%([Mm]ov|[aeio])@<!ies$','ys') - let word = s:sub(word,'xe[ns]$','xs') - let word = s:sub(word,'ves$','fs') - let word = s:sub(word,'ss%(es)=$','sss') - let word = s:sub(word,'s$','') - let word = s:sub(word,'%([nrt]ch|tatus|lias)\zse$','') - let word = s:sub(word,'%(nd|rt)\zsice$','ex') - return word -endfunction - -function! rails#pluralize(word) - let word = a:word - if word == '' - return word - endif - let word = s:sub(word,'[aeio]@<!y$','ie') - let word = s:sub(word,'%(nd|rt)@<=ex$','ice') - let word = s:sub(word,'%([osxz]|[cs]h)$','&e') - let word = s:sub(word,'f@<!f$','ve') - let word .= 's' - let word = s:sub(word,'ersons$','eople') - return word -endfunction - -function! rails#app(...) - let root = a:0 ? a:1 : RailsRoot() - " TODO: populate dynamically - " TODO: normalize path - return get(s:apps,root,0) -endfunction - -function! rails#buffer(...) - return extend(extend({'#': bufnr(a:0 ? a:1 : '%')},s:buffer_prototype,'keep'),s:readable_prototype,'keep') - endif -endfunction - -function! s:buffer_app() dict abort - if self.getvar('rails_root') != '' - return rails#app(self.getvar('rails_root')) - else - return 0 - endif -endfunction - -function! s:readable_app() dict abort - return self._app -endfunction - -function! RailsRevision() - return 1000*matchstr(g:autoloaded_rails,'^\d\+')+matchstr(g:autoloaded_rails,'[1-9]\d*$') -endfunction - -function! RailsRoot() - if exists("b:rails_root") - return b:rails_root - else - return "" - endif -endfunction - -function! s:app_file(name) - return extend(extend({'_app': self, '_name': a:name}, s:file_prototype,'keep'),s:readable_prototype,'keep') -endfunction - -function! s:file_path() dict abort - return self.app().path(self._name) -endfunction - -function! s:file_name() dict abort - return self._name -endfunction - -function! s:buffer_number() dict abort - return self['#'] -endfunction - -function! s:buffer_path() dict abort - return s:gsub(fnamemodify(bufname(self.number()),':p'),'\\ @!','/') -endfunction - -function! s:buffer_name() dict abort - let app = self.app() - let f = s:gsub(resolve(fnamemodify(bufname(self.number()),':p')),'\\ @!','/') - let f = s:sub(f,'/$','') - let sep = matchstr(f,'^[^\\/]\{3,\}\zs[\\/]') - if sep != "" - let f = getcwd().sep.f - endif - if s:startswith(tolower(f),s:gsub(tolower(app.path()),'\\ @!','/')) || f == "" - return strpart(f,strlen(app.path())+1) - else - if !exists("s:path_warn") - let s:path_warn = 1 - call s:warn("File ".f." does not appear to be under the Rails root ".self.app().path().". Please report to the rails.vim author!") - endif - return f - endif -endfunction - -function! RailsFilePath() - if !exists("b:rails_root") - return "" - else - return rails#buffer().name() - endif -endfunction - -function! RailsFile() - return RailsFilePath() -endfunction - -function! RailsFileType() - if !exists("b:rails_root") - return "" - else - return rails#buffer().type_name() - end -endfunction - -function! s:readable_calculate_file_type() dict abort - let f = self.name() - let e = fnamemodify(f,':e') - let r = "-" - let full_path = self.path() - let nr = bufnr('^'.full_path.'$') - if nr < 0 && exists('+shellslash') && ! &shellslash - let nr = bufnr('^'.s:gsub(full_path,'/','\\').'$') - endif - if f == "" - let r = f - elseif nr > 0 && getbufvar(nr,'rails_file_type') != '' - return getbufvar(nr,'rails_file_type') - elseif f =~ '_controller\.rb$' || f =~ '\<app/controllers/.*\.rb$' - if join(s:readfile(full_path,50),"\n") =~ '\<wsdl_service_name\>' - let r = "controller-api" - else - let r = "controller" - endif - elseif f =~ '_api\.rb' - let r = "api" - elseif f =~ '\<test/test_helper\.rb$' - let r = "test" - elseif f =~ '\<spec/spec_helper\.rb$' - let r = "spec" - elseif f =~ '_helper\.rb$' - let r = "helper" - elseif f =~ '\<app/metal/.*\.rb$' - let r = "metal" - elseif f =~ '\<app/mailers/.*\.rb' - let r = "mailer" - elseif f =~ '\<app/models/' - let top = join(s:readfile(full_path,50),"\n") - let class = matchstr(top,'\<Acti\w\w\u\w\+\%(::\h\w*\)\+\>') - if class == "ActiveResource::Base" - let class = "ares" - let r = "model-ares" - elseif class == 'ActionMailer::Base' - let r = "mailer" - elseif class != '' - let class = tolower(s:gsub(class,'[^A-Z]','')) - let r = "model-".class - elseif f =~ '_mailer\.rb$' - let r = "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 =~ '\<app/views/layouts\>.*\.' - let r = "view-layout-" . e - elseif f =~ '\<\%(app/views\|components\)/.*/_\k\+\.\k\+\%(\.\k\+\)\=$' - let r = "view-partial-" . e - elseif f =~ '\<app/views\>.*\.' || f =~ '\<components/.*/.*\.'.s:viewspattern().'$' - let r = "view-" . e - elseif f =~ '\<test/unit/.*_test\.rb$' - let r = "test-unit" - elseif f =~ '\<test/functional/.*_test\.rb$' - let r = "test-functional" - elseif f =~ '\<test/integration/.*_test\.rb$' - let r = "test-integration" - elseif f =~ '\<spec/lib/.*_spec\.rb$' - let r = 'spec-lib' - elseif f =~ '\<lib/.*\.rb$' - let r = 'lib' - elseif f =~ '\<spec/\w*s/.*_spec\.rb$' - let r = s:sub(f,'.*<spec/(\w*)s/.*','spec-\1') - elseif f =~ '\<features/.*\.feature$' - let r = 'cucumber-feature' - elseif f =~ '\<features/step_definitions/.*_steps\.rb$' - let r = 'cucumber-steps' - elseif f =~ '\<features/.*\.rb$' - let r = 'cucumber' - elseif f =~ '\<\%(test\|spec\)/fixtures\>' - if e == "yml" - let r = "fixtures-yaml" - else - let r = "fixtures" . (e == "" ? "" : "-" . e) - endif - elseif f =~ '\<test/.*_test\.rb' - let r = "test" - elseif f =~ '\<spec/.*_spec\.rb' - let r = "spec" - elseif f =~ '\<spec/support/.*\.rb' - let r = "spec" - elseif f =~ '\<db/migrate\>' - let r = "db-migration" - elseif f=~ '\<db/schema\.rb$' - let r = "db-schema" - elseif f =~ '\<vendor/plugins/.*/recipes/.*\.rb$' || f =~ '\.rake$' || f =~ '\<\%(Rake\|Cap\)file$' || f =~ '\<config/deploy\.rb$' - let r = "task" - elseif f =~ '\<log/.*\.log$' - let r = "log" - elseif e == "css" || e =~ "s[ac]ss" || e == "less" - let r = "stylesheet-".e - elseif e == "js" - let r = "javascript" - elseif e == "coffee" - let r = "javascript-coffee" - elseif e == "html" - let r = e - elseif f =~ '\<config/routes\>.*\.rb$' - let r = "config-routes" - elseif f =~ '\<config/' - let r = "config" - endif - return r -endfunction - -function! s:buffer_type_name(...) dict abort - let type = getbufvar(self.number(),'rails_cached_file_type') - if type == '' - let type = self.calculate_file_type() - endif - return call('s:match_type',[type == '-' ? '' : type] + a:000) -endfunction - -function! s:readable_type_name() dict abort - let type = self.calculate_file_type() - return call('s:match_type',[type == '-' ? '' : type] + a:000) -endfunction - -function! s:match_type(type,...) - if a:0 - return !empty(filter(copy(a:000),'a:type =~# "^".v:val."\\%(-\\|$\\)"')) - 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/', - \'lesscss': 'app/stylesheets/', - \'coffee': 'app/scripts/'} - 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_script_shell_command(cmd) dict abort - if self.has_file('script/rails') && a:cmd !~# '^rails\>' - let cmd = 'script/rails '.a:cmd - else - let cmd = 'script/'.a:cmd - endif - return self.ruby_shell_command(cmd) -endfunction - -function! s:app_background_script_command(cmd) dict abort - let cmd = s:esccmd(self.script_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 - elseif exists("$TMUX") && !has("gui_running") && screen && executable("tmux") - silent exe '!tmux new-window -d -n "'.s:sub(s:sub(a:cmd,'\s.*',''),'^%(script|-rcommand)/','rails-').'" "'.cmd.'"' - else - exe "!".cmd - endif - return v:shell_error -endfunction - -function! s:app_execute_script_command(cmd) dict abort - exe '!'.s:esccmd(self.script_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','script_shell_command','execute_script_command','background_script_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(<bang>0,!<count> && <line1> ? -1 : <count>,<q-args>) - command! -buffer -bar -nargs=? -bang -range -complete=customlist,s:Complete_preview Rpreview :call s:Preview(<bang>0,<line1>,<q-args>) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_environments Rlog :call s:Log(<bang>0,<q-args>) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_set Rset :call s:Set(<bang>0,<f-args>) - 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 <bang>0 || <q-args> =~ "^\\([:'-]\\|g:\\)" | - \ exe RailsHelpCommand(<q-args>) | - \ else | call s:Doc(<bang>0,<q-args>) | endif - command! -buffer -bar -nargs=0 -bang Rrefresh :if <bang>0|unlet! g:autoloaded_rails|source `=s:file`|endif|call s:Refresh(<bang>0) - if exists(":NERDTree") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rtree :NERDTree `=rails#app().path(<f-args>)` - endif - if exists("g:loaded_dbext") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_environments Rdbext :call s:BufDatabase(2,<q-args>)|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 -bang -nargs=? -range -complete=customlist,s:controllerList Rextract :<line1>,<line2>call s:Extract(<bang>0,<f-args>) - endif - if RailsFilePath() =~ '\<db/migrate/.*\.rb$' - command! -buffer -bar Rinvert :call s:Invert(<bang>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') && rails#buffer().type_name() == '' - echo msg." (Rails)" - elseif a:bang && exists('b:rails_root') - echo msg." (Rails-".rails#buffer().type_name().")" - elseif a:bang - echo msg - else - !rails - endif - return - endif - let args = map(copy(a:000),'expand(v:val)') - if a:bang - let args = ['--force'] + args - endif - exe '!rails '.join(map(copy(args),'s:rquote(v:val)'),' ') - for dir in args - if dir !~# '^-' && filereadable(dir.'/'.g:rails_default_file) - edit `=dir.'/'.g:rails_default_file` - return - endif - endfor -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,' - \.'%\\s%#[%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:,' - \.'%m\ [%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 exists('b:bundler_root') && b:bundler_root ==# rails#app().path() - let &l:makeprg = 'bundle exec rake' - else - let &l:makeprg = 'rake' - endif - let &l:errorformat = s:efm_backtrace - 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 - if !has_key(self,'options') | let self.options = {} | endif - if arg == '-' - let arg = get(self.options,'last_rake_task','') - endif - let self.options['last_rake_task'] = arg - 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\>.*\|migrate:status\|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 lnum = a:lnum < 0 ? 0 : a:lnum - if self.getvar('&buftype') == 'quickfix' - return '-' - elseif 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 self.type_name('config-routes') - return 'routes' - elseif self.type_name('fixtures-yaml') && lnum - return "db:fixtures:identify LABEL=".self.last_method(lnum) - elseif self.type_name('fixtures') && lnum == 0 - return "db:fixtures:load FIXTURES=".s:sub(fnamemodify(self.name(),':r'),'^.{-}/fixtures/','') - elseif self.type_name('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 self.type_name('spec') - if self.name() =~# '\<spec/spec_helper\.rb$' - return 'spec' - elseif lnum > 0 - return 'spec SPEC="'.self.path().'":'.lnum - else - return 'spec SPEC="'.self.path().'"' - endif - elseif self.type_name('test') - let meth = self.last_method(lnum) - if meth =~ '^test_' - let call = " -n".meth."" - else - let call = "" - endif - if self.type_name('test-unit','test-functional','test-integration') - return s:sub(s:gsub(self.type_name(),'-',':'),'unit$|functional$','&s').' TEST="'.self.path().'"'.s:sub(call,'^ ',' TESTOPTS=') - elseif self.name() =~# '\<test/test_helper\.rb$' - return 'test' - else - return 'test:recent TEST="'.self.path().'"'.s:sub(call,'^ ',' TESTOPTS=') - endif - elseif self.type_name('db-migration') - let ver = matchstr(self.name(),'\<db/migrate/0*\zs\d*\ze_') - if ver != "" - let method = self.last_method(lnum) - if method == "down" || lnum == 1 - return "db:migrate:down VERSION=".ver - elseif method == "up" || lnum == line('$') - return "db:migrate:up VERSION=".ver - elseif lnum > 0 - return "db:migrate:down db:migrate:up VERSION=".ver - else - return "db:migrate VERSION=".ver - endif - else - return 'db:migrate' - endif - elseif self.name() =~# '\<db/seeds\.rb$' - return 'db:seed' - elseif self.type_name('controller') && lnum - let lm = self.last_method(lnum) - if lm != '' - " rake routes doesn't support ACTION... yet... - return 'routes CONTROLLER='.self.controller_name().' ACTION='.lm - else - return 'routes CONTROLLER='.self.controller_name() - endif - elseif app.has('spec') && self.name() =~# '^app/.*\.\w\+$' && app.has_file(s:sub(self.name(),'^app/(.*)\.\w\+$','spec/\1_spec.rb')) - return 'spec SPEC="'.fnamemodify(s:sub(self.name(),'<app/','spec/'),':p:r').'_spec.rb"' - elseif app.has('spec') && self.name() =~# '^app/.*\.\w\+$' && app.has_file(s:sub(self.name(),'^app/(.*)$','spec/\1_spec.rb')) - return 'spec SPEC="'.fnamemodify(s:sub(self.name(),'<app/','spec/'),':p').'_spec.rb"' - elseif self.type_name('model') - return 'test:units TEST="'.fnamemodify(s:sub(self.name(),'<app/models/','test/unit/'),':p:r').'_test.rb"' - elseif self.type_name('api','mailer') - return 'test:units TEST="'.fnamemodify(s:sub(self.name(),'<app/%(apis|mailers|models)/','test/functional/'),':p:r').'_test.rb"' - elseif self.type_name('helper') - return 'test:units TEST="'.fnamemodify(s:sub(self.name(),'<app/','test/unit/'),':p:r').'_test.rb"' - elseif self.type_name('controller','helper','view') - if self.name() =~ '\<app/' && s:controller() !~# '^\%(application\)\=$' - return 'test:functionals TEST="'.s:escarg(app.path('test/functional/'.s:controller().'_controller_test.rb')).'"' - else - return 'test:functionals' - endif - elseif self.type_name('cucumber-feature') - if lnum > 0 - return 'cucumber FEATURE="'.self.path().'":'.lnum - else - return 'cucumber FEATURE="'.self.path().'"' - endif - elseif self.type_name('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 <args> - elseif has("gui_win32") - command -bar -nargs=1 OpenURL :!start cmd /cstart /b <args> - elseif executable("sensible-browser") - command -bar -nargs=1 OpenURL :!sensible-browser <args> - 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/'),'\.s[ac]ss$','.css')] - elseif self.name() =~ '^public/' - let urls = urls + [s:sub(self.name(),'^public','')] - elseif self.name() =~ '^app/assets/stylesheets/' - let urls = urls + ['/assets/application.css'] - elseif self.name() =~ '^app/assets/javascripts/' - let urls = urls + ['/assets/application.js'] - elseif self.name() =~ '^app/stylesheets/' - let urls = urls + [s:sub(s:sub(self.name(),'^app/stylesheets/','/stylesheets/'),'\.less$','.css')] - elseif self.name() =~ '^app/scripts/' - let urls = urls + [s:sub(s:sub(self.name(),'^app/scripts/','/javascripts/'),'\.coffee$','.js')] - 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 <buffer> <silent> q :bwipe<CR> - 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(<bang>0,<f-args>) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_generate Rgenerate :call rails#app().generate_command(<bang>0,<f-args>) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_destroy Rdestroy :call rails#app().destroy_command(<bang>0,<f-args>) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_server Rserver :call rails#app().server_command(<bang>0,<q-args>) - command! -buffer -bang -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rrunner :call rails#app().runner_command(<bang>0 ? -2 : (<count>==<line2>?<count>:-1),<f-args>) - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rp :call rails#app().runner_command(<count>==<line2>?<count>:-1,'p begin '.<f-args>.' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rpp :call rails#app().runner_command(<count>==<line2>?<count>:-1,'require %{pp}; pp begin '.<f-args>.' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Ry :call rails#app().runner_command(<count>==<line2>?<count>:-1,'y begin '.<f-args>.' 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_script_command(cmd.str) - else - return self.execute_script_command(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")) || (exists("$TMUX") && !has("gui_running") && screen && executable("tmux")) - call self.background_script_command('server '.a:arg) - else - " --daemon would be more descriptive but lighttpd does not support it - call self.execute_script_command('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_script_command('destroy') - elseif a:0 == 1 - return self.execute_script_command('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_script_command('destroy'.str) - call self.cache.clear('user_classes') -endfunction - -function! s:app_generate_command(bang,...) dict - if a:0 == 0 - return self.execute_script_command('generate') - elseif a:0 == 1 - return self.execute_script_command('generate '.s:rquote(a:1)) - endif - let cmd = join(map(copy(a:000),'s:rquote(v:val)'),' ') - if cmd !~ '-p\>' && cmd !~ '--pretend\>' - let execstr = self.script_shell_command('generate '.cmd.' -p -f') - let res = system(execstr) - let g:res = res - let junk = '\%(\e\[[0-9;]*m\)\=' - let file = matchstr(res,junk.'\s\+\%(create\|force\)'.junk.'\s\+\zs\f\+\.rb\ze\n') - if file == "" - let file = matchstr(res,junk.'\s\+\%(identical\)'.junk.'\s\+\zs\f\+\.rb\ze\n') - endif - else - let file = "" - endif - if !self.execute_script_command('generate '.cmd) && 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+','') - 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\+\%(\w\+:\)\=\zs\w\+\ze\s\+') - if target =~# '^\w*controller$' - return filter(s:controllerList(a:ArgLead,"",""),'v:val !=# "application"') - elseif target ==# 'generator' - return s:completion_filter(map(rails#app().relglob('lib/generators/','*'),'s:sub(v:val,"/$","")')) - elseif target ==# 'helper' - return s:helperList(a:ArgLead,"","") - elseif target ==# 'integration_test' || target ==# 'integration_spec' || target ==# 'feature' - return s:integrationtestList(a:ArgLead,"","") - elseif target ==# 'metal' - return s:metalList(a:ArgLead,"","") - elseif target ==# 'migration' || target ==# 'session_migration' - return s:migrationList(a:ArgLead,"","") - elseif target =~# '^\w*\%(model\|resource\)$' || target =~# '\w*scaffold\%(_controller\)\=$' || target ==# 'mailer' - return s:modelList(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) - 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(<q-args>)` - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rlcd :lcd `=rails#app().path(<q-args>)` - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rfind :call s:warn( 'Rfind has been deprecated in favor of :1R or :find' )|call s:Find(<count>,'<bang>' ,<f-args>) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find REfind :call s:warn('REfind has been deprecated in favor of :1RE or :find')|call s:Find(<count>,'E<bang>',<f-args>) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RSfind :call s:warn('RSfind has been deprecated in favor of :1RS or :find')|call s:Find(<count>,'S<bang>',<f-args>) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RVfind :call s:warn('RVfind has been deprecated in favor of :1RV or :find')|call s:Find(<count>,'V<bang>',<f-args>) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RTfind :call s:warn('RTfind has been deprecated in favor of :1RT or :find')|call s:Find(<count>,'T<bang>',<f-args>) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rsfind :call s:warn('Rsfind has been deprecated in favor of :1RS or :sfind')|<count>RSfind<bang> <args> - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rtabfind :call s:warn('Rtabfind has been deprecated in favor of :1RT or :tabfind')|<count>RTfind<bang> <args> - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit Redit :call s:warn( 'Redit has been deprecated in favor of :R')|call s:Edit(<count>,'<bang>' ,<f-args>) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit REedit :call s:warn('REedit has been deprecated in favor of :RE')|call s:Edit(<count>,'E<bang>',<f-args>) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RSedit :call s:warn('RSedit has been deprecated in favor of :RS')|call s:Edit(<count>,'S<bang>',<f-args>) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RVedit :call s:warn('RVedit has been deprecated in favor of :RV')|call s:Edit(<count>,'V<bang>',<f-args>) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RTedit :call s:warn('RTedit has been deprecated in favor of :RT')|call s:Edit(<count>,'T<bang>',<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_edit RDedit :call s:warn('RDedit has been deprecated in favor of :RD')|call s:Edit(<count>,'<line1>D<bang>',<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related A :call s:Alternate('<bang>', <line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AE :call s:Alternate('E<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AS :call s:Alternate('S<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AV :call s:Alternate('V<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AT :call s:Alternate('T<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AD :call s:Alternate('D<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AN :call s:Related('<bang>' ,<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related R :call s:Related('<bang>' ,<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RE :call s:Related('E<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RS :call s:Related('S<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RV :call s:Related('V<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RT :call s:Related('T<bang>',<line1>,<line2>,<count>,<f-args>) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RD :call s:Related('D<bang>',<line1>,<line2>,<count>,<f-args>) -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*\%(mail\>.*\|respond_to\)\s*\%(\<do\|{\)\s*|\zs\h\k*\ze|' - let end = s:endof(line('.')) - let rline = search(rpat,'',end) - if rline > 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 - return s:autocamelize(sort(keys(seen)),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("<cfile>") != 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*=>\|\<'.a:sym.':\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>.\=',a:repl) -endfunction - -function! s:findfromview(func,repl) - " ( ) ( ) ( \1 ) ( ) - return s:findit('\s*\%(<%\)\==\=\s*\<\%('.a:func.'\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>['."'".'"]\=\s*\%(%>\s*\)\=',a:repl) -endfunction - -function! s:RailsFind() - if filereadable(expand("<cfile>")) - return expand("<cfile>") - endif - - " UGH - let buffer = rails#buffer() - let format = s:format('html') - - let res = s:findit('\v\s*<require\s*\(=\s*File.dirname\(__FILE__\)\s*\+\s*[:'."'".'"](\f+)>.=',expand('%:h').'/\1') - if res != ""|return res.(fnamemodify(res,':e') == '' ? '.rb' : '')|endif - - let res = s:findit('\v<File.dirname\(__FILE__\)\s*\+\s*[:'."'".'"](\f+)>['."'".'"]=',expand('%:h').'\1') - if res != ""|return res|endif - - let res = rails#underscore(s:findit('\v\s*<%(include|extend)\(=\s*<([[:alnum:]_:]+)>','\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() =~ '\<spec/' ? 'spec/'.res : res - endif - - let res = s:findamethod('\%(\w\+\.\)\=resources','app/controllers/\1_controller.rb') - if res != ""|return res|endif - - let res = s:findamethod('\%(\w\+\.\)\=resource','app/controllers/\1') - if res != ""|return rails#pluralize(res)."_controller.rb"|endif - - let res = s:findasymbol('to','app/controllers/\1') - if res =~ '#'|return s:sub(res,'#','_controller.rb#')|endif - - let res = s:findamethod('root\s*\%(:to\s*=>\|\<to:\)\s*','app/controllers/\1') - if res =~ '#'|return s:sub(res,'#','_controller.rb#')|endif - - let res = s:findamethod('\%(match\|get\|put\|post\|delete\|redirect\)\s*(\=\s*[:''"][^''"]*[''"]\=\s*\%(\%(,\s*:to\s*\)\==>\|,\s*to:\)\s*','app/controllers/\1') - if res =~ '#'|return s:sub(res,'#','_controller.rb#')|endif - - let res = s:findamethod('layout','\=s:findlayout(submatch(1))') - if res != ""|return res|endif - - let res = s:findasymbol('layout','\=s:findlayout(submatch(1))') - if res != ""|return res|endif - - let res = s:findamethod('helper','app/helpers/\1_helper.rb') - if res != ""|return res|endif - - let res = s:findasymbol('controller','app/controllers/\1_controller.rb') - if res != ""|return res|endif - - let res = s:findasymbol('action','\1') - if res != ""|return res|endif - - let res = s:findasymbol('template','app/views/\1') - if res != ""|return res|endif - - let res = s:sub(s:sub(s:findasymbol('partial','\1'),'^/',''),'[^/]+$','_&') - if res != ""|return res."\n".s:findview(res)|endif - - let res = s:sub(s:sub(s:findfromview('render\s*(\=\s*\%(:partial\s\+=>\|partial:\)\s*','\1'),'^/',''),'[^/]+$','_&') - if res != ""|return res."\n".s:findview(res)|endif - - let res = s:findamethod('render\>\s*\%(:\%(template\|action\)\s\+=>\|template:\|action:\)\s*','\1.'.format.'\n\1') - if res != ""|return res|endif - - let res = s:sub(s:findfromview('render','\1'),'^/','') - if buffer.type_name('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\+=>\|\<action:\)\s*','\1') - if res != ""|return res|endif - - let res = s:findfromview('stylesheet_link_tag','public/stylesheets/\1') - if res != '' && fnamemodify(res, ':e') == '' " Append the default extension iff the filename doesn't already contains an extension - let res .= '.css' - end - if res != ""|return res|endif - - let res = s:sub(s:findfromview('javascript_include_tag','public/javascripts/\1'),'/defaults>','/application') - if res != '' && fnamemodify(res, ':e') == '' " Append the default extension iff the filename doesn't already contains an extension - let res .= '.js' - end - if res != ""|return res|endif - - if buffer.type_name('controller') - let contr = s:controller() - let view = s:findit('\s*\<def\s\+\(\k\+\)\>(\=','/\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("<cfile>") - 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 #<Object:0x...> style output - let str = s:gsub(str,"[\"']",'') - if line =~# '\<\(require\|load\)\s*(\s*$' - return str - elseif str =~# '^\l\w*#\w\+$' - return 'app/controllers/'.s:sub(str,'#','_controller.rb#') - 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,'[^/]+$','_&') - let str = s:findview(str) - elseif line =~# '\<layout\s*(\=\s*' || line =~# ':layout\s*=>\s*' - let str = s:findview(s:sub(str,'^/=','layouts/')) - elseif line =~# ':controller\s*=>\s*' - let str = 'app/controllers/'.str.'_controller.rb' - elseif line =~# '\<helper\s*(\=\s*' - let str = 'app/helpers/'.str.'_helper.rb' - elseif line =~# '\<fixtures\s*(\='.fpat - if RailsFilePath() =~# '\<spec/' - let str = s:sub(str,'^/@!','spec/fixtures/') - else - let str = s:sub(str,'^/@!','test/fixtures/') - endif - elseif line =~# '\<stylesheet_\(link_tag\|path\)\s*(\='.fpat - let str = s:sub(str,'^/@!','/stylesheets/') - if str != '' && fnamemodify(str, ':e') == '' - let str .= '.css' - endif - elseif line =~# '\<javascript_\(include_tag\|path\)\s*(\='.fpat - if str ==# "defaults" - let str = "application" - endif - let str = s:sub(str,'^/@!','/javascripts/') - if str != '' && fnamemodify(str, ':e') == '' - let str .= '.js' - endif - elseif line =~# '\<\(has_one\|belongs_to\)\s*(\=\s*' - let str = 'app/models/'.str.'.rb' - elseif line =~# '\<has_\(and_belongs_to_\)\=many\s*(\=\s*' - let str = 'app/models/'.rails#singularize(str).'.rb' - elseif line =~# '\<def\s\+' && expand("%:t") =~# '_controller\.rb' - let str = s:findview(str) - elseif str =~# '_\%(path\|url\)$' || (line =~# ':as\s*=>\s*$' && rails#buffer().type_name('config-routes')) - if line !~# ':as\s*=>\s*$' - let str = s:sub(str,'_%(path|url)$','') - let str = s:sub(str,'^hash_for_','') - endif - let file = rails#app().named_route_file(str) - if file == "" - let str = s:sub(str,'^formatted_','') - if str =~# '^\%(new\|edit\)_' - let str = 'app/controllers/'.s:sub(rails#pluralize(str),'^(new|edit)_(.*)','\2_controller.rb#\1') - elseif str ==# rails#singularize(str) - " If the word can't be singularized, it's probably a link to the show - " method. We should verify by checking for an argument, but that's - " difficult the way things here are currently structured. - let str = 'app/controllers/'.rails#pluralize(str).'_controller.rb#show' - else - let str = 'app/controllers/'.str.'_controller.rb#index' - endif - else - let str = file - endif - elseif str !~ '/' - " If we made it this far, we'll risk making it singular. - let str = rails#singularize(str) - let str = s:sub(str,'_id$','') - endif - if str =~ '^/' && !filereadable(str) - let str = s:sub(str,'^/','') - endif - if str =~# '^lib/' && !filereadable(str) - let str = s:sub(str,'^lib/','') - endif - return str -endfunction - -" }}}1 -" File Finders {{{1 - -function! s:addfilecmds(type) - let l = s:sub(a:type,'^.','\l&') - let cmds = 'ESVTD ' - let cmd = '' - while cmds != '' - let cplt = " -complete=customlist,".s:sid.l."List" - exe "command! -buffer -bar ".(cmd == 'D' ? '-range=0 ' : '')."-nargs=*".cplt." R".cmd.l." :call s:".l.'Edit("'.(cmd == 'D' ? '<line1>' : '').cmd.'<bang>",<f-args>)' - let cmd = strpart(cmds,0,1) - let cmds = strpart(cmds,1) - endwhile -endfunction - -function! s:BufFinderCommands() - command! -buffer -bar -nargs=+ Rnavcommand :call s:Navcommand(<bang>0,<f-args>) - call s:addfilecmds("metal") - call s:addfilecmds("model") - call s:addfilecmds("view") - call s:addfilecmds("controller") - call s:addfilecmds("mailer") - 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:mailerList(A,L,P) - return s:autocamelize(rails#app().relglob("app/mailers/","**/*",".rb"),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) - let list = rails#app().relglob('app/assets/stylesheets/','**/*.*','') - call map(list,'s:sub(v:val,"\\..*$","")') - let list += rails#app().relglob('public/stylesheets/','**/*','.css') - if rails#app().has('sass') - call extend(list,rails#app().relglob('public/stylesheets/sass/','**/*','.s?ss')) - call s:uniq(list) - endif - return s:completion_filter(list,a:A) -endfunction - -function! s:javascriptList(A,L,P) - let list = rails#app().relglob('app/assets/javascripts/','**/*.*','') - call map(list,'s:sub(v:val,"\\..*$","")') - let list += rails#app().relglob("public/javascripts/","**/*",".js") - return s:completion_filter(list,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") - let found += rails#app().relglob("spec/mailers/","**/*","_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/requests/","**/*","_spec.rb") - 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() =~ '\<vendor/plugins/.' - let path = s:sub(RailsFilePath(),'<vendor/plugins/[^/]*/\zs.*','') - let all = rails#app().relglob(path."tasks/","**/*",".rake")+rails#app().relglob(path."lib/tasks/","**/*",".rake")+all - endif - return s:autocamelize(all,a:A) -endfunction - -function! s:libList(A,L,P) - let all = rails#app().relglob('lib/',"**/*",".rb") - if RailsFilePath() =~ '\<vendor/plugins/.' - let path = s:sub(RailsFilePath(),'<vendor/plugins/[^/]*/\zs.*','lib/') - let all = rails#app().relglob(path,"**/*",".rb") + all - endif - return s:autocamelize(all,a:A) -endfunction - -function! s:environmentList(A,L,P) - return s:completion_filter(rails#app().relglob("config/environments/","**/*",".rb"),a:A) -endfunction - -function! s:initializerList(A,L,P) - return s:completion_filter(rails#app().relglob("config/initializers/","**/*",".rb"),a:A) -endfunction - -function! s:Navcommand(bang,...) - let suffix = ".rb" - let filter = "**/*" - let prefix = "" - let default = "" - let name = "" - let i = 0 - while i < a:0 - let i += 1 - let arg = a:{i} - if arg =~# '^-suffix=' - let suffix = matchstr(arg,'-suffix=\zs.*') - elseif arg =~# '^-default=' - let default = matchstr(arg,'-default=\zs.*') - elseif arg =~# '^-\%(glob\|filter\)=' - let filter = matchstr(arg,'-\w*=\zs.*') - elseif arg !~# '^-' - " A literal '\n'. For evaluation below - if name == "" - let name = arg - else - let prefix .= "\\n".s:sub(arg,'/=$','/') - endif - endif - endwhile - let prefix = s:sub(prefix,'^\\n','') - if name !~ '^[A-Za-z]\+$' - return s:error("E182: Invalid command name") - endif - let cmds = 'ESVTD ' - let cmd = '' - while cmds != '' - exe 'command! -buffer -bar -bang -nargs=* -complete=customlist,'.s:sid.'CommandList R'.cmd.name." :call s:CommandEdit('".cmd."<bang>','".name."',\"".prefix."\",".string(suffix).",".string(filter).",".string(default).",<f-args>)" - 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 files = split(glob(self.path('db/migrate/').glob),"\n") - if arg == '' - return get(files,-1,'') - endif - call map(files,'strpart(v:val,1+strlen(self.path()))') - let keep = get(files,0,'') - if glob =~# '^\*.*\*rb' - let pattern = glob[1:-4] - call filter(files,'v:val =~# ''db/migrate/\d\+_''.pattern.''\.rb''') - let keep = get(files,0,keep) - endif - return keep -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 rails#buffer().type_name('controller','mailer') - 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,'p') - 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(rails#buffer().type_name('mailer') ? 'text' : 'html') - if glob(rails#app().path(file.'.'.format).'.*[^~]') != '' - let file .= '.' . format - endif - call s:findedit(a:cmd,file) - endif -endfunction - -function! s:findview(name) - let self = rails#buffer() - let name = a:name - let pre = 'app/views/' - if name !~# '/' - let controller = self.controller_name(1) - if controller != '' - let name = controller.'/'.name - endif - endif - if name =~# '\.\w\+\.\w\+$' || name =~# '\.'.s:viewspattern().'$' - return pre.name - else - for format in ['.'.s:format('html'), ''] - for type in s:view_types - if self.app().has_file(pre.name.format.'.'.type) - return pre.name.format.'.'.type - endif - endfor - endfor - endif - return '' -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 rails#buffer().type_name() =~# '^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:mailerEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"mailer",a:0? a:1 : s:controller(1),"app/mailers/\napp/models/",".rb") -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) - elseif rails#app().has('sass') && rails#app().has_file('public/stylesheets/sass/'.name.'.scss') - return s:EditSimpleRb(a:cmd,"stylesheet",name,"public/stylesheets/sass/",".scss",1) - elseif rails#app().has('lesscss') && rails#app().has_file('app/stylesheets/'.name.'.less') - return s:EditSimpleRb(a:cmd,"stylesheet",name,"app/stylesheets/",".less",1) - else - let types = rails#app().relglob('app/assets/stylesheets/'.name,'.*','') - if !empty(types) - return s:EditSimpleRb(a:cmd,'stylesheet',name,'app/assets/stylesheets/',types[0],1) - else - return s:EditSimpleRb(a:cmd,'stylesheet',name,'public/stylesheets/','.css',1) - endif - endif -endfunction - -function! s:javascriptEdit(cmd,...) - let name = a:0 ? a:1 : s:controller(1) - if rails#app().has('coffee') && rails#app().has_file('app/scripts/'.name.'.coffee') - return s:EditSimpleRb(a:cmd,'javascript',name,'app/scripts/','.coffee',1) - elseif rails#app().has('coffee') && rails#app().has_file('app/scripts/'.name.'.js') - return s:EditSimpleRb(a:cmd,'javascript',name,'app/scripts/','.js',1) - else - let types = rails#app().relglob('app/assets/javascripts/'.name,'.*','') - if !empty(types) - return s:EditSimpleRb(a:cmd,'javascript',name,'app/assets/javascripts/',types[0],1) - else - return s:EditSimpleRb(a:cmd,'javascript',name,'public/javascripts/','.js',1) - endif - endif -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 && rails#buffer().type_name('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','_controller_test.rb']], 'spec': [['spec/controllers/','spec/mailers/'],['_spec.rb','_controller_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 [prefixes, suffixes] in tests - for prefix in prefixes - for suffix in suffixes - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - endif - endfor - endfor - endfor - return s:EditSimpleRb(a:cmd,"functionaltest",f.jump,tests[0][0][0],tests[0][1][0],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 tests = [['test/integration/','_test.rb'], [ 'spec/requests/','_spec.rb'], [ 'spec/integration/','_spec.rb'], [ 'features/','.feature']] - call filter(tests, 'isdirectory(rails#app().path(v:val[0]))') - if empty(tests) - let tests = [['test/integration/','_test.rb']] - 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() =~ '\<vendor/plugins/.' - let plugin = matchstr(RailsFilePath(),'\<vendor/plugins/\zs[^/]*\ze') - let extra = "vendor/plugins/" . plugin . "/\n" - endif - if a:0 - if a:1 =~ '^[^/.]*/\=$' && rails#app().has_file("vendor/plugins/".a:1."/init.rb") - return s:EditSimpleRb(a:cmd,"plugin",s:sub(a:1,'/$',''),"vendor/plugins/","/init.rb") - elseif plugin == "" - call s:edit(cmd,"vendor/plugins/".s:sub(a:1,'\.$','')) - elseif a:1 == "." - call s:findedit(cmd,"vendor/plugins/".plugin) - elseif isdirectory(rails#app().path("vendor/plugins/".matchstr(a:1,'^[^/]*'))) - call s:edit(cmd,"vendor/plugins/".a:1) - else - call s:findedit(cmd,"vendor/plugins/".a:1."\nvendor/plugins/".plugin."/".a:1) - endif - else - call s:findedit(a:cmd,"Gemfile") - endif -endfunction - -function! s:taskEdit(cmd,...) - let plugin = "" - let extra = "" - if RailsFilePath() =~ '\<vendor/plugins/.' - let plugin = matchstr(RailsFilePath(),'\<vendor/plugins/[^/]*') - let extra = plugin."/tasks/\n".plugin."/lib/tasks/\n" - endif - if a:0 - call s:EditSimpleRb(a:cmd,"task",a:1,extra."lib/tasks/",".rake") - else - call s:findedit(a:cmd,(plugin != "" ? plugin."/Rakefile\n" : "")."Rakefile") - endif -endfunction - -function! s:libEdit(cmd,...) - let extra = "" - if RailsFilePath() =~ '\<vendor/plugins/.' - let extra = s:sub(RailsFilePath(),'<vendor/plugins/[^/]*/\zs.*','lib/')."\n" - endif - if a:0 - call s:EditSimpleRb(a:cmd,"lib",a:0? a:1 : "",extra."lib/",".rb") - else - call s:EditSimpleRb(a:cmd,"lib","seeds","db/",".rb") - endif -endfunction - -function! s:environmentEdit(cmd,...) - if a:0 || rails#app().has_file('config/application.rb') - return s:EditSimpleRb(a:cmd,"environment",a:0? a:1 : "../application","config/environments/",".rb") - else - return s:EditSimpleRb(a:cmd,"environment","environment","config/",".rb") - endif -endfunction - -function! s:initializerEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"initializer",a:0? a:1 : "../routes","config/initializers/",".rb") -endfunction - -" }}}1 -" Alternate/Related {{{1 - -function! s:findcmdfor(cmd) - let bang = '' - if a:cmd =~ '\!$' - let bang = '!' - let cmd = s:sub(a:cmd,'\!$','') - else - let cmd = a:cmd - endif - if cmd =~ '^\d' - let num = matchstr(cmd,'^\d\+') - let cmd = s:sub(cmd,'^\d+','') - else - let num = '' - endif - if cmd == '' || cmd == 'E' || cmd == 'F' - return num.'find'.bang - elseif cmd == 'S' - return num.'sfind'.bang - elseif cmd == 'V' - return 'vert '.num.'sfind'.bang - elseif cmd == 'T' - return num.'tabfind'.bang - elseif cmd == 'D' - return num.'read'.bang - else - return num.cmd.bang - endif -endfunction - -function! s:editcmdfor(cmd) - let cmd = s:findcmdfor(a:cmd) - let cmd = s:sub(cmd,'<sfind>','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() - if a:0 && a:1 - let lastmethod = self.last_method(a:1) - if self.type_name('controller','mailer') && lastmethod != "" - let root = s:sub(s:sub(s:sub(f,'/application%(_controller)=\.rb$','/shared_controller.rb'),'/%(controllers|models|mailers)/','/views/'),'%(_controller)=\.rb$','/'.lastmethod) - let format = self.last_format(a:1) - if format == '' - let format = self.type_name('mailer') ? 'text' : 'html' - endif - if glob(self.app().path().'/'.root.'.'.format.'.*[^~]') != '' - return root . '.' . format - else - return root - endif - elseif f =~ '\<config/environments/' - return "config/database.yml#". fnamemodify(f,':t:r') - elseif f =~ '\<config/database\.yml$' - if lastmethod != "" - return "config/environments/".lastmethod.".rb" - else - return "config/application.rb\nconfig/environment.rb" - endif - elseif f =~ '\<config/routes\.rb$' | return "config/database.yml" - elseif f =~ '\<config/\%(application\|environment\)\.rb$' - return "config/routes.rb" - elseif self.type_name('view-layout') - return s:sub(s:sub(f,'/views/','/controllers/'),'/layouts/(\k+)\..*$','/\1_controller.rb') - elseif self.type_name('view') - 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 mailer = s:sub(s:sub(f,'/views/','/mailers/'),'/(\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(mailer,'#.{-}$','')) - return mailer - elseif self.app().has_file(s:sub(model,'#.{-}$','')) || model =~ '_mailer\.rb#' - return model - else - return controller - endif - elseif self.type_name('controller') - return s:sub(s:sub(f,'/controllers/','/helpers/'),'%(_controller)=\.rb$','_helper.rb') - " elseif self.type_name('helper') - " return s:findlayout(s:controller()) - elseif self.type_name('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'),'.{-}<app/models/',''),'/','_')) - endif - return self.app().migration('0#'.table_name) - elseif self.type_name('model-aro') - return s:sub(f,'_observer\.rb$','.rb') - elseif self.type_name('db-schema') - return self.app().migration(1) - endif - endif - if f =~ '\<config/environments/' - return "config/application.rb\nconfig/environment.rb" - elseif f == 'README' - return "config/database.yml" - elseif f =~ '\<config/database\.yml$' | return "config/routes.rb" - elseif f =~ '\<config/routes\.rb$' - return "config/application.rb\nconfig/environment.rb" - elseif f =~ '\<config/\%(application\|environment\)\.rb$' - return "config/database.yml" - elseif f ==# 'Gemfile' - return 'Gemfile.lock' - elseif f ==# 'Gemfile.lock' - return 'Gemfile' - elseif f =~ '\<db/migrate/' - let migrations = sort(self.app().relglob('db/migrate/','*','.rb')) - let me = matchstr(f,'\<db/migrate/\zs.*\ze\.rb$') - if !exists('l:lastmethod') || lastmethod == 'down' - let candidates = reverse(filter(copy(migrations),'v:val < me')) - let migration = "db/migrate/".get(candidates,0,migrations[-1]).".rb" - else - let candidates = filter(copy(migrations),'v:val > me') - let migration = "db/migrate/".get(candidates,0,migrations[0]).".rb" - endif - return migration . (exists('l:lastmethod') && lastmethod != '' ? '#'.lastmethod : '') - elseif f =~ '\<application\.js$' - return "app/helpers/application_helper.rb" - elseif self.type_name('javascript') - return "public/javascripts/application.js" - elseif self.type_name('db/schema') - return self.app().migration('') - elseif self.type_name('view') - let spec1 = fnamemodify(f,':s?\<app/?spec/?')."_spec.rb" - let spec2 = fnamemodify(f,':r:s?\<app/?spec/?')."_spec.rb" - let spec3 = fnamemodify(f,':r:r:s?\<app/?spec/?')."_spec.rb" - if self.app().has_file(spec1) - return spec1 - elseif self.app().has_file(spec2) - return spec2 - elseif self.app().has_file(spec3) - return spec3 - elseif self.app().has('spec') - return spec2 - else - if self.type_name('view-layout') - let dest = fnamemodify(f,':r:s?/layouts\>??').'/layout.'.fnamemodify(f,':e') - else - let dest = f - endif - return s:sub(s:sub(dest,'<app/views/','test/functional/'),'/[^/]*$','_controller_test.rb') - endif - elseif self.type_name('controller-api') - let api = s:sub(s:sub(f,'/controllers/','/apis/'),'_controller\.rb$','_api.rb') - return api - elseif self.type_name('api') - return s:sub(s:sub(f,'/apis/','/controllers/'),'_api\.rb$','_controller.rb') - elseif self.type_name('fixtures') && f =~ '\<spec/' - let file = rails#singularize(fnamemodify(f,":t:r")).'_spec.rb' - return file - elseif self.type_name('fixtures') - let file = rails#singularize(fnamemodify(f,":t:r")).'_test.rb' - return file - elseif f == '' - call s:warn("No filename present") - elseif f =~ '\<test/unit/routing_test\.rb$' - return 'config/routes.rb' - elseif self.type_name('spec-view') - return s:sub(s:sub(f,'<spec/','app/'),'_spec\.rb$','') - elseif fnamemodify(f,":e") == "rb" - let file = fnamemodify(f,":r") - if file =~ '_\%(test\|spec\)$' - let file = s:sub(file,'_%(test|spec)$','.rb') - else - let file .= '_test.rb' - endif - if self.type_name('helper') - return s:sub(file,'<app/helpers/','test/unit/helpers/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'<app/helpers/','spec/helpers/') - elseif self.type_name('model') - return s:sub(file,'<app/models/','test/unit/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'<app/models/','spec/models/') - elseif self.type_name('controller') - return s:sub(file,'<app/controllers/','test/functional/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'app/controllers/','spec/controllers/') - elseif self.type_name('mailer') - return s:sub(file,'<app/m%(ailer|odel)s/','test/unit/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'<app/','spec/') - elseif self.type_name('test-unit') - return s:sub(s:sub(file,'test/unit/helpers/','app/helpers/'),'test/unit/','app/models/')."\n".s:sub(file,'test/unit/','lib/') - elseif self.type_name('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 self.type_name('spec-lib') - return s:sub(file,'<spec/','') - elseif self.type_name('lib') - return s:sub(f, '<lib/(.*)\.rb$', 'test/unit/\1_test.rb')."\n".s:sub(f, '<lib/(.*)\.rb$', 'spec/lib/\1_spec.rb') - elseif self.type_name('spec') - return s:sub(file,'<spec/','app/') - elseif file =~ '\<vendor/.*/lib/' - return s:sub(file,'<vendor/.{-}/\zslib/','test/') - elseif file =~ '\<vendor/.*/test/' - return s:sub(file,'<vendor/.{-}/\zstest/','lib/') - else - return fnamemodify(file,':t')."\n".s:sub(s:sub(f,'\.rb$','_spec.rb'),'^app/','spec/') - endif - else - return "" - endif -endfunction - -call s:add_methods('readable',['related']) - -" }}}1 -" Partial Extraction {{{1 - -function! s:Extract(bang,...) range abort - if a:0 == 0 || a:0 > 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 rails#buffer().type_name('view-layout') - if RailsFilePath() =~ '\<app/views/layouts/application\>' - let curdir = 'app/views/shared' - if file !~ '/' - let file = "shared/" .file - endif - else - let curdir = s:sub(RailsFilePath(),'.*<app/views/layouts/(.*)%(\.\w*)$','app/views/\1') - endif - else - let curdir = fnamemodify(RailsFilePath(),':h') - endif - let curdir = rails_root."/".curdir - let dir = fnamemodify(file,":h") - let fname = fnamemodify(file,":t") - if fnamemodify(fname,":e") == "" - let name = fname - let fname .= ".".matchstr(expand("%:t"),'\.\zs.*') - elseif fnamemodify(fname,":e") !~ '^'.s:viewspattern().'$' - let name = fnamemodify(fname,":r") - let fname .= ".".ext - else - let name = fnamemodify(fname,":r:r") - endif - let var = "@".name - let collection = "" - if dir =~ '^/' - let out = (rails_root).dir."/_".fname - elseif dir == "" || dir == "." - let out = (curdir)."/_".fname - elseif isdirectory(curdir."/".dir) - let out = (curdir)."/".dir."/_".fname - else - let out = (rails_root)."/app/views/".dir."/_".fname - endif - if filereadable(out) && !a:bang - return s:error('E13: File exists (add ! to override)') - endif - if !isdirectory(fnamemodify(out,':h')) - if a:bang - call mkdir(fnamemodify(out,':h'),'p') - else - return s:error('No such directory') - 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\<CR>".fspaces.renderstr."\<CR>.\<CR>" - finally - let &ai = old_ai - endtry - if renderstr =~ '<%' - norm ^6w - else - norm ^5w - endif - let ft = &ft - let shortout = fnamemodify(out,':.') - silent split `=shortout` - silent %delete - let &ft = ft - let @@ = partial - silent put - 0delete - let @@ = buf - if spaces != "" - silent! exe '%substitute/^'.spaces.'//' - endif - silent! exe '%substitute?\%(\w\|[@:"'."'".'-]\)\@<!'.var.'\>?'.name.'?g' - 1 -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 =~ '\<create_table\>' - let add = s:migspc(line)."drop_table".s:mextargs(line,1).s:mkeep(line) - let lnum = s:endof(lnum) - elseif line =~ '\<drop_table\>' - let add = s:sub(line,'<drop_table>\s*\(=\s*([^,){ ]*).*','create_table \1 do |t|'."\n".matchstr(line,'^\s*').'end').s:mkeep(line) - elseif line =~ '\<add_column\>' - let add = s:migspc(line).'remove_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\<remove_column\>' - let add = s:sub(line,'<remove_column>','add_column') - elseif line =~ '\<add_index\>' - 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,'\<add_index\>[^,]*,\s*\zs\%(\[[^]]*\]\|[:"'."'".']\w*["'."'".']\=\)') - if mat != '' - let add = s:sub(add,'\)=$',', :column => '.mat.'&') - endif - endif - let add .= s:mkeep(line) - elseif line =~ '\<remove_index\>' - let add = s:sub(s:sub(line,'<remove_index','add_index'),':column\s*\=\>\s*','') - elseif line =~ '\<rename_\%(table\|column\|index\)\>' - let add = s:sub(line,'<rename_%(table\s*\(=\s*|%(column|index)\s*\(=\s*[^,]*,\s*)\zs([^,]*)(,\s*)([^,]*)','\3\2\1') - elseif line =~ '\<change_column\>' - let add = s:migspc(line).'change_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\<change_column_default\>' - 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 "" - \."action_name atom_feed audio_path audio_tag auto_discovery_link_tag " - \."button_tag button_to button_to_function " - \."cache capture cdata_section check_box check_box_tag collection_select concat content_for content_tag content_tag_for controller controller_name controller_path convert_to_model cookies csrf_meta_tag csrf_meta_tags 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 " - \."email_field email_field_tag escape_javascript escape_once excerpt " - \."favicon_link_tag field_set_tag fields_for file_field file_field_tag flash form_for form_tag " - \."grouped_collection_select grouped_options_for_select " - \."headers hidden_field hidden_field_tag highlight " - \."image_alt image_path image_submit_tag image_tag " - \."j javascript_cdata_section javascript_include_tag javascript_path javascript_tag " - \."l label label_tag link_to link_to_function link_to_if link_to_unless link_to_unless_current localize logger " - \."mail_to " - \."number_field number_field_tag number_to_currency number_to_human number_to_human_size number_to_percentage number_to_phone number_with_delimiter number_with_precision " - \."option_groups_from_collection_for_select options_for_select options_from_collection_for_select " - \."params password_field password_field_tag path_to_audio path_to_image path_to_javascript path_to_stylesheet path_to_video phone_field phone_field_tag pluralize provide " - \."radio_button radio_button_tag range_field range_field_tag raw render request request_forgery_protection_token reset_cycle response " - \."safe_concat safe_join sanitize sanitize_css search_field search_field_tag select select_date select_datetime select_day select_hour select_minute select_month select_second select_tag select_time select_year session simple_format strip_links strip_tags stylesheet_link_tag stylesheet_path submit_tag " - \."t tag telephone_field telephone_field_tag text_area text_area_tag text_field text_field_tag time_ago_in_words time_select time_tag time_zone_options_for_select time_zone_select translate truncate " - \."url_field url_field_tag url_for url_options " - \."video_path video_tag " - \."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 buffer = rails#buffer() - let s:javascript_functions = "$ $$ $A $F $H $R $w jQuery" - 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 buffer.type_name() == '' - syn keyword rubyRailsMethod params request response session headers cookies flash - endif - if buffer.type_name('api') - syn keyword rubyRailsAPIMethod api_method inflect_names - endif - if buffer.type_name() ==# 'model' || buffer.type_name('model-arb') - syn keyword rubyRailsARMethod default_scope named_scope 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 rubyRailsARCallbackMethod around_create around_destroy around_save around_update - syn keyword rubyRailsARCallbackMethod after_commit after_find after_initialize after_rollback after_touch - syn keyword rubyRailsARClassMethod attr_accessible attr_protected attr_readonly establish_connection set_inheritance_column set_locking_column set_primary_key set_sequence_name set_table_name - syn keyword rubyRailsARValidationMethod validate validates 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 buffer.type_name('model-aro') - syn keyword rubyRailsARMethod observe - endif - if buffer.type_name('mailer') - syn keyword rubyRailsMethod logger url_for polymorphic_path polymorphic_url - syn keyword rubyRailsRenderMethod mail render - syn keyword rubyRailsControllerMethod attachments default helper helper_attr helper_method - endif - if buffer.type_name('helper','view') - syn keyword rubyRailsViewMethod polymorphic_path polymorphic_url - exe "syn keyword rubyRailsHelperMethod ".s:gsub(s:helpermethods(),'<%(content_for|select)\s+','') - syn match rubyRailsHelperMethod '\<select\>\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!' - syn match rubyRailsHelperMethod '\<\%(content_for?\=\|current_page?\)' - syn match rubyRailsViewMethod '\.\@<!\<\(h\|html_escape\|u\|url_encode\)\>' - if buffer.type_name('view-partial') - syn keyword rubyRailsMethod local_assigns - endif - elseif buffer.type_name('controller') - syn keyword rubyRailsMethod params request response session headers cookies flash - syn keyword rubyRailsRenderMethod render - syn keyword rubyRailsMethod logger polymorphic_path polymorphic_url - 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 rescue_from - syn keyword rubyRailsRenderMethod head redirect_to render_to_string respond_with - syn match rubyRailsRenderMethod '\<respond_to\>?\@!' - 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 buffer.type_name('db-migration','db-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 rename_index execute - endif - if buffer.type_name('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 !buffer.type_name('test-unit') - syn match rubyRailsTestControllerMethod '\.\@<!\<\%(get\|post\|put\|delete\|head\|process\|assigns\)\>' - syn keyword rubyRailsTestControllerMethod get_via_redirect post_via_redirect put_via_redirect delete_via_redirect request_via_redirect - 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 buffer.type_name('spec') - syn keyword rubyRailsTestMethod describe context it its specify shared_examples_for it_should_behave_like before after around subject fixtures controller_name helper_name - syn match rubyRailsTestMethod '\<let\>!\=' - syn keyword rubyRailsTestMethod violated pending expect double mock mock_model stub_model - syn match rubyRailsTestMethod '\.\@<!\<stub\>!\@!' - if !buffer.type_name('spec-model') - syn match rubyRailsTestControllerMethod '\.\@<!\<\%(get\|post\|put\|delete\|head\|process\|assigns\)\>' - syn keyword rubyRailsTestControllerMethod integrate_views - syn keyword rubyRailsMethod params request response session flash - syn keyword rubyRailsMethod polymorphic_path polymorphic_url - endif - endif - if buffer.type_name('task') - syn match rubyRailsRakeMethod '^\s*\zs\%(task\|file\|namespace\|desc\|before\|after\|on\)\>\%(\s*=\)\@!' - endif - if buffer.type_name('model-awss') - syn keyword rubyRailsMethod member - endif - if buffer.type_name('config-routes') - syn match rubyRailsMethod '\.\zs\%(connect\|named_route\)\>' - syn keyword rubyRailsMethod match get put post delete redirect root resource resources collection member nested scope namespace controller constraints - 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 - - 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 '.&syntax.'RailsUserClass '.classes.' contained containedin=@'.&syntax.'RailsRegions' - endif - if &syntax == 'haml' - exe 'syn cluster hamlRailsRegions contains=hamlRubyCodeIncluded,hamlRubyCode,hamlRubyHash,@hamlEmbeddedRuby,rubyInterpolation' - else - exe 'syn cluster erubyRailsRegions contains=erubyOneLiner,erubyBlock,erubyExpression,rubyInterpolation' - endif - exe 'syn keyword '.&syntax.'RailsHelperMethod '.s:gsub(s:helpermethods(),'<%(content_for|select)\s+','').' contained containedin=@'.&syntax.'RailsRegions' - exe 'syn match '.&syntax.'RailsHelperMethod "\<select\>\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!" contained containedin=@'.&syntax.'RailsRegions' - exe 'syn match '.&syntax.'RailsHelperMethod "\<\%(content_for?\=\|current_page?\)" contained containedin=@'.&syntax.'RailsRegions' - exe 'syn keyword '.&syntax.'RailsMethod debugger polymorphic_path polymorphic_url contained containedin=@'.&syntax.'RailsRegions' - exe 'syn match '.&syntax.'RailsViewMethod "\.\@<!\<\(h\|html_escape\|u\|url_encode\)\>" contained containedin=@'.&syntax.'RailsRegions' - if buffer.type_name('view-partial') - exe 'syn keyword '.&syntax.'RailsMethod local_assigns contained containedin=@'.&syntax.'RailsRegions' - endif - exe 'syn keyword '.&syntax.'RailsRenderMethod render contained containedin=@'.&syntax.'RailsRegions' - exe 'syn case match' - set isk+=$ - exe 'syn keyword javascriptRailsFunction contained '.s:javascript_functions - exe '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 '\.\@<!\<\(h\|html_escape\|u\|url_encode\)\>' 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" || &syntax == "coffee" - " 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 erubyRailsUserClass railsUserClass - hi def link hamlRailsHelperMethod hamlRailsMethod - hi def link hamlRailsViewMethod hamlRailsMethod - hi def link hamlRailsRenderMethod hamlRailsMethod - hi def link hamlRailsMethod railsMethod - hi def link hamlRailsUserMethod railsUserMethod - hi def link hamlRailsUserClass railsUserClass - hi def link railsUserMethod railsMethod - 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() - if has('conceal') - syn match railslogEscape '\e\[[0-9;]*m' conceal - syn match railslogEscapeMN '\e\[[0-9;]*m' conceal nextgroup=railslogModelNum,railslogEscapeMN skipwhite contained - syn match railslogEscapeSQL '\e\[[0-9;]*m' conceal nextgroup=railslogSQL,railslogEscapeSQL skipwhite contained - else - syn match railslogEscape '\e\[[0-9;]*m' - syn match railslogEscapeMN '\e\[[0-9;]*m' nextgroup=railslogModelNum,railslogEscapeMN skipwhite contained - syn match railslogEscapeSQL '\e\[[0-9;]*m' nextgroup=railslogSQL,railslogEscapeSQL skipwhite contained - endif - syn match railslogRender '\%(^\s*\%(\e\[[0-9;]*m\)\=\)\@<=\%(Processing\|Rendering\|Rendered\|Redirected\|Completed\)\>' - syn match railslogComment '^\s*# .*' - syn match railslogModel '\%(^\s*\%(\e\[[0-9;]*m\)\=\)\@<=\u\%(\w\|:\)* \%(Load\%( Including Associations\| IDs For Limited Eager Loading\)\=\|Columns\|Count\|Create\|Update\|Destroy\|Delete all\)\>' skipwhite nextgroup=railslogModelNum,railslogEscapeMN - syn match railslogModel '\%(^\s*\%(\e\[[0-9;]*m\)\=\)\@<=SQL\>' skipwhite nextgroup=railslogModelNum,railslogEscapeMN - syn region railslogModelNum start='(' end=')' contains=railslogNumber contained skipwhite nextgroup=railslogSQL,railslogEscapeSQL - syn match railslogSQL '\u[^\e]*' contained - " Destroy generates multiline SQL, ugh - syn match railslogSQL '\%(^ \%(\e\[[0-9;]*m\)\=\)\@<=\%(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 railslogEscapeMN railslogEscape - hi def link railslogEscapeSQL railslogEscape - hi def link railslogEscape Ignore - 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 -" Mappings {{{1 - -function! s:BufMappings() - nnoremap <buffer> <silent> <Plug>RailsFind :<C-U>call <SID>Find(v:count1,'E')<CR> - nnoremap <buffer> <silent> <Plug>RailsSplitFind :<C-U>call <SID>Find(v:count1,'S')<CR> - nnoremap <buffer> <silent> <Plug>RailsVSplitFind :<C-U>call <SID>Find(v:count1,'V')<CR> - nnoremap <buffer> <silent> <Plug>RailsTabFind :<C-U>call <SID>Find(v:count1,'T')<CR> - if g:rails_mappings - if !hasmapto("<Plug>RailsFind") - nmap <buffer> gf <Plug>RailsFind - endif - if !hasmapto("<Plug>RailsSplitFind") - nmap <buffer> <C-W>f <Plug>RailsSplitFind - endif - if !hasmapto("<Plug>RailsTabFind") - nmap <buffer> <C-W>gf <Plug>RailsTabFind - endif - if exists("$CREAM") - imap <buffer> <C-CR> <C-O><Plug>RailsFind - imap <buffer> <M-[> <C-O><Plug>RailsAlternate - imap <buffer> <M-]> <C-O><Plug>RailsRelated - endif - endif - " SelectBuf you're a dirty hack - let v:errmsg = "" -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({'mysql2': 'mysql', 'postgresql': 'pgsql', 'sqlite3': 'sqlite', 'sqlserver': 'sqlsrv', 'sybase': 'asa', 'oracle': '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'] = '' - if adapter == 'ora' - let dict['srvname'] = s:extractdbvar(out,'database') - else - let dict['srvname'] = s:extractdbvar(out,'host') - endif - 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\<Trusted[_ ]Connection\s*=\s*yes\>' - 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)) && (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 =~ '\<render\s*(\=\s*:partial\s*=>\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 ,'[\"|]','\\&'),'\<','\\<Lt>') - let expn2 = s:gsub(s:gsub(a:0 ? a:1 : '','[\"|]','\\&'),'\<','\\<Lt>') - if a:0 - exe "inoreabbrev <buffer> <silent> ".a:abbr." <C-R>=<SID>selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).",\"".expn2."\")<CR>" - else - exe "inoreabbrev <buffer> <silent> ".a:abbr." <C-R>=<SID>selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).")<CR>" - 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(<bang>0,<f-args>) - " Some of these were cherry picked from the TextMate snippets - if g:rails_abbreviations - let buffer = rails#buffer() - " Limit to the right filetypes. But error on the liberal side - if buffer.type_name('controller','view','helper','test-functional','test-integration') - Rabbrev pa[ params - Rabbrev rq[ request - Rabbrev rs[ response - Rabbrev se[ session - Rabbrev hd[ headers - Rabbrev coo[ 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 buffer.type_name('view','helper') - Rabbrev dotiw distance_of_time_in_words - Rabbrev taiw time_ago_in_words - endif - if buffer.type_name('controller') - Rabbrev re( redirect_to - Rabbrev rea( redirect_to :action\ =>\ - Rabbrev rec( redirect_to :controller\ =>\ - Rabbrev rst( respond_to - endif - if buffer.type_name() ==# 'model' || buffer.type_name('model-arb') - 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 buffer.type_name('db-migration','db-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 buffer.type_name('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 <buffer> <silent> :c <C-R>=<SID>TheCWord()<CR> - 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 AD:: ActionDispatch - Rabbrev AS:: ActiveSupport - Rabbrev AM:: ActionMailer - Rabbrev AO:: ActiveModel - Rabbrev AE:: ActiveResource - 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 <buffer> ".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\<Rset'.pat) - let matend = matchend(lines,'\C\<Rset'.pat) - while mat != "" && cnt < 10 - let mat = s:sub(mat,'\s+$','') - let mat = s:gsub(mat,'\|','\\|') - if mat != '' - silent! exe "Rset <B> ".mat - endif - let mat = matchstr(lines,'\C\<Rset'.pat,matend) - let matend = matchend(lines,'\C\<Rset'.pat,matend) - let cnt += 1 - endwhile -endfunction - -function! s:LocalModelines(lnum) - if !g:rails_modelines - return - endif - let lbeg = s:lastmethodline(a:lnum) - let lend = s:endof(lbeg) - if lbeg == 0 || lend == 0 - return - endif - let lines = "\n" - let lnum = lbeg - while lnum < lend && lnum < lbeg + 5 - let lines .= getline(lnum) . "\n" - let lnum += 1 - endwhile - let pat = '\s\+\zs.\{-\}\ze\%(\n\|\s\s\|#{\@!\|%>\|-->\|$\)' - let cnt = 1 - let mat = matchstr(lines,'\C\<rset'.pat) - let matend = matchend(lines,'\C\<rset'.pat) - while mat != "" && cnt < 10 - let mat = s:sub(mat,'\s+$','') - let mat = s:gsub(mat,'\|','\\|') - if mat != '' - silent! exe "Rset <l> ".mat - endif - let mat = matchstr(lines,'\C\<rset'.pat,matend) - let matend = matchend(lines,'\C\<rset'.pat,matend) - let cnt += 1 - endwhile -endfunction - -" }}}1 -" Detection {{{1 - -function! s:app_source_callback(file) dict - if self.cache.needs('existence') - call self.cache.set('existence',{}) - endif - let cache = self.cache.get('existence') - if !has_key(cache,a:file) - let cache[a:file] = self.has_file(a:file) - endif - if cache[a:file] - sandbox source `=self.path(a:file)` - endif -endfunction - -call s:add_methods('app',['source_callback']) - -function! RailsBufInit(path) - let firsttime = !(exists("b:rails_root") && b:rails_root == a:path) - let b:rails_root = a:path - if !has_key(s:apps,a:path) - let s:apps[a:path] = deepcopy(s:app_prototype) - let s:apps[a:path].root = a:path - endif - let app = s:apps[a:path] - let buffer = rails#buffer() - " Apparently rails#buffer().calculate_file_type() can be slow if the - " underlying file system is slow (even though it doesn't really do anything - " IO related). This caching is a temporary hack; if it doesn't cause - " problems it should probably be refactored. - let b:rails_cached_file_type = buffer.calculate_file_type() - if g:rails_history_size > 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 expand('%:t') =~ '\.yml\.example$' - setlocal filetype=yaml - elseif expand('%:e') =~ '^\%(rjs\|rxml\|builder\)$' - setlocal filetype=ruby - elseif firsttime - " Activate custom syntax - let &syntax = &syntax - endif - if expand('%:e') == 'log' - nnoremap <buffer> <silent> R :checktime<CR> - nnoremap <buffer> <silent> G :checktime<Bar>$<CR> - nnoremap <buffer> <silent> q :bwipe<CR> - setlocal modifiable filetype=railslog noswapfile autoread foldmethod=syntax - if exists('+concealcursor') - setlocal concealcursor=nc conceallevel=2 - else - silent %s/\%(\e\[[0-9;]*m\|\r$\)//ge - endif - setlocal readonly nomodifiable - $ - endif - call s:BufSettings() - call s:BufCommands() - call s:BufAbbreviations() - " 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 = rails#buffer().type_name() - 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 add_dot = self.getvar('&path') =~# '^\.\%(,\|$\)' - 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/requests', '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',(add_dot ? '.,' : '').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.'/tmp/tags') == -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 = '*.'.join(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,.".join(s:view_types,',.')) - let ft = self.getvar('&filetype') - if ft =~ '^\%(e\=ruby\|[yh]aml\|coffee\|css\|s[ac]ss\|lesscss\)$' - 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('&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()) - elseif ft =~# '^eruby\>' - if exists("g:loaded_allml") - 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 - if exists("g:loaded_ragtag") - call self.setvar('ragtag_stylesheet_link_tag', "<%= stylesheet_link_tag '\r' %>") - call self.setvar('ragtag_javascript_include_tag', "<%= javascript_include_tag '\r' %>") - call self.setvar('ragtag_doctype_index', 10) - endif - elseif ft == 'haml' - if exists("g:loaded_allml") - 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 - if exists("g:loaded_ragtag") - call self.setvar('ragtag_stylesheet_link_tag', "= stylesheet_link_tag '\r'") - call self.setvar('ragtag_javascript_include_tag', "= javascript_include_tag '\r'") - call self.setvar('ragtag_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,coffee,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 <SID>xx <SID>xx -let s:sid = s:sub(maparg("<SID>xx"),'xx$','') -unmap <SID>xx -let s:file = expand('<sfile>: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/snipMate.vim b/vim/autoload/snipMate.vim deleted file mode 100644 index 0ad5a58..0000000 --- a/vim/autoload/snipMate.vim +++ /dev/null @@ -1,435 +0,0 @@ -fun! Filename(...) - let filename = expand('%:t:r') - if filename == '' | return a:0 == 2 ? a:2 : '' | endif - return !a:0 || a:1 == '' ? filename : substitute(a:1, '$1', filename, 'g') -endf - -fun s:RemoveSnippet() - unl! g:snipPos s:curPos s:snipLen s:endCol s:endLine s:prevLen - \ s:lastBuf s:oldWord - if exists('s:update') - unl s:startCol s:origWordLen s:update - if exists('s:oldVars') | unl s:oldVars s:oldEndCol | endif - endif - aug! snipMateAutocmds -endf - -fun snipMate#expandSnip(snip, col) - let lnum = line('.') | let col = a:col - - let snippet = s:ProcessSnippet(a:snip) - " Avoid error if eval evaluates to nothing - if snippet == '' | return '' | endif - - " Expand snippet onto current position with the tab stops removed - let snipLines = split(substitute(snippet, '$\d\+\|${\d\+.\{-}}', '', 'g'), "\n", 1) - - let line = getline(lnum) - let afterCursor = strpart(line, col - 1) - " Keep text after the cursor - if afterCursor != "\t" && afterCursor != ' ' - let line = strpart(line, 0, col - 1) - let snipLines[-1] .= afterCursor - else - let afterCursor = '' - " For some reason the cursor needs to move one right after this - if line != '' && col == 1 && &ve != 'all' && &ve != 'onemore' - let col += 1 - endif - endif - - call setline(lnum, line.snipLines[0]) - - " Autoindent snippet according to previous indentation - let indent = matchend(line, '^.\{-}\ze\(\S\|$\)') + 1 - call append(lnum, map(snipLines[1:], "'".strpart(line, 0, indent - 1)."'.v:val")) - - " Open any folds snippet expands into - if &fen | sil! exe lnum.','.(lnum + len(snipLines) - 1).'foldopen' | endif - - let [g:snipPos, s:snipLen] = s:BuildTabStops(snippet, lnum, col - indent, indent) - - if s:snipLen - aug snipMateAutocmds - au CursorMovedI * call s:UpdateChangedSnip(0) - au InsertEnter * call s:UpdateChangedSnip(1) - aug END - let s:lastBuf = bufnr(0) " Only expand snippet while in current buffer - let s:curPos = 0 - let s:endCol = g:snipPos[s:curPos][1] - let s:endLine = g:snipPos[s:curPos][0] - - call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) - let s:prevLen = [line('$'), col('$')] - if g:snipPos[s:curPos][2] != -1 | return s:SelectWord() | endif - else - unl g:snipPos s:snipLen - " Place cursor at end of snippet if no tab stop is given - let newlines = len(snipLines) - 1 - call cursor(lnum + newlines, indent + len(snipLines[-1]) - len(afterCursor) - \ + (newlines ? 0: col - 1)) - endif - return '' -endf - -" Prepare snippet to be processed by s:BuildTabStops -fun s:ProcessSnippet(snip) - let snippet = a:snip - " Evaluate eval (`...`) expressions. - " Backquotes prefixed with a backslash "\" are ignored. - " Using a loop here instead of a regex fixes a bug with nested "\=". - if stridx(snippet, '`') != -1 - while match(snippet, '\(^\|[^\\]\)`.\{-}[^\\]`') != -1 - let snippet = substitute(snippet, '\(^\|[^\\]\)\zs`.\{-}[^\\]`\ze', - \ substitute(eval(matchstr(snippet, '\(^\|[^\\]\)`\zs.\{-}[^\\]\ze`')), - \ "\n\\%$", '', ''), '') - endw - let snippet = substitute(snippet, "\r", "\n", 'g') - let snippet = substitute(snippet, '\\`', '`', 'g') - endif - - " Place all text after a colon in a tab stop after the tab stop - " (e.g. "${#:foo}" becomes "${:foo}foo"). - " This helps tell the position of the tab stops later. - let snippet = substitute(snippet, '${\d\+:\(.\{-}\)}', '&\1', 'g') - - " Update the a:snip so that all the $# become the text after - " the colon in their associated ${#}. - " (e.g. "${1:foo}" turns all "$1"'s into "foo") - let i = 1 - while stridx(snippet, '${'.i) != -1 - let s = matchstr(snippet, '${'.i.':\zs.\{-}\ze}') - if s != '' - let snippet = substitute(snippet, '$'.i, s.'&', 'g') - endif - let i += 1 - endw - - if &et " Expand tabs to spaces if 'expandtab' is set. - return substitute(snippet, '\t', repeat(' ', &sts ? &sts : &sw), 'g') - endif - return snippet -endf - -" Counts occurences of haystack in needle -fun s:Count(haystack, needle) - let counter = 0 - let index = stridx(a:haystack, a:needle) - while index != -1 - let index = stridx(a:haystack, a:needle, index+1) - let counter += 1 - endw - return counter -endf - -" Builds a list of a list of each tab stop in the snippet containing: -" 1.) The tab stop's line number. -" 2.) The tab stop's column number -" (by getting the length of the string between the last "\n" and the -" tab stop). -" 3.) The length of the text after the colon for the current tab stop -" (e.g. "${1:foo}" would return 3). If there is no text, -1 is returned. -" 4.) If the "${#:}" construct is given, another list containing all -" the matches of "$#", to be replaced with the placeholder. This list is -" composed the same way as the parent; the first item is the line number, -" and the second is the column. -fun s:BuildTabStops(snip, lnum, col, indent) - let snipPos = [] - let i = 1 - let withoutVars = substitute(a:snip, '$\d\+', '', 'g') - while stridx(a:snip, '${'.i) != -1 - let beforeTabStop = matchstr(withoutVars, '^.*\ze${'.i.'\D') - let withoutOthers = substitute(withoutVars, '${\('.i.'\D\)\@!\d\+.\{-}}', '', 'g') - - let j = i - 1 - call add(snipPos, [0, 0, -1]) - let snipPos[j][0] = a:lnum + s:Count(beforeTabStop, "\n") - let snipPos[j][1] = a:indent + len(matchstr(withoutOthers, '.*\(\n\|^\)\zs.*\ze${'.i.'\D')) - if snipPos[j][0] == a:lnum | let snipPos[j][1] += a:col | endif - - " Get all $# matches in another list, if ${#:name} is given - if stridx(withoutVars, '${'.i.':') != -1 - let snipPos[j][2] = len(matchstr(withoutVars, '${'.i.':\zs.\{-}\ze}')) - let dots = repeat('.', snipPos[j][2]) - call add(snipPos[j], []) - let withoutOthers = substitute(a:snip, '${\d\+.\{-}}\|$'.i.'\@!\d\+', '', 'g') - while match(withoutOthers, '$'.i.'\(\D\|$\)') != -1 - let beforeMark = matchstr(withoutOthers, '^.\{-}\ze'.dots.'$'.i.'\(\D\|$\)') - call add(snipPos[j][3], [0, 0]) - let snipPos[j][3][-1][0] = a:lnum + s:Count(beforeMark, "\n") - let snipPos[j][3][-1][1] = a:indent + (snipPos[j][3][-1][0] > a:lnum - \ ? len(matchstr(beforeMark, '.*\n\zs.*')) - \ : a:col + len(beforeMark)) - let withoutOthers = substitute(withoutOthers, '$'.i.'\ze\(\D\|$\)', '', '') - endw - endif - let i += 1 - endw - return [snipPos, i - 1] -endf - -fun snipMate#jumpTabStop(backwards) - let leftPlaceholder = exists('s:origWordLen') - \ && s:origWordLen != g:snipPos[s:curPos][2] - if leftPlaceholder && exists('s:oldEndCol') - let startPlaceholder = s:oldEndCol + 1 - endif - - if exists('s:update') - call s:UpdatePlaceholderTabStops() - else - call s:UpdateTabStops() - endif - - " Don't reselect placeholder if it has been modified - if leftPlaceholder && g:snipPos[s:curPos][2] != -1 - if exists('startPlaceholder') - let g:snipPos[s:curPos][1] = startPlaceholder - else - let g:snipPos[s:curPos][1] = col('.') - let g:snipPos[s:curPos][2] = 0 - endif - endif - - let s:curPos += a:backwards ? -1 : 1 - " Loop over the snippet when going backwards from the beginning - if s:curPos < 0 | let s:curPos = s:snipLen - 1 | endif - - if s:curPos == s:snipLen - let sMode = s:endCol == g:snipPos[s:curPos-1][1]+g:snipPos[s:curPos-1][2] - call s:RemoveSnippet() - return sMode ? "\<tab>" : TriggerSnippet() - endif - - call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) - - let s:endLine = g:snipPos[s:curPos][0] - let s:endCol = g:snipPos[s:curPos][1] - let s:prevLen = [line('$'), col('$')] - - return g:snipPos[s:curPos][2] == -1 ? '' : s:SelectWord() -endf - -fun s:UpdatePlaceholderTabStops() - let changeLen = s:origWordLen - g:snipPos[s:curPos][2] - unl s:startCol s:origWordLen s:update - if !exists('s:oldVars') | return | endif - " Update tab stops in snippet if text has been added via "$#" - " (e.g., in "${1:foo}bar$1${2}"). - if changeLen != 0 - let curLine = line('.') - - for pos in g:snipPos - if pos == g:snipPos[s:curPos] | continue | endif - let changed = pos[0] == curLine && pos[1] > s:oldEndCol - let changedVars = 0 - let endPlaceholder = pos[2] - 1 + pos[1] - " Subtract changeLen from each tab stop that was after any of - " the current tab stop's placeholders. - for [lnum, col] in s:oldVars - if lnum > pos[0] | break | endif - if pos[0] == lnum - if pos[1] > col || (pos[2] == -1 && pos[1] == col) - let changed += 1 - elseif col < endPlaceholder - let changedVars += 1 - endif - endif - endfor - let pos[1] -= changeLen * changed - let pos[2] -= changeLen * changedVars " Parse variables within placeholders - " e.g., "${1:foo} ${2:$1bar}" - - if pos[2] == -1 | continue | endif - " Do the same to any placeholders in the other tab stops. - for nPos in pos[3] - let changed = nPos[0] == curLine && nPos[1] > s:oldEndCol - for [lnum, col] in s:oldVars - if lnum > nPos[0] | break | endif - if nPos[0] == lnum && nPos[1] > col - let changed += 1 - endif - endfor - let nPos[1] -= changeLen * changed - endfor - endfor - endif - unl s:endCol s:oldVars s:oldEndCol -endf - -fun s:UpdateTabStops() - let changeLine = s:endLine - g:snipPos[s:curPos][0] - let changeCol = s:endCol - g:snipPos[s:curPos][1] - if exists('s:origWordLen') - let changeCol -= s:origWordLen - unl s:origWordLen - endif - let lnum = g:snipPos[s:curPos][0] - let col = g:snipPos[s:curPos][1] - " Update the line number of all proceeding tab stops if <cr> has - " been inserted. - if changeLine != 0 - let changeLine -= 1 - for pos in g:snipPos - if pos[0] >= lnum - if pos[0] == lnum | let pos[1] += changeCol | endif - let pos[0] += changeLine - endif - if pos[2] == -1 | continue | endif - for nPos in pos[3] - if nPos[0] >= lnum - if nPos[0] == lnum | let nPos[1] += changeCol | endif - let nPos[0] += changeLine - endif - endfor - endfor - elseif changeCol != 0 - " Update the column of all proceeding tab stops if text has - " been inserted/deleted in the current line. - for pos in g:snipPos - if pos[1] >= col && pos[0] == lnum - let pos[1] += changeCol - endif - if pos[2] == -1 | continue | endif - for nPos in pos[3] - if nPos[0] > lnum | break | endif - if nPos[0] == lnum && nPos[1] >= col - let nPos[1] += changeCol - endif - endfor - endfor - endif -endf - -fun s:SelectWord() - let s:origWordLen = g:snipPos[s:curPos][2] - let s:oldWord = strpart(getline('.'), g:snipPos[s:curPos][1] - 1, - \ s:origWordLen) - let s:prevLen[1] -= s:origWordLen - if !empty(g:snipPos[s:curPos][3]) - let s:update = 1 - let s:endCol = -1 - let s:startCol = g:snipPos[s:curPos][1] - 1 - endif - if !s:origWordLen | return '' | endif - let l = col('.') != 1 ? 'l' : '' - if &sel == 'exclusive' - return "\<esc>".l.'v'.s:origWordLen."l\<c-g>" - endif - return s:origWordLen == 1 ? "\<esc>".l.'gh' - \ : "\<esc>".l.'v'.(s:origWordLen - 1)."l\<c-g>" -endf - -" This updates the snippet as you type when text needs to be inserted -" into multiple places (e.g. in "${1:default text}foo$1bar$1", -" "default text" would be highlighted, and if the user types something, -" UpdateChangedSnip() would be called so that the text after "foo" & "bar" -" are updated accordingly) -" -" It also automatically quits the snippet if the cursor is moved out of it -" while in insert mode. -fun s:UpdateChangedSnip(entering) - if exists('g:snipPos') && bufnr(0) != s:lastBuf - call s:RemoveSnippet() - elseif exists('s:update') " If modifying a placeholder - if !exists('s:oldVars') && s:curPos + 1 < s:snipLen - " Save the old snippet & word length before it's updated - " s:startCol must be saved too, in case text is added - " before the snippet (e.g. in "foo$1${2}bar${1:foo}"). - let s:oldEndCol = s:startCol - let s:oldVars = deepcopy(g:snipPos[s:curPos][3]) - endif - let col = col('.') - 1 - - if s:endCol != -1 - let changeLen = col('$') - s:prevLen[1] - let s:endCol += changeLen - else " When being updated the first time, after leaving select mode - if a:entering | return | endif - let s:endCol = col - 1 - endif - - " If the cursor moves outside the snippet, quit it - if line('.') != g:snipPos[s:curPos][0] || col < s:startCol || - \ col - 1 > s:endCol - unl! s:startCol s:origWordLen s:oldVars s:update - return s:RemoveSnippet() - endif - - call s:UpdateVars() - let s:prevLen[1] = col('$') - elseif exists('g:snipPos') - if !a:entering && g:snipPos[s:curPos][2] != -1 - let g:snipPos[s:curPos][2] = -2 - endif - - let col = col('.') - let lnum = line('.') - let changeLine = line('$') - s:prevLen[0] - - if lnum == s:endLine - let s:endCol += col('$') - s:prevLen[1] - let s:prevLen = [line('$'), col('$')] - endif - if changeLine != 0 - let s:endLine += changeLine - let s:endCol = col - endif - - " Delete snippet if cursor moves out of it in insert mode - if (lnum == s:endLine && (col > s:endCol || col < g:snipPos[s:curPos][1])) - \ || lnum > s:endLine || lnum < g:snipPos[s:curPos][0] - call s:RemoveSnippet() - endif - endif -endf - -" This updates the variables in a snippet when a placeholder has been edited. -" (e.g., each "$1" in "${1:foo} $1bar $1bar") -fun s:UpdateVars() - let newWordLen = s:endCol - s:startCol + 1 - let newWord = strpart(getline('.'), s:startCol, newWordLen) - if newWord == s:oldWord || empty(g:snipPos[s:curPos][3]) - return - endif - - let changeLen = g:snipPos[s:curPos][2] - newWordLen - let curLine = line('.') - let startCol = col('.') - let oldStartSnip = s:startCol - let updateTabStops = changeLen != 0 - let i = 0 - - for [lnum, col] in g:snipPos[s:curPos][3] - if updateTabStops - let start = s:startCol - if lnum == curLine && col <= start - let s:startCol -= changeLen - let s:endCol -= changeLen - endif - for nPos in g:snipPos[s:curPos][3][(i):] - " This list is in ascending order, so quit if we've gone too far. - if nPos[0] > lnum | break | endif - if nPos[0] == lnum && nPos[1] > col - let nPos[1] -= changeLen - endif - endfor - if lnum == curLine && col > start - let col -= changeLen - let g:snipPos[s:curPos][3][i][1] = col - endif - let i += 1 - endif - - " "Very nomagic" is used here to allow special characters. - call setline(lnum, substitute(getline(lnum), '\%'.col.'c\V'. - \ escape(s:oldWord, '\'), escape(newWord, '\&'), '')) - endfor - if oldStartSnip != s:startCol - call cursor(0, startCol + s:startCol - oldStartSnip) - endif - - let s:oldWord = newWord - let g:snipPos[s:curPos][2] = newWordLen -endf -" vim:noet:sw=4:ts=4:ft=vim diff --git a/vim/autoload/syntastic.vim b/vim/autoload/syntastic.vim deleted file mode 100644 index a477736..0000000 --- a/vim/autoload/syntastic.vim +++ /dev/null @@ -1,24 +0,0 @@ - -function! syntastic#ErrorBalloonExpr() - if !exists('b:syntastic_balloons') | return '' | endif - return get(b:syntastic_balloons, v:beval_lnum, '') -endfunction - -function! syntastic#HighlightErrors(errors, termfunc, ...) - call clearmatches() - let forcecb = a:0 && a:1 - for item in a:errors - let group = item['type'] == 'E' ? 'SpellBad' : 'SpellCap' - if item['col'] && !forcecb - let lastcol = col([item['lnum'], '$']) - let lcol = min([lastcol, item['col']]) - call matchadd(group, '\%'.item['lnum'].'l\%'.lcol.'c') - else - let term = a:termfunc(item) - if len(term) > 0 - call matchadd(group, '\%' . item['lnum'] . 'l' . term) - endif - endif - endfor -endfunction - diff --git a/vim/autoload/syntastic/c.vim b/vim/autoload/syntastic/c.vim deleted file mode 100644 index c7232df..0000000 --- a/vim/autoload/syntastic/c.vim +++ /dev/null @@ -1,171 +0,0 @@ -if exists("g:loaded_syntastic_c_autoload") - finish -endif -let g:loaded_syntastic_c_autoload = 1 - -let s:save_cpo = &cpo -set cpo&vim - -" initialize c/cpp syntax checker handlers -function! s:Init() - let s:handlers = [] - let s:cflags = {} - - call s:RegHandler('gtk', 'syntastic#c#CheckPKG', - \ ['gtk', 'gtk+-2.0', 'gtk+', 'glib-2.0', 'glib']) - call s:RegHandler('glib', 'syntastic#c#CheckPKG', - \ ['glib', 'glib-2.0', 'glib']) - call s:RegHandler('glade', 'syntastic#c#CheckPKG', - \ ['glade', 'libglade-2.0', 'libglade']) - call s:RegHandler('libsoup', 'syntastic#c#CheckPKG', - \ ['libsoup', 'libsoup-2.4', 'libsoup-2.2']) - call s:RegHandler('webkit', 'syntastic#c#CheckPKG', - \ ['webkit', 'webkit-1.0']) - call s:RegHandler('cairo', 'syntastic#c#CheckPKG', - \ ['cairo', 'cairo']) - call s:RegHandler('pango', 'syntastic#c#CheckPKG', - \ ['pango', 'pango']) - call s:RegHandler('libxml', 'syntastic#c#CheckPKG', - \ ['libxml', 'libxml-2.0', 'libxml']) - call s:RegHandler('freetype', 'syntastic#c#CheckPKG', - \ ['freetype', 'freetype2', 'freetype']) - call s:RegHandler('SDL', 'syntastic#c#CheckPKG', - \ ['sdl', 'sdl']) - call s:RegHandler('opengl', 'syntastic#c#CheckPKG', - \ ['opengl', 'gl']) - call s:RegHandler('ruby', 'syntastic#c#CheckRuby', []) - call s:RegHandler('Python\.h', 'syntastic#c#CheckPython', []) - call s:RegHandler('php\.h', 'syntastic#c#CheckPhp', []) -endfunction - -" search the first 100 lines for include statements that are -" given in the handlers dictionary -function! syntastic#c#SearchHeaders() - let includes = '' - let files = [] - let found = [] - let lines = filter(getline(1, 100), 'v:val =~# "#\s*include"') - - " search current buffer - for line in lines - let file = matchstr(line, '"\zs\S\+\ze"') - if file != '' - call add(files, file) - continue - endif - for handler in s:handlers - if line =~# handler["regex"] - let includes .= call(handler["func"], handler["args"]) - call add(found, handler["regex"]) - break - endif - endfor - endfor - - " search included headers - for hfile in files - if hfile != '' - let filename = expand('%:p:h') . ((has('win32') || has('win64')) ? - \ '\' : '/') . hfile - try - let lines = readfile(filename, '', 100) - catch /E484/ - continue - endtry - let lines = filter(lines, 'v:val =~# "#\s*include"') - for handler in s:handlers - if index(found, handler["regex"]) != -1 - continue - endif - for line in lines - if line =~# handler["regex"] - let includes .= call(handler["func"], handler["args"]) - call add(found, handler["regex"]) - break - endif - endfor - endfor - endif - endfor - - return includes -endfunction - -" try to find library with 'pkg-config' -" search possible libraries from first to last given -" argument until one is found -function! syntastic#c#CheckPKG(name, ...) - if executable('pkg-config') - if !has_key(s:cflags, a:name) - for i in range(a:0) - let l:cflags = system('pkg-config --cflags '.a:000[i]) - " since we cannot necessarily trust the pkg-config exit code - " we have to check for an error output as well - if v:shell_error == 0 && l:cflags !~? 'not found' - let l:cflags = ' '.substitute(l:cflags, "\n", '', '') - let s:cflags[a:name] = l:cflags - return l:cflags - endif - endfor - else - return s:cflags[a:name] - endif - endif - return '' -endfunction - -" try to find PHP includes with 'php-config' -function! syntastic#c#CheckPhp() - if executable('php-config') - if !exists('s:php_flags') - let s:php_flags = system('php-config --includes') - let s:php_flags = ' ' . substitute(s:php_flags, "\n", '', '') - endif - return s:php_flags - endif - return '' -endfunction - -" try to find the ruby headers with 'rbconfig' -function! syntastic#c#CheckRuby() - if executable('ruby') - if !exists('s:ruby_flags') - let s:ruby_flags = system('ruby -r rbconfig -e ' - \ . '''puts Config::CONFIG["archdir"]''') - let s:ruby_flags = substitute(s:ruby_flags, "\n", '', '') - let s:ruby_flags = ' -I' . s:ruby_flags - endif - return s:ruby_flags - endif - return '' -endfunction - -" try to find the python headers with distutils -function! syntastic#c#CheckPython() - if executable('python') - if !exists('s:python_flags') - let s:python_flags = system('python -c ''from distutils import ' - \ . 'sysconfig; import sys; sys.stdout.write(sysconfig.get_python_inc())''') - let s:python_flags = substitute(s:python_flags, "\n", '', '') - let s:python_flags = ' -I' . s:python_flags - endif - return s:python_flags - endif - return '' -endfunction - -" return a handler dictionary object -function! s:RegHandler(regex, function, args) - let handler = {} - let handler["regex"] = a:regex - let handler["func"] = function(a:function) - let handler["args"] = a:args - call add(s:handlers, handler) -endfunction - -call s:Init() - -let &cpo = s:save_cpo -unlet s:save_cpo - -" vim: set et sts=4 sw=4: diff --git a/vim/autoload/tagbar.vim b/vim/autoload/tagbar.vim deleted file mode 100644 index 48ad320..0000000 --- a/vim/autoload/tagbar.vim +++ /dev/null @@ -1,3099 +0,0 @@ -" ============================================================================ -" File: tagbar.vim -" Description: List the current file's tags in a sidebar, ordered by class etc -" Author: Jan Larres <jan@majutsushi.net> -" Licence: Vim licence -" Website: http://majutsushi.github.com/tagbar/ -" Version: 2.3 -" Note: This plugin was heavily inspired by the 'Taglist' plugin by -" Yegappan Lakshmanan and uses a small amount of code from it. -" -" Original taglist copyright notice: -" Permission is hereby granted to use and distribute this code, -" with or without modifications, provided that this copyright -" notice is copied with it. Like anything else that's free, -" taglist.vim is provided *as is* and comes with no warranty of -" any kind, either expressed or implied. In no event will the -" copyright holder be liable for any damamges resulting from the -" use of this software. -" ============================================================================ - -scriptencoding utf-8 - -" Initialization {{{1 - -" Basic init {{{2 - -if !exists('g:tagbar_ctags_bin') - if executable('ctags-exuberant') - let g:tagbar_ctags_bin = 'ctags-exuberant' - elseif executable('exuberant-ctags') - let g:tagbar_ctags_bin = 'exuberant-ctags' - elseif executable('exctags') - let g:tagbar_ctags_bin = 'exctags' - elseif has('macunix') && executable('/usr/local/bin/ctags') - " Homebrew default location - let g:tagbar_ctags_bin = '/usr/local/bin/ctags' - elseif has('macunix') && executable('/opt/local/bin/ctags') - " Macports default location - let g:tagbar_ctags_bin = '/opt/local/bin/ctags' - elseif executable('ctags') - let g:tagbar_ctags_bin = 'ctags' - elseif executable('ctags.exe') - let g:tagbar_ctags_bin = 'ctags.exe' - elseif executable('tags') - let g:tagbar_ctags_bin = 'tags' - else - echomsg 'Tagbar: Exuberant ctags not found, skipping plugin' - finish - endif -else - " reset 'wildignore' temporarily in case *.exe is included in it - let wildignore_save = &wildignore - set wildignore& - - let g:tagbar_ctags_bin = expand(g:tagbar_ctags_bin) - - let &wildignore = wildignore_save - - if !executable(g:tagbar_ctags_bin) - echomsg 'Tagbar: Exuberant ctags not found in specified place,' - \ 'skipping plugin' - finish - endif -endif - -redir => s:ftype_out -silent filetype -redir END -if s:ftype_out !~# 'detection:ON' - echomsg 'Tagbar: Filetype detection is turned off, skipping plugin' - unlet s:ftype_out - finish -endif -unlet s:ftype_out - -let s:icon_closed = g:tagbar_iconchars[0] -let s:icon_open = g:tagbar_iconchars[1] - -let s:type_init_done = 0 -let s:autocommands_done = 0 -let s:checked_ctags = 0 -let s:window_expanded = 0 - -let s:access_symbols = { - \ 'public' : '+', - \ 'protected' : '#', - \ 'private' : '-' -\ } - -let g:loaded_tagbar = 1 - -let s:last_highlight_tline = 0 -let s:debug = 0 -let s:debug_file = '' - -" s:Init() {{{2 -function! s:Init() - if !s:type_init_done - call s:InitTypes() - endif - - if !s:checked_ctags - if !s:CheckForExCtags() - return - endif - endif -endfunction - -" s:InitTypes() {{{2 -function! s:InitTypes() - call s:LogDebugMessage('Initializing types') - - let s:known_types = {} - - " Ant {{{3 - let type_ant = {} - let type_ant.ctagstype = 'ant' - let type_ant.kinds = [ - \ {'short' : 'p', 'long' : 'projects', 'fold' : 0}, - \ {'short' : 't', 'long' : 'targets', 'fold' : 0} - \ ] - let s:known_types.ant = type_ant - " Asm {{{3 - let type_asm = {} - let type_asm.ctagstype = 'asm' - let type_asm.kinds = [ - \ {'short' : 'm', 'long' : 'macros', 'fold' : 0}, - \ {'short' : 't', 'long' : 'types', 'fold' : 0}, - \ {'short' : 'd', 'long' : 'defines', 'fold' : 0}, - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0} - \ ] - let s:known_types.asm = type_asm - " ASP {{{3 - let type_aspvbs = {} - let type_aspvbs.ctagstype = 'asp' - let type_aspvbs.kinds = [ - \ {'short' : 'd', 'long' : 'constants', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 's', 'long' : 'subroutines', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let s:known_types.aspvbs = type_aspvbs - " Awk {{{3 - let type_awk = {} - let type_awk.ctagstype = 'awk' - let type_awk.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.awk = type_awk - " Basic {{{3 - let type_basic = {} - let type_basic.ctagstype = 'basic' - let type_basic.kinds = [ - \ {'short' : 'c', 'long' : 'constants', 'fold' : 0}, - \ {'short' : 'g', 'long' : 'enumerations', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0}, - \ {'short' : 't', 'long' : 'types', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let s:known_types.basic = type_basic - " BETA {{{3 - let type_beta = {} - let type_beta.ctagstype = 'beta' - let type_beta.kinds = [ - \ {'short' : 'f', 'long' : 'fragments', 'fold' : 0}, - \ {'short' : 's', 'long' : 'slots', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'patterns', 'fold' : 0} - \ ] - let s:known_types.beta = type_beta - " C {{{3 - let type_c = {} - let type_c.ctagstype = 'c' - let type_c.kinds = [ - \ {'short' : 'd', 'long' : 'macros', 'fold' : 1}, - \ {'short' : 'p', 'long' : 'prototypes', 'fold' : 1}, - \ {'short' : 'g', 'long' : 'enums', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'enumerators', 'fold' : 0}, - \ {'short' : 't', 'long' : 'typedefs', 'fold' : 0}, - \ {'short' : 's', 'long' : 'structs', 'fold' : 0}, - \ {'short' : 'u', 'long' : 'unions', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'members', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let type_c.sro = '::' - let type_c.kind2scope = { - \ 'g' : 'enum', - \ 's' : 'struct', - \ 'u' : 'union' - \ } - let type_c.scope2kind = { - \ 'enum' : 'g', - \ 'struct' : 's', - \ 'union' : 'u' - \ } - let s:known_types.c = type_c - " C++ {{{3 - let type_cpp = {} - let type_cpp.ctagstype = 'c++' - let type_cpp.kinds = [ - \ {'short' : 'd', 'long' : 'macros', 'fold' : 1}, - \ {'short' : 'p', 'long' : 'prototypes', 'fold' : 1}, - \ {'short' : 'g', 'long' : 'enums', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'enumerators', 'fold' : 0}, - \ {'short' : 't', 'long' : 'typedefs', 'fold' : 0}, - \ {'short' : 'n', 'long' : 'namespaces', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 's', 'long' : 'structs', 'fold' : 0}, - \ {'short' : 'u', 'long' : 'unions', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'members', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let type_cpp.sro = '::' - let type_cpp.kind2scope = { - \ 'g' : 'enum', - \ 'n' : 'namespace', - \ 'c' : 'class', - \ 's' : 'struct', - \ 'u' : 'union' - \ } - let type_cpp.scope2kind = { - \ 'enum' : 'g', - \ 'namespace' : 'n', - \ 'class' : 'c', - \ 'struct' : 's', - \ 'union' : 'u' - \ } - let s:known_types.cpp = type_cpp - " C# {{{3 - let type_cs = {} - let type_cs.ctagstype = 'c#' - let type_cs.kinds = [ - \ {'short' : 'd', 'long' : 'macros', 'fold' : 1}, - \ {'short' : 'f', 'long' : 'fields', 'fold' : 0}, - \ {'short' : 'g', 'long' : 'enums', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'enumerators', 'fold' : 0}, - \ {'short' : 't', 'long' : 'typedefs', 'fold' : 0}, - \ {'short' : 'n', 'long' : 'namespaces', 'fold' : 0}, - \ {'short' : 'i', 'long' : 'interfaces', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 's', 'long' : 'structs', 'fold' : 0}, - \ {'short' : 'E', 'long' : 'events', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'properties', 'fold' : 0} - \ ] - let type_cs.sro = '.' - let type_cs.kind2scope = { - \ 'n' : 'namespace', - \ 'i' : 'interface', - \ 'c' : 'class', - \ 's' : 'struct', - \ 'g' : 'enum' - \ } - let type_cs.scope2kind = { - \ 'namespace' : 'n', - \ 'interface' : 'i', - \ 'class' : 'c', - \ 'struct' : 's', - \ 'enum' : 'g' - \ } - let s:known_types.cs = type_cs - " COBOL {{{3 - let type_cobol = {} - let type_cobol.ctagstype = 'cobol' - let type_cobol.kinds = [ - \ {'short' : 'd', 'long' : 'data items', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'file descriptions', 'fold' : 0}, - \ {'short' : 'g', 'long' : 'group items', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'paragraphs', 'fold' : 0}, - \ {'short' : 'P', 'long' : 'program ids', 'fold' : 0}, - \ {'short' : 's', 'long' : 'sections', 'fold' : 0} - \ ] - let s:known_types.cobol = type_cobol - " DOS Batch {{{3 - let type_dosbatch = {} - let type_dosbatch.ctagstype = 'dosbatch' - let type_dosbatch.kinds = [ - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let s:known_types.dosbatch = type_dosbatch - " Eiffel {{{3 - let type_eiffel = {} - let type_eiffel.ctagstype = 'eiffel' - let type_eiffel.kinds = [ - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'features', 'fold' : 0} - \ ] - let type_eiffel.sro = '.' " Not sure, is nesting even possible? - let type_eiffel.kind2scope = { - \ 'c' : 'class', - \ 'f' : 'feature' - \ } - let type_eiffel.scope2kind = { - \ 'class' : 'c', - \ 'feature' : 'f' - \ } - let s:known_types.eiffel = type_eiffel - " Erlang {{{3 - let type_erlang = {} - let type_erlang.ctagstype = 'erlang' - let type_erlang.kinds = [ - \ {'short' : 'm', 'long' : 'modules', 'fold' : 0}, - \ {'short' : 'd', 'long' : 'macro definitions', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'r', 'long' : 'record definitions', 'fold' : 0} - \ ] - let type_erlang.sro = '.' " Not sure, is nesting even possible? - let type_erlang.kind2scope = { - \ 'm' : 'module' - \ } - let type_erlang.scope2kind = { - \ 'module' : 'm' - \ } - let s:known_types.erlang = type_erlang - " Flex {{{3 - " Vim doesn't support Flex out of the box, this is based on rough - " guesses and probably requires - " http://www.vim.org/scripts/script.php?script_id=2909 - " Improvements welcome! - let type_mxml = {} - let type_mxml.ctagstype = 'flex' - let type_mxml.kinds = [ - \ {'short' : 'v', 'long' : 'global variables', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'properties', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'x', 'long' : 'mxtags', 'fold' : 0} - \ ] - let type_mxml.sro = '.' - let type_mxml.kind2scope = { - \ 'c' : 'class' - \ } - let type_mxml.scope2kind = { - \ 'class' : 'c' - \ } - let s:known_types.mxml = type_mxml - " Fortran {{{3 - let type_fortran = {} - let type_fortran.ctagstype = 'fortran' - let type_fortran.kinds = [ - \ {'short' : 'm', 'long' : 'modules', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'programs', 'fold' : 0}, - \ {'short' : 'k', 'long' : 'components', 'fold' : 0}, - \ {'short' : 't', 'long' : 'derived types and structures', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'common blocks', 'fold' : 0}, - \ {'short' : 'b', 'long' : 'block data', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'entry points', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 's', 'long' : 'subroutines', 'fold' : 0}, - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0}, - \ {'short' : 'n', 'long' : 'namelists', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let type_fortran.sro = '.' " Not sure, is nesting even possible? - let type_fortran.kind2scope = { - \ 'm' : 'module', - \ 'p' : 'program', - \ 'f' : 'function', - \ 's' : 'subroutine' - \ } - let type_fortran.scope2kind = { - \ 'module' : 'm', - \ 'program' : 'p', - \ 'function' : 'f', - \ 'subroutine' : 's' - \ } - let s:known_types.fortran = type_fortran - " HTML {{{3 - let type_html = {} - let type_html.ctagstype = 'html' - let type_html.kinds = [ - \ {'short' : 'f', 'long' : 'JavaScript funtions', 'fold' : 0}, - \ {'short' : 'a', 'long' : 'named anchors', 'fold' : 0} - \ ] - let s:known_types.html = type_html - " Java {{{3 - let type_java = {} - let type_java.ctagstype = 'java' - let type_java.kinds = [ - \ {'short' : 'p', 'long' : 'packages', 'fold' : 1}, - \ {'short' : 'f', 'long' : 'fields', 'fold' : 0}, - \ {'short' : 'g', 'long' : 'enum types', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'enum constants', 'fold' : 0}, - \ {'short' : 'i', 'long' : 'interfaces', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0} - \ ] - let type_java.sro = '.' - let type_java.kind2scope = { - \ 'g' : 'enum', - \ 'i' : 'interface', - \ 'c' : 'class' - \ } - let type_java.scope2kind = { - \ 'enum' : 'g', - \ 'interface' : 'i', - \ 'class' : 'c' - \ } - let s:known_types.java = type_java - " JavaScript {{{3 - " JavaScript is weird -- it does have scopes, but ctags doesn't seem to - " properly generate the information for them, instead it simply uses the - " complete name. So ctags has to be fixed before I can do anything here. - " Alternatively jsctags/doctorjs will be used if available. - let type_javascript = {} - let type_javascript.ctagstype = 'javascript' - let jsctags = s:CheckFTCtags('jsctags', 'javascript') - if jsctags != '' - let type_javascript.kinds = [ - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let type_javascript.sro = '.' - let type_javascript.kind2scope = { - \ 'v' : 'namespace', - \ 'f' : 'namespace' - \ } - let type_javascript.scope2kind = { - \ 'namespace' : 'v' - \ } - let type_javascript.ctagsbin = jsctags - let type_javascript.ctagsargs = '-f -' - else - let type_javascript.kinds = [ - \ {'short' : 'v', 'long' : 'global variables', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'properties', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - endif - let s:known_types.javascript = type_javascript - " Lisp {{{3 - let type_lisp = {} - let type_lisp.ctagstype = 'lisp' - let type_lisp.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.lisp = type_lisp - " Lua {{{3 - let type_lua = {} - let type_lua.ctagstype = 'lua' - let type_lua.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.lua = type_lua - " Make {{{3 - let type_make = {} - let type_make.ctagstype = 'make' - let type_make.kinds = [ - \ {'short' : 'm', 'long' : 'macros', 'fold' : 0} - \ ] - let s:known_types.make = type_make - " Matlab {{{3 - let type_matlab = {} - let type_matlab.ctagstype = 'matlab' - let type_matlab.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.matlab = type_matlab - " Ocaml {{{3 - let type_ocaml = {} - let type_ocaml.ctagstype = 'ocaml' - let type_ocaml.kinds = [ - \ {'short' : 'M', 'long' : 'modules or functors', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'global variables', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'C', 'long' : 'constructors', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'exceptions', 'fold' : 0}, - \ {'short' : 't', 'long' : 'type names', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'r', 'long' : 'structure fields', 'fold' : 0} - \ ] - let type_ocaml.sro = '.' " Not sure, is nesting even possible? - let type_ocaml.kind2scope = { - \ 'M' : 'Module', - \ 'c' : 'class', - \ 't' : 'type' - \ } - let type_ocaml.scope2kind = { - \ 'Module' : 'M', - \ 'class' : 'c', - \ 'type' : 't' - \ } - let s:known_types.ocaml = type_ocaml - " Pascal {{{3 - let type_pascal = {} - let type_pascal.ctagstype = 'pascal' - let type_pascal.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'procedures', 'fold' : 0} - \ ] - let s:known_types.pascal = type_pascal - " Perl {{{3 - let type_perl = {} - let type_perl.ctagstype = 'perl' - let type_perl.kinds = [ - \ {'short' : 'p', 'long' : 'packages', 'fold' : 1}, - \ {'short' : 'c', 'long' : 'constants', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'formats', 'fold' : 0}, - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0}, - \ {'short' : 's', 'long' : 'subroutines', 'fold' : 0} - \ ] - let s:known_types.perl = type_perl - " PHP {{{3 - let type_php = {} - let type_php.ctagstype = 'php' - let type_php.kinds = [ - \ {'short' : 'i', 'long' : 'interfaces', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'd', 'long' : 'constant definitions', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0}, - \ {'short' : 'j', 'long' : 'javascript functions', 'fold' : 0} - \ ] - let s:known_types.php = type_php - " Python {{{3 - let type_python = {} - let type_python.ctagstype = 'python' - let type_python.kinds = [ - \ {'short' : 'i', 'long' : 'imports', 'fold' : 1}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'members', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0} - \ ] - let type_python.sro = '.' - let type_python.kind2scope = { - \ 'c' : 'class', - \ 'f' : 'function', - \ 'm' : 'function' - \ } - let type_python.scope2kind = { - \ 'class' : 'c', - \ 'function' : 'f' - \ } - let s:known_types.python = type_python - " REXX {{{3 - let type_rexx = {} - let type_rexx.ctagstype = 'rexx' - let type_rexx.kinds = [ - \ {'short' : 's', 'long' : 'subroutines', 'fold' : 0} - \ ] - let s:known_types.rexx = type_rexx - " Ruby {{{3 - let type_ruby = {} - let type_ruby.ctagstype = 'ruby' - let type_ruby.kinds = [ - \ {'short' : 'm', 'long' : 'modules', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'F', 'long' : 'singleton methods', 'fold' : 0} - \ ] - let type_ruby.sro = '.' - let type_ruby.kind2scope = { - \ 'c' : 'class', - \ 'm' : 'class' - \ } - let type_ruby.scope2kind = { - \ 'class' : 'c' - \ } - let s:known_types.ruby = type_ruby - " Scheme {{{3 - let type_scheme = {} - let type_scheme.ctagstype = 'scheme' - let type_scheme.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 's', 'long' : 'sets', 'fold' : 0} - \ ] - let s:known_types.scheme = type_scheme - " Shell script {{{3 - let type_sh = {} - let type_sh.ctagstype = 'sh' - let type_sh.kinds = [ - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.sh = type_sh - let s:known_types.csh = type_sh - let s:known_types.zsh = type_sh - " SLang {{{3 - let type_slang = {} - let type_slang.ctagstype = 'slang' - let type_slang.kinds = [ - \ {'short' : 'n', 'long' : 'namespaces', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0} - \ ] - let s:known_types.slang = type_slang - " SML {{{3 - let type_sml = {} - let type_sml.ctagstype = 'sml' - let type_sml.kinds = [ - \ {'short' : 'e', 'long' : 'exception declarations', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'function definitions', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'functor definitions', 'fold' : 0}, - \ {'short' : 's', 'long' : 'signature declarations', 'fold' : 0}, - \ {'short' : 'r', 'long' : 'structure declarations', 'fold' : 0}, - \ {'short' : 't', 'long' : 'type definitions', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'value bindings', 'fold' : 0} - \ ] - let s:known_types.sml = type_sml - " SQL {{{3 - " The SQL ctags parser seems to be buggy for me, so this just uses the - " normal kinds even though scopes should be available. Improvements - " welcome! - let type_sql = {} - let type_sql.ctagstype = 'sql' - let type_sql.kinds = [ - \ {'short' : 'P', 'long' : 'packages', 'fold' : 1}, - \ {'short' : 'c', 'long' : 'cursors', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'F', 'long' : 'record fields', 'fold' : 0}, - \ {'short' : 'L', 'long' : 'block label', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'procedures', 'fold' : 0}, - \ {'short' : 's', 'long' : 'subtypes', 'fold' : 0}, - \ {'short' : 't', 'long' : 'tables', 'fold' : 0}, - \ {'short' : 'T', 'long' : 'triggers', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0}, - \ {'short' : 'i', 'long' : 'indexes', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'events', 'fold' : 0}, - \ {'short' : 'U', 'long' : 'publications', 'fold' : 0}, - \ {'short' : 'R', 'long' : 'services', 'fold' : 0}, - \ {'short' : 'D', 'long' : 'domains', 'fold' : 0}, - \ {'short' : 'V', 'long' : 'views', 'fold' : 0}, - \ {'short' : 'n', 'long' : 'synonyms', 'fold' : 0}, - \ {'short' : 'x', 'long' : 'MobiLink Table Scripts', 'fold' : 0}, - \ {'short' : 'y', 'long' : 'MobiLink Conn Scripts', 'fold' : 0} - \ ] - let s:known_types.sql = type_sql - " Tcl {{{3 - let type_tcl = {} - let type_tcl.ctagstype = 'tcl' - let type_tcl.kinds = [ - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'methods', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'procedures', 'fold' : 0} - \ ] - let s:known_types.tcl = type_tcl - " LaTeX {{{3 - let type_tex = {} - let type_tex.ctagstype = 'tex' - let type_tex.kinds = [ - \ {'short' : 'p', 'long' : 'parts', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'chapters', 'fold' : 0}, - \ {'short' : 's', 'long' : 'sections', 'fold' : 0}, - \ {'short' : 'u', 'long' : 'subsections', 'fold' : 0}, - \ {'short' : 'b', 'long' : 'subsubsections', 'fold' : 0}, - \ {'short' : 'P', 'long' : 'paragraphs', 'fold' : 0}, - \ {'short' : 'G', 'long' : 'subparagraphs', 'fold' : 0} - \ ] - let s:known_types.tex = type_tex - " Vera {{{3 - " Why are variables 'virtual'? - let type_vera = {} - let type_vera.ctagstype = 'vera' - let type_vera.kinds = [ - \ {'short' : 'd', 'long' : 'macros', 'fold' : 1}, - \ {'short' : 'g', 'long' : 'enums', 'fold' : 0}, - \ {'short' : 'T', 'long' : 'typedefs', 'fold' : 0}, - \ {'short' : 'c', 'long' : 'classes', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'enumerators', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'members', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 't', 'long' : 'tasks', 'fold' : 0}, - \ {'short' : 'v', 'long' : 'variables', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'programs', 'fold' : 0} - \ ] - let type_vera.sro = '.' " Nesting doesn't seem to be possible - let type_vera.kind2scope = { - \ 'g' : 'enum', - \ 'c' : 'class', - \ 'v' : 'virtual' - \ } - let type_vera.scope2kind = { - \ 'enum' : 'g', - \ 'class' : 'c', - \ 'virtual' : 'v' - \ } - let s:known_types.vera = type_vera - " Verilog {{{3 - let type_verilog = {} - let type_verilog.ctagstype = 'verilog' - let type_verilog.kinds = [ - \ {'short' : 'c', 'long' : 'constants', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'events', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'modules', 'fold' : 0}, - \ {'short' : 'n', 'long' : 'net data types', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'ports', 'fold' : 0}, - \ {'short' : 'r', 'long' : 'register data types', 'fold' : 0}, - \ {'short' : 't', 'long' : 'tasks', 'fold' : 0} - \ ] - let s:known_types.verilog = type_verilog - " VHDL {{{3 - " The VHDL ctags parser unfortunately doesn't generate proper scopes - let type_vhdl = {} - let type_vhdl.ctagstype = 'vhdl' - let type_vhdl.kinds = [ - \ {'short' : 'P', 'long' : 'packages', 'fold' : 1}, - \ {'short' : 'c', 'long' : 'constants', 'fold' : 0}, - \ {'short' : 't', 'long' : 'types', 'fold' : 0}, - \ {'short' : 'T', 'long' : 'subtypes', 'fold' : 0}, - \ {'short' : 'r', 'long' : 'records', 'fold' : 0}, - \ {'short' : 'e', 'long' : 'entities', 'fold' : 0}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'p', 'long' : 'procedures', 'fold' : 0} - \ ] - let s:known_types.vhdl = type_vhdl - " Vim {{{3 - let type_vim = {} - let type_vim.ctagstype = 'vim' - let type_vim.kinds = [ - \ {'short' : 'v', 'long' : 'variables', 'fold' : 1}, - \ {'short' : 'f', 'long' : 'functions', 'fold' : 0}, - \ {'short' : 'a', 'long' : 'autocommand groups', 'fold' : 1}, - \ {'short' : 'c', 'long' : 'commands', 'fold' : 0}, - \ {'short' : 'm', 'long' : 'maps', 'fold' : 1} - \ ] - let s:known_types.vim = type_vim - " YACC {{{3 - let type_yacc = {} - let type_yacc.ctagstype = 'yacc' - let type_yacc.kinds = [ - \ {'short' : 'l', 'long' : 'labels', 'fold' : 0} - \ ] - let s:known_types.yacc = type_yacc - " }}}3 - - let user_defs = s:GetUserTypeDefs() - for [key, value] in items(user_defs) - if !has_key(s:known_types, key) || - \ (has_key(value, 'replace') && value.replace) - let s:known_types[key] = value - else - call extend(s:known_types[key], value) - endif - endfor - - " Create a dictionary of the kind order for fast - " access in sorting functions - for type in values(s:known_types) - let i = 0 - let type.kinddict = {} - for kind in type.kinds - let type.kinddict[kind.short] = i - let i += 1 - endfor - endfor - - let s:type_init_done = 1 -endfunction - -" s:GetUserTypeDefs() {{{2 -function! s:GetUserTypeDefs() - call s:LogDebugMessage('Initializing user types') - - redir => defs - silent execute 'let g:' - redir END - - let deflist = split(defs, '\n') - call map(deflist, 'substitute(v:val, ''^\S\+\zs.*'', "", "")') - call filter(deflist, 'v:val =~ "^tagbar_type_"') - - let defdict = {} - for defstr in deflist - let type = substitute(defstr, '^tagbar_type_', '', '') - execute 'let defdict["' . type . '"] = g:' . defstr - endfor - - " If the user only specified one of kind2scope and scope2kind use it to - " generate the other one - " Also, transform the 'kind' definitions into dictionary format - for def in values(defdict) - if has_key(def, 'kinds') - let kinds = def.kinds - let def.kinds = [] - for kind in kinds - let kindlist = split(kind, ':') - let kinddict = {'short' : kindlist[0], 'long' : kindlist[1]} - if len(kindlist) == 3 - let kinddict.fold = kindlist[2] - else - let kinddict.fold = 0 - endif - call add(def.kinds, kinddict) - endfor - endif - - if has_key(def, 'kind2scope') && !has_key(def, 'scope2kind') - let def.scope2kind = {} - for [key, value] in items(def.kind2scope) - let def.scope2kind[value] = key - endfor - elseif has_key(def, 'scope2kind') && !has_key(def, 'kind2scope') - let def.kind2scope = {} - for [key, value] in items(def.scope2kind) - let def.kind2scope[value] = key - endfor - endif - endfor - - return defdict -endfunction - -" s:RestoreSession() {{{2 -" Properly restore Tagbar after a session got loaded -function! s:RestoreSession() - call s:LogDebugMessage('Restoring session') - - let tagbarwinnr = bufwinnr('__Tagbar__') - if tagbarwinnr == -1 - " Tagbar wasn't open in the saved session, nothing to do - return - else - let in_tagbar = 1 - if winnr() != tagbarwinnr - execute tagbarwinnr . 'wincmd w' - let in_tagbar = 0 - endif - endif - - call s:Init() - - call s:InitWindow(g:tagbar_autoclose) - - " Leave the Tagbar window and come back so the update event gets triggered - wincmd p - execute tagbarwinnr . 'wincmd w' - - if !in_tagbar - wincmd p - endif -endfunction - -" s:MapKeys() {{{2 -function! s:MapKeys() - call s:LogDebugMessage('Mapping keys') - - nnoremap <script> <silent> <buffer> <2-LeftMouse> - \ :call <SID>JumpToTag(0)<CR> - nnoremap <script> <silent> <buffer> <LeftRelease> - \ <LeftRelease>:call <SID>CheckMouseClick()<CR> - - inoremap <script> <silent> <buffer> <2-LeftMouse> - \ <C-o>:call <SID>JumpToTag(0)<CR> - inoremap <script> <silent> <buffer> <LeftRelease> - \ <LeftRelease><C-o>:call <SID>CheckMouseClick()<CR> - - nnoremap <script> <silent> <buffer> <CR> :call <SID>JumpToTag(0)<CR> - nnoremap <script> <silent> <buffer> p :call <SID>JumpToTag(1)<CR> - nnoremap <script> <silent> <buffer> <Space> :call <SID>ShowPrototype()<CR> - - nnoremap <script> <silent> <buffer> + :call <SID>OpenFold()<CR> - nnoremap <script> <silent> <buffer> <kPlus> :call <SID>OpenFold()<CR> - nnoremap <script> <silent> <buffer> zo :call <SID>OpenFold()<CR> - nnoremap <script> <silent> <buffer> - :call <SID>CloseFold()<CR> - nnoremap <script> <silent> <buffer> <kMinus> :call <SID>CloseFold()<CR> - nnoremap <script> <silent> <buffer> zc :call <SID>CloseFold()<CR> - nnoremap <script> <silent> <buffer> o :call <SID>ToggleFold()<CR> - nnoremap <script> <silent> <buffer> za :call <SID>ToggleFold()<CR> - - nnoremap <script> <silent> <buffer> * :call <SID>SetFoldLevel(99)<CR> - nnoremap <script> <silent> <buffer> <kMultiply> - \ :call <SID>SetFoldLevel(99)<CR> - nnoremap <script> <silent> <buffer> zR :call <SID>SetFoldLevel(99)<CR> - nnoremap <script> <silent> <buffer> = :call <SID>SetFoldLevel(0)<CR> - nnoremap <script> <silent> <buffer> zM :call <SID>SetFoldLevel(0)<CR> - - nnoremap <script> <silent> <buffer> <C-N> - \ :call <SID>GotoNextToplevelTag(1)<CR> - nnoremap <script> <silent> <buffer> <C-P> - \ :call <SID>GotoNextToplevelTag(-1)<CR> - - nnoremap <script> <silent> <buffer> s :call <SID>ToggleSort()<CR> - nnoremap <script> <silent> <buffer> x :call <SID>ZoomWindow()<CR> - nnoremap <script> <silent> <buffer> q :call <SID>CloseWindow()<CR> - nnoremap <script> <silent> <buffer> <F1> :call <SID>ToggleHelp()<CR> -endfunction - -" s:CreateAutocommands() {{{2 -function! s:CreateAutocommands() - call s:LogDebugMessage('Creating autocommands') - - augroup TagbarAutoCmds - autocmd! - autocmd BufEnter __Tagbar__ nested call s:QuitIfOnlyWindow() - autocmd BufUnload __Tagbar__ call s:CleanUp() - autocmd CursorHold __Tagbar__ call s:ShowPrototype() - - autocmd BufWritePost * - \ if line('$') < g:tagbar_updateonsave_maxlines | - \ call s:AutoUpdate(fnamemodify(expand('<afile>'), ':p')) | - \ endif - autocmd BufEnter,CursorHold,FileType * call - \ s:AutoUpdate(fnamemodify(expand('<afile>'), ':p')) - autocmd BufDelete * call - \ s:CleanupFileinfo(fnamemodify(expand('<afile>'), ':p')) - augroup END - - let s:autocommands_done = 1 -endfunction - -" s:CheckForExCtags() {{{2 -" Test whether the ctags binary is actually Exuberant Ctags and not GNU ctags -" (or something else) -function! s:CheckForExCtags() - call s:LogDebugMessage('Checking for Exuberant Ctags') - - let ctags_cmd = s:EscapeCtagsCmd(g:tagbar_ctags_bin, '--version') - if ctags_cmd == '' - return - endif - - let ctags_output = s:ExecuteCtags(ctags_cmd) - - if v:shell_error || ctags_output !~# 'Exuberant Ctags' - echoerr 'Tagbar: Ctags doesn''t seem to be Exuberant Ctags!' - echomsg 'GNU ctags will NOT WORK.' - \ 'Please download Exuberant Ctags from ctags.sourceforge.net' - \ 'and install it in a directory in your $PATH' - \ 'or set g:tagbar_ctags_bin.' - echomsg 'Executed command: "' . ctags_cmd . '"' - if !empty(ctags_output) - echomsg 'Command output:' - for line in split(ctags_output, '\n') - echomsg line - endfor - endif - return 0 - elseif !s:CheckExCtagsVersion(ctags_output) - echoerr 'Tagbar: Exuberant Ctags is too old!' - echomsg 'You need at least version 5.5 for Tagbar to work.' - \ 'Please download a newer version from ctags.sourceforge.net.' - echomsg 'Executed command: "' . ctags_cmd . '"' - if !empty(ctags_output) - echomsg 'Command output:' - for line in split(ctags_output, '\n') - echomsg line - endfor - endif - return 0 - else - let s:checked_ctags = 1 - return 1 - endif -endfunction - -" s:CheckExCtagsVersion() {{{2 -function! s:CheckExCtagsVersion(output) - call s:LogDebugMessage('Checking Exuberant Ctags version') - - if a:output =~ 'Exuberant Ctags Development' - return 1 - endif - - let matchlist = matchlist(a:output, '\vExuberant Ctags (\d+)\.(\d+)') - let major = matchlist[1] - let minor = matchlist[2] - - return major >= 6 || (major == 5 && minor >= 5) -endfunction - -" s:CheckFTCtags() {{{2 -function! s:CheckFTCtags(bin, ftype) - if executable(a:bin) - return a:bin - endif - - if exists('g:tagbar_type_' . a:ftype) - execute 'let userdef = ' . 'g:tagbar_type_' . a:ftype - if has_key(userdef, 'ctagsbin') - return userdef.ctagsbin - else - return '' - endif - endif - - return '' -endfunction - -" Prototypes {{{1 -" Base tag {{{2 -let s:BaseTag = {} - -" s:BaseTag._init() {{{3 -function! s:BaseTag._init(name) dict - let self.name = a:name - let self.fields = {} - let self.fields.line = 0 - let self.path = '' - let self.fullpath = a:name - let self.depth = 0 - let self.parent = {} - let self.tline = -1 - let self.fileinfo = {} -endfunction - -" s:BaseTag.isNormalTag() {{{3 -function! s:BaseTag.isNormalTag() dict - return 0 -endfunction - -" s:BaseTag.isPseudoTag() {{{3 -function! s:BaseTag.isPseudoTag() dict - return 0 -endfunction - -" s:BaseTag.isKindheader() {{{3 -function! s:BaseTag.isKindheader() dict - return 0 -endfunction - -" s:BaseTag.getPrototype() {{{3 -function! s:BaseTag.getPrototype() dict - return '' -endfunction - -" s:BaseTag._getPrefix() {{{3 -function! s:BaseTag._getPrefix() dict - let fileinfo = self.fileinfo - - if has_key(self, 'children') && !empty(self.children) - if fileinfo.tagfolds[self.fields.kind][self.fullpath] - let prefix = s:icon_closed - else - let prefix = s:icon_open - endif - else - let prefix = ' ' - endif - if has_key(self.fields, 'access') - let prefix .= get(s:access_symbols, self.fields.access, ' ') - else - let prefix .= ' ' - endif - - return prefix -endfunction - -" s:BaseTag.initFoldState() {{{3 -function! s:BaseTag.initFoldState() dict - let fileinfo = self.fileinfo - - if s:known_files.has(fileinfo.fpath) && - \ has_key(fileinfo._tagfolds_old[self.fields.kind], self.fullpath) - " The file has been updated and the tag was there before, so copy its - " old fold state - let fileinfo.tagfolds[self.fields.kind][self.fullpath] = - \ fileinfo._tagfolds_old[self.fields.kind][self.fullpath] - elseif self.depth >= fileinfo.foldlevel - let fileinfo.tagfolds[self.fields.kind][self.fullpath] = 1 - else - let fileinfo.tagfolds[self.fields.kind][self.fullpath] = - \ fileinfo.kindfolds[self.fields.kind] - endif -endfunction - -" s:BaseTag.getClosedParentTline() {{{3 -function! s:BaseTag.getClosedParentTline() dict - let tagline = self.tline - let fileinfo = self.fileinfo - - let parent = self.parent - while !empty(parent) - if parent.isFolded() - let tagline = parent.tline - break - endif - let parent = parent.parent - endwhile - - return tagline -endfunction - -" s:BaseTag.isFoldable() {{{3 -function! s:BaseTag.isFoldable() dict - return has_key(self, 'children') && !empty(self.children) -endfunction - -" s:BaseTag.isFolded() {{{3 -function! s:BaseTag.isFolded() dict - return self.fileinfo.tagfolds[self.fields.kind][self.fullpath] -endfunction - -" s:BaseTag.openFold() {{{3 -function! s:BaseTag.openFold() dict - if self.isFoldable() - let self.fileinfo.tagfolds[self.fields.kind][self.fullpath] = 0 - endif -endfunction - -" s:BaseTag.closeFold() {{{3 -function! s:BaseTag.closeFold() dict - let newline = line('.') - - if !empty(self.parent) && self.parent.isKindheader() - " Tag is child of generic 'kind' - call self.parent.closeFold() - let newline = self.parent.tline - elseif self.isFoldable() && !self.isFolded() - " Tag is parent of a scope and is not folded - let self.fileinfo.tagfolds[self.fields.kind][self.fullpath] = 1 - let newline = self.tline - elseif !empty(self.parent) - " Tag is normal child, so close parent - let parent = self.parent - let self.fileinfo.tagfolds[parent.fields.kind][parent.fullpath] = 1 - let newline = parent.tline - endif - - return newline -endfunction - -" s:BaseTag.setFolded() {{{3 -function! s:BaseTag.setFolded(folded) dict - let self.fileinfo.tagfolds[self.fields.kind][self.fullpath] = a:folded -endfunction - -" s:BaseTag.openParents() {{{3 -function! s:BaseTag.openParents() dict - let parent = self.parent - - while !empty(parent) - call parent.openFold() - let parent = parent.parent - endwhile -endfunction - -" Normal tag {{{2 -let s:NormalTag = copy(s:BaseTag) - -" s:NormalTag.New() {{{3 -function! s:NormalTag.New(name) dict - let newobj = copy(self) - - call newobj._init(a:name) - - return newobj -endfunction - -" s:NormalTag.isNormalTag() {{{3 -function! s:NormalTag.isNormalTag() dict - return 1 -endfunction - -" s:NormalTag.str() {{{3 -function! s:NormalTag.str() dict - let fileinfo = self.fileinfo - let typeinfo = s:known_types[fileinfo.ftype] - - let suffix = get(self.fields, 'signature', '') - if has_key(self.fields, 'type') - let suffix .= ' : ' . self.fields.type - elseif has_key(typeinfo, 'kind2scope') && - \ has_key(typeinfo.kind2scope, self.fields.kind) - let suffix .= ' : ' . typeinfo.kind2scope[self.fields.kind] - endif - - return self._getPrefix() . self.name . suffix . "\n" -endfunction - -" s:NormalTag.getPrototype() {{{3 -function! s:NormalTag.getPrototype() dict - return self.prototype -endfunction - -" Pseudo tag {{{2 -let s:PseudoTag = copy(s:BaseTag) - -" s:PseudoTag.New() {{{3 -function! s:PseudoTag.New(name) dict - let newobj = copy(self) - - call newobj._init(a:name) - - return newobj -endfunction - -" s:PseudoTag.isPseudoTag() {{{3 -function! s:PseudoTag.isPseudoTag() dict - return 1 -endfunction - -" s:PseudoTag.str() {{{3 -function! s:PseudoTag.str() dict - let fileinfo = self.fileinfo - let typeinfo = s:known_types[fileinfo.ftype] - - let suffix = get(self.fields, 'signature', '') - if has_key(typeinfo.kind2scope, self.fields.kind) - let suffix .= ' : ' . typeinfo.kind2scope[self.fields.kind] - endif - - return self._getPrefix() . self.name . '*' . suffix -endfunction - -" Kind header {{{2 -let s:KindheaderTag = copy(s:BaseTag) - -" s:KindheaderTag.New() {{{3 -function! s:KindheaderTag.New(name) dict - let newobj = copy(self) - - call newobj._init(a:name) - - return newobj -endfunction - -" s:KindheaderTag.isKindheader() {{{3 -function! s:KindheaderTag.isKindheader() dict - return 1 -endfunction - -" s:KindheaderTag.getPrototype() {{{3 -function! s:KindheaderTag.getPrototype() dict - return self.name . ': ' . - \ self.numtags . ' ' . (self.numtags > 1 ? 'tags' : 'tag') -endfunction - -" s:KindheaderTag.isFoldable() {{{3 -function! s:KindheaderTag.isFoldable() dict - return 1 -endfunction - -" s:KindheaderTag.isFolded() {{{3 -function! s:KindheaderTag.isFolded() dict - return self.fileinfo.kindfolds[self.short] -endfunction - -" s:KindheaderTag.openFold() {{{3 -function! s:KindheaderTag.openFold() dict - let self.fileinfo.kindfolds[self.short] = 0 -endfunction - -" s:KindheaderTag.closeFold() {{{3 -function! s:KindheaderTag.closeFold() dict - let self.fileinfo.kindfolds[self.short] = 1 - return line('.') -endfunction - -" s:KindheaderTag.toggleFold() {{{3 -function! s:KindheaderTag.toggleFold() dict - let fileinfo = s:known_files.getCurrent() - - let fileinfo.kindfolds[self.short] = !fileinfo.kindfolds[self.short] -endfunction - -" File info {{{2 -let s:FileInfo = {} - -" s:FileInfo.New() {{{3 -function! s:FileInfo.New(fname, ftype) dict - let newobj = copy(self) - - " The complete file path - let newobj.fpath = a:fname - - " File modification time - let newobj.mtime = getftime(a:fname) - - " The vim file type - let newobj.ftype = a:ftype - - " List of the tags that are present in the file, sorted according to the - " value of 'g:tagbar_sort' - let newobj.tags = [] - - " Dictionary of the tags, indexed by line number in the file - let newobj.fline = {} - - " Dictionary of the tags, indexed by line number in the tagbar - let newobj.tline = {} - - " Dictionary of the folding state of 'kind's, indexed by short name - let newobj.kindfolds = {} - let typeinfo = s:known_types[a:ftype] - " copy the default fold state from the type info - for kind in typeinfo.kinds - let newobj.kindfolds[kind.short] = - \ g:tagbar_foldlevel == 0 ? 1 : kind.fold - endfor - - " Dictionary of dictionaries of the folding state of individual tags, - " indexed by kind and full path - let newobj.tagfolds = {} - for kind in typeinfo.kinds - let newobj.tagfolds[kind.short] = {} - endfor - - " The current foldlevel of the file - let newobj.foldlevel = g:tagbar_foldlevel - - return newobj -endfunction - -" s:FileInfo.reset() {{{3 -" Reset stuff that gets regenerated while processing a file and save the old -" tag folds -function! s:FileInfo.reset() dict - let self.mtime = getftime(self.fpath) - let self.tags = [] - let self.fline = {} - let self.tline = {} - - let self._tagfolds_old = self.tagfolds - let self.tagfolds = {} - - let typeinfo = s:known_types[self.ftype] - for kind in typeinfo.kinds - let self.tagfolds[kind.short] = {} - endfor -endfunction - -" s:FileInfo.clearOldFolds() {{{3 -function! s:FileInfo.clearOldFolds() dict - if exists('self._tagfolds_old') - unlet self._tagfolds_old - endif -endfunction - -" s:FileInfo.sortTags() {{{3 -function! s:FileInfo.sortTags() dict - if has_key(s:compare_typeinfo, 'sort') - if s:compare_typeinfo.sort - call s:SortTags(self.tags, 's:CompareByKind') - else - call s:SortTags(self.tags, 's:CompareByLine') - endif - elseif g:tagbar_sort - call s:SortTags(self.tags, 's:CompareByKind') - else - call s:SortTags(self.tags, 's:CompareByLine') - endif -endfunction - -" s:FileInfo.openKindFold() {{{3 -function! s:FileInfo.openKindFold(kind) dict - let self.kindfolds[a:kind.short] = 0 -endfunction - -" s:FileInfo.closeKindFold() {{{3 -function! s:FileInfo.closeKindFold(kind) dict - let self.kindfolds[a:kind.short] = 1 -endfunction - -" Known files {{{2 -let s:known_files = { - \ '_current' : {}, - \ '_files' : {} -\ } - -" s:known_files.getCurrent() {{{3 -function! s:known_files.getCurrent() dict - return self._current -endfunction - -" s:known_files.setCurrent() {{{3 -function! s:known_files.setCurrent(fileinfo) dict - let self._current = a:fileinfo -endfunction - -" s:known_files.get() {{{3 -function! s:known_files.get(fname) dict - return get(self._files, a:fname, {}) -endfunction - -" s:known_files.put() {{{3 -" Optional second argument is the filename -function! s:known_files.put(fileinfo, ...) dict - if a:0 == 1 - let self._files[a:1] = a:fileinfo - else - let fname = a:fileinfo.fpath - let self._files[fname] = a:fileinfo - endif -endfunction - -" s:known_files.has() {{{3 -function! s:known_files.has(fname) dict - return has_key(self._files, a:fname) -endfunction - -" s:known_files.rm() {{{3 -function! s:known_files.rm(fname) dict - if s:known_files.has(a:fname) - call remove(self._files, a:fname) - endif -endfunction - -" Window management {{{1 -" s:ToggleWindow() {{{2 -function! s:ToggleWindow() - let tagbarwinnr = bufwinnr("__Tagbar__") - if tagbarwinnr != -1 - call s:CloseWindow() - return - endif - - call s:OpenWindow('') -endfunction - -" s:OpenWindow() {{{2 -function! s:OpenWindow(flags) - let autofocus = a:flags =~# 'f' - let jump = a:flags =~# 'j' - let autoclose = a:flags =~# 'c' - - " If the tagbar window is already open check jump flag - " Also set the autoclose flag if requested - let tagbarwinnr = bufwinnr('__Tagbar__') - if tagbarwinnr != -1 - if winnr() != tagbarwinnr && jump - execute tagbarwinnr . 'wincmd w' - if autoclose - let w:autoclose = autoclose - endif - endif - return - endif - - call s:Init() - - " Expand the Vim window to accomodate for the Tagbar window if requested - if g:tagbar_expand && !s:window_expanded && has('gui_running') - let &columns += g:tagbar_width + 1 - let s:window_expanded = 1 - endif - - let eventignore_save = &eventignore - set eventignore=all - - let openpos = g:tagbar_left ? 'topleft vertical ' : 'botright vertical ' - exe 'silent keepalt ' . openpos . g:tagbar_width . 'split ' . '__Tagbar__' - - let &eventignore = eventignore_save - - call s:InitWindow(autoclose) - - wincmd p - - " Jump back to the tagbar window if autoclose or autofocus is set. Can't - " just stay in it since it wouldn't trigger the update event - if g:tagbar_autoclose || autofocus || g:tagbar_autofocus - let tagbarwinnr = bufwinnr('__Tagbar__') - execute tagbarwinnr . 'wincmd w' - endif -endfunction - -" s:InitWindow() {{{2 -function! s:InitWindow(autoclose) - setlocal noreadonly " in case the "view" mode is used - setlocal buftype=nofile - setlocal bufhidden=hide - setlocal noswapfile - setlocal nobuflisted - setlocal nomodifiable - setlocal filetype=tagbar - setlocal nolist - setlocal nonumber - setlocal nowrap - setlocal winfixwidth - setlocal textwidth=0 - setlocal nocursorline - setlocal nocursorcolumn - - if exists('+relativenumber') - setlocal norelativenumber - endif - - setlocal nofoldenable - setlocal foldcolumn=0 - " Reset fold settings in case a plugin set them globally to something - " expensive. Apparently 'foldexpr' gets executed even if 'foldenable' is - " off, and then for every appended line (like with :put). - setlocal foldmethod& - setlocal foldexpr& - - " Earlier versions have a bug in local, evaluated statuslines - if v:version > 701 || (v:version == 701 && has('patch097')) - setlocal statusline=%!TagbarGenerateStatusline() - else - setlocal statusline=Tagbar - endif - - " Script-local variable needed since compare functions can't - " take extra arguments - let s:compare_typeinfo = {} - - let s:is_maximized = 0 - let s:short_help = 1 - - let w:autoclose = a:autoclose - - if has('balloon_eval') - setlocal balloonexpr=TagbarBalloonExpr() - set ballooneval - endif - - let cpoptions_save = &cpoptions - set cpoptions&vim - - if !hasmapto('JumpToTag', 'n') - call s:MapKeys() - endif - - if !s:autocommands_done - call s:CreateAutocommands() - endif - - let &cpoptions = cpoptions_save -endfunction - -" s:CloseWindow() {{{2 -function! s:CloseWindow() - let tagbarwinnr = bufwinnr('__Tagbar__') - if tagbarwinnr == -1 - return - endif - - let tagbarbufnr = winbufnr(tagbarwinnr) - - if winnr() == tagbarwinnr - if winbufnr(2) != -1 - " Other windows are open, only close the tagbar one - close - wincmd p - endif - else - " Go to the tagbar window, close it and then come back to the - " original window - let curbufnr = bufnr('%') - execute tagbarwinnr . 'wincmd w' - close - " Need to jump back to the original window only if we are not - " already in that window - let winnum = bufwinnr(curbufnr) - if winnr() != winnum - exe winnum . 'wincmd w' - endif - endif - - " If the Vim window has been expanded, and Tagbar is not open in any other - " tabpages, shrink the window again - if s:window_expanded - let tablist = [] - for i in range(tabpagenr('$')) - call extend(tablist, tabpagebuflist(i + 1)) - endfor - - if index(tablist, tagbarbufnr) == -1 - let &columns -= g:tagbar_width + 1 - let s:window_expanded = 0 - endif - endif -endfunction - -" s:ZoomWindow() {{{2 -function! s:ZoomWindow() - if s:is_maximized - execute 'vert resize ' . g:tagbar_width - let s:is_maximized = 0 - else - vert resize - let s:is_maximized = 1 - endif -endfunction - -" Tag processing {{{1 -" s:ProcessFile() {{{2 -" Execute ctags and put the information into a 'FileInfo' object -function! s:ProcessFile(fname, ftype) - call s:LogDebugMessage('ProcessFile called on ' . a:fname) - - if !s:IsValidFile(a:fname, a:ftype) - call s:LogDebugMessage('Not a valid file, returning') - return - endif - - let ctags_output = s:ExecuteCtagsOnFile(a:fname, a:ftype) - - if ctags_output == -1 - call s:LogDebugMessage('Ctags error when processing file') - " put an empty entry into known_files so the error message is only - " shown once - call s:known_files.put({}, a:fname) - return - elseif ctags_output == '' - call s:LogDebugMessage('Ctags output empty') - return - endif - - " If the file has only been updated preserve the fold states, otherwise - " create a new entry - if s:known_files.has(a:fname) - let fileinfo = s:known_files.get(a:fname) - call fileinfo.reset() - else - let fileinfo = s:FileInfo.New(a:fname, a:ftype) - endif - - let typeinfo = s:known_types[a:ftype] - - " Parse the ctags output lines - call s:LogDebugMessage('Parsing ctags output') - let rawtaglist = split(ctags_output, '\n\+') - for line in rawtaglist - " skip comments - if line =~# '^!_TAG_' - continue - endif - - let parts = split(line, ';"') - if len(parts) == 2 " Is a valid tag line - let taginfo = s:ParseTagline(parts[0], parts[1], typeinfo, fileinfo) - let fileinfo.fline[taginfo.fields.line] = taginfo - call add(fileinfo.tags, taginfo) - endif - endfor - - " Process scoped tags - let processedtags = [] - if has_key(typeinfo, 'kind2scope') - call s:LogDebugMessage('Processing scoped tags') - - let scopedtags = [] - let is_scoped = 'has_key(typeinfo.kind2scope, v:val.fields.kind) || - \ has_key(v:val, "scope")' - let scopedtags += filter(copy(fileinfo.tags), is_scoped) - call filter(fileinfo.tags, '!(' . is_scoped . ')') - - call s:AddScopedTags(scopedtags, processedtags, {}, 0, - \ typeinfo, fileinfo) - - if !empty(scopedtags) - echoerr 'Tagbar: ''scopedtags'' not empty after processing,' - \ 'this should never happen!' - \ 'Please contact the script maintainer with an example.' - endif - endif - call s:LogDebugMessage('Number of top-level tags: ' . len(processedtags)) - - " Create a placeholder tag for the 'kind' header for folding purposes - for kind in typeinfo.kinds - - let curtags = filter(copy(fileinfo.tags), - \ 'v:val.fields.kind ==# kind.short') - call s:LogDebugMessage('Processing kind: ' . kind.short . - \ ', number of tags: ' . len(curtags)) - - if empty(curtags) - continue - endif - - let kindtag = s:KindheaderTag.New(kind.long) - let kindtag.short = kind.short - let kindtag.numtags = len(curtags) - let kindtag.fileinfo = fileinfo - - for tag in curtags - let tag.parent = kindtag - endfor - endfor - - if !empty(processedtags) - call extend(fileinfo.tags, processedtags) - endif - - " Clear old folding information from previous file version to prevent leaks - call fileinfo.clearOldFolds() - - " Sort the tags - let s:compare_typeinfo = typeinfo - call fileinfo.sortTags() - - call s:known_files.put(fileinfo) -endfunction - -" s:ExecuteCtagsOnFile() {{{2 -function! s:ExecuteCtagsOnFile(fname, ftype) - call s:LogDebugMessage('ExecuteCtagsOnFile called on ' . a:fname) - - let typeinfo = s:known_types[a:ftype] - - if has_key(typeinfo, 'ctagsargs') - let ctags_args = ' ' . typeinfo.ctagsargs . ' ' - else - let ctags_args = ' -f - ' - let ctags_args .= ' --format=2 ' - let ctags_args .= ' --excmd=pattern ' - let ctags_args .= ' --fields=nksSa ' - let ctags_args .= ' --extra= ' - let ctags_args .= ' --sort=yes ' - - " Include extra type definitions - if has_key(typeinfo, 'deffile') - let ctags_args .= ' --options=' . typeinfo.deffile . ' ' - endif - - let ctags_type = typeinfo.ctagstype - - let ctags_kinds = '' - for kind in typeinfo.kinds - let ctags_kinds .= kind.short - endfor - - let ctags_args .= ' --language-force=' . ctags_type . - \ ' --' . ctags_type . '-kinds=' . ctags_kinds . ' ' - endif - - if has_key(typeinfo, 'ctagsbin') - " reset 'wildignore' temporarily in case *.exe is included in it - let wildignore_save = &wildignore - set wildignore& - let ctags_bin = expand(typeinfo.ctagsbin) - let &wildignore = wildignore_save - else - let ctags_bin = g:tagbar_ctags_bin - endif - - let ctags_cmd = s:EscapeCtagsCmd(ctags_bin, ctags_args, a:fname) - if ctags_cmd == '' - return '' - endif - - let ctags_output = s:ExecuteCtags(ctags_cmd) - - if v:shell_error || ctags_output =~ 'Warning: cannot open source file' - echoerr 'Tagbar: Could not execute ctags for ' . a:fname . '!' - echomsg 'Executed command: "' . ctags_cmd . '"' - if !empty(ctags_output) - call s:LogDebugMessage('Command output:') - call s:LogDebugMessage(ctags_output) - echomsg 'Command output:' - for line in split(ctags_output, '\n') - echomsg line - endfor - endif - return -1 - endif - - call s:LogDebugMessage('Ctags executed successfully') - return ctags_output -endfunction - -" s:ParseTagline() {{{2 -" Structure of a tag line: -" tagname<TAB>filename<TAB>expattern;"fields -" fields: <TAB>name:value -" fields that are always present: kind, line -function! s:ParseTagline(part1, part2, typeinfo, fileinfo) - let basic_info = split(a:part1, '\t') - - let taginfo = s:NormalTag.New(basic_info[0]) - let taginfo.file = basic_info[1] - - " the pattern can contain tabs and thus may have been split up, so join - " the rest of the items together again - let pattern = join(basic_info[2:], "\t") - let start = 2 " skip the slash and the ^ - let end = strlen(pattern) - 1 - if pattern[end - 1] ==# '$' - let end -= 1 - let dollar = '\$' - else - let dollar = '' - endif - let pattern = strpart(pattern, start, end - start) - let taginfo.pattern = '\V\^\C' . pattern . dollar - let prototype = substitute(pattern, '^[[:space:]]\+', '', '') - let prototype = substitute(prototype, '[[:space:]]\+$', '', '') - let taginfo.prototype = prototype - - let fields = split(a:part2, '\t') - let taginfo.fields.kind = remove(fields, 0) - for field in fields - " can't use split() since the value can contain ':' - let delimit = stridx(field, ':') - let key = strpart(field, 0, delimit) - let val = strpart(field, delimit + 1) - if len(val) > 0 - let taginfo.fields[key] = val - endif - endfor - " Needed for jsctags - if has_key(taginfo.fields, 'lineno') - let taginfo.fields.line = taginfo.fields.lineno - endif - - " Make some information easier accessible - if has_key(a:typeinfo, 'scope2kind') - for scope in keys(a:typeinfo.scope2kind) - if has_key(taginfo.fields, scope) - let taginfo.scope = scope - let taginfo.path = taginfo.fields[scope] - - let taginfo.fullpath = taginfo.path . a:typeinfo.sro . - \ taginfo.name - break - endif - endfor - let taginfo.depth = len(split(taginfo.path, '\V' . a:typeinfo.sro)) - endif - - let taginfo.fileinfo = a:fileinfo - - " Needed for folding - try - call taginfo.initFoldState() - catch /^Vim(\a\+):E716:/ " 'Key not present in Dictionary' - " The tag has a 'kind' that doesn't exist in the type definition - echoerr 'Your ctags and Tagbar configurations are out of sync!' - \ 'Please read '':help tagbar-extend''.' - endtry - - return taginfo -endfunction - -" s:AddScopedTags() {{{2 -" Recursively process tags. Unfortunately there is a problem: not all tags in -" a hierarchy are actually there. For example, in C++ a class can be defined -" in a header file and implemented in a .cpp file (so the class itself doesn't -" appear in the .cpp file and thus doesn't generate a tag). Another example -" are anonymous structures like namespaces, structs, enums, and unions, that -" also don't get a tag themselves. These tags are thus called 'pseudo-tags' in -" Tagbar. Properly parsing them is quite tricky, so try not to think about it -" too much. -function! s:AddScopedTags(tags, processedtags, parent, depth, - \ typeinfo, fileinfo) - if !empty(a:parent) - let curpath = a:parent.fullpath - let pscope = a:typeinfo.kind2scope[a:parent.fields.kind] - else - let curpath = '' - let pscope = '' - endif - - let is_cur_tag = 'v:val.depth == a:depth' - - if !empty(curpath) - " Check whether the tag is either a direct child at the current depth - " or at least a proper grandchild with pseudo-tags in between. If it - " is a direct child also check for matching scope. - let is_cur_tag .= ' && - \ (v:val.path ==# curpath || - \ match(v:val.path, ''\V\^\C'' . curpath . a:typeinfo.sro) == 0) && - \ (v:val.path ==# curpath ? (v:val.scope ==# pscope) : 1)' - endif - - let curtags = filter(copy(a:tags), is_cur_tag) - - if !empty(curtags) - call filter(a:tags, '!(' . is_cur_tag . ')') - - let realtags = [] - let pseudotags = [] - - while !empty(curtags) - let tag = remove(curtags, 0) - - if tag.path != curpath - " tag is child of a pseudo-tag, so create a new pseudo-tag and - " add all its children to it - let pseudotag = s:ProcessPseudoTag(curtags, tag, a:parent, - \ a:typeinfo, a:fileinfo) - - call add(pseudotags, pseudotag) - else - call add(realtags, tag) - endif - endwhile - - " Recursively add the children of the tags on the current level - for tag in realtags - let tag.parent = a:parent - - if !has_key(a:typeinfo.kind2scope, tag.fields.kind) - continue - endif - - if !has_key(tag, 'children') - let tag.children = [] - endif - - call s:AddScopedTags(a:tags, tag.children, tag, a:depth + 1, - \ a:typeinfo, a:fileinfo) - endfor - call extend(a:processedtags, realtags) - - " Recursively add the children of the tags that are children of the - " pseudo-tags on the current level - for tag in pseudotags - call s:ProcessPseudoChildren(a:tags, tag, a:depth, a:typeinfo, - \ a:fileinfo) - endfor - call extend(a:processedtags, pseudotags) - endif - - " Now we have to check if there are any pseudo-tags at the current level - " so we have to check for real tags at a lower level, i.e. grandchildren - let is_grandchild = 'v:val.depth > a:depth' - - if !empty(curpath) - let is_grandchild .= - \ ' && match(v:val.path, ''\V\^\C'' . curpath . a:typeinfo.sro) == 0' - endif - - let grandchildren = filter(copy(a:tags), is_grandchild) - - if !empty(grandchildren) - call s:AddScopedTags(a:tags, a:processedtags, a:parent, a:depth + 1, - \ a:typeinfo, a:fileinfo) - endif -endfunction - -" s:ProcessPseudoTag() {{{2 -function! s:ProcessPseudoTag(curtags, tag, parent, typeinfo, fileinfo) - let curpath = !empty(a:parent) ? a:parent.fullpath : '' - - let pseudoname = substitute(a:tag.path, curpath, '', '') - let pseudoname = substitute(pseudoname, '\V\^' . a:typeinfo.sro, '', '') - let pseudotag = s:CreatePseudoTag(pseudoname, a:parent, a:tag.scope, - \ a:typeinfo, a:fileinfo) - let pseudotag.children = [a:tag] - - " get all the other (direct) children of the current pseudo-tag - let ispseudochild = 'v:val.path ==# a:tag.path && v:val.scope ==# a:tag.scope' - let pseudochildren = filter(copy(a:curtags), ispseudochild) - if !empty(pseudochildren) - call filter(a:curtags, '!(' . ispseudochild . ')') - call extend(pseudotag.children, pseudochildren) - endif - - return pseudotag -endfunction - -" s:ProcessPseudoChildren() {{{2 -function! s:ProcessPseudoChildren(tags, tag, depth, typeinfo, fileinfo) - for childtag in a:tag.children - let childtag.parent = a:tag - - if !has_key(a:typeinfo.kind2scope, childtag.fields.kind) - continue - endif - - if !has_key(childtag, 'children') - let childtag.children = [] - endif - - call s:AddScopedTags(a:tags, childtag.children, childtag, a:depth + 1, - \ a:typeinfo, a:fileinfo) - endfor - - let is_grandchild = 'v:val.depth > a:depth && - \ match(v:val.path, ''^\C'' . a:tag.fullpath) == 0' - let grandchildren = filter(copy(a:tags), is_grandchild) - if !empty(grandchildren) - call s:AddScopedTags(a:tags, a:tag.children, a:tag, a:depth + 1, - \ a:typeinfo, a:fileinfo) - endif -endfunction - -" s:CreatePseudoTag() {{{2 -function! s:CreatePseudoTag(name, parent, scope, typeinfo, fileinfo) - if !empty(a:parent) - let curpath = a:parent.fullpath - let pscope = a:typeinfo.kind2scope[a:parent.fields.kind] - else - let curpath = '' - let pscope = '' - endif - - let pseudotag = s:PseudoTag.New(a:name) - let pseudotag.fields.kind = a:typeinfo.scope2kind[a:scope] - - let parentscope = substitute(curpath, a:name . '$', '', '') - let parentscope = substitute(parentscope, - \ '\V\^' . a:typeinfo.sro . '\$', '', '') - - if pscope != '' - let pseudotag.fields[pscope] = parentscope - let pseudotag.scope = pscope - let pseudotag.path = parentscope - let pseudotag.fullpath = - \ pseudotag.path . a:typeinfo.sro . pseudotag.name - endif - let pseudotag.depth = len(split(pseudotag.path, '\V' . a:typeinfo.sro)) - - let pseudotag.parent = a:parent - - let pseudotag.fileinfo = a:fileinfo - - call pseudotag.initFoldState() - - return pseudotag -endfunction - -" Sorting {{{1 -" s:SortTags() {{{2 -function! s:SortTags(tags, comparemethod) - call sort(a:tags, a:comparemethod) - - for tag in a:tags - if has_key(tag, 'children') - call s:SortTags(tag.children, a:comparemethod) - endif - endfor -endfunction - -" s:CompareByKind() {{{2 -function! s:CompareByKind(tag1, tag2) - let typeinfo = s:compare_typeinfo - - if typeinfo.kinddict[a:tag1.fields.kind] <# - \ typeinfo.kinddict[a:tag2.fields.kind] - return -1 - elseif typeinfo.kinddict[a:tag1.fields.kind] ># - \ typeinfo.kinddict[a:tag2.fields.kind] - return 1 - else - " Ignore '~' prefix for C++ destructors to sort them directly under - " the constructors - if a:tag1.name[0] ==# '~' - let name1 = a:tag1.name[1:] - else - let name1 = a:tag1.name - endif - if a:tag2.name[0] ==# '~' - let name2 = a:tag2.name[1:] - else - let name2 = a:tag2.name - endif - - if name1 <=# name2 - return -1 - else - return 1 - endif - endif -endfunction - -" s:CompareByLine() {{{2 -function! s:CompareByLine(tag1, tag2) - return a:tag1.fields.line - a:tag2.fields.line -endfunction - -" s:ToggleSort() {{{2 -function! s:ToggleSort() - let fileinfo = s:known_files.getCurrent() - if empty(fileinfo) - return - endif - - let curline = line('.') - - match none - - let s:compare_typeinfo = s:known_types[fileinfo.ftype] - - if has_key(s:compare_typeinfo, 'sort') - let s:compare_typeinfo.sort = !s:compare_typeinfo.sort - else - let g:tagbar_sort = !g:tagbar_sort - endif - - call fileinfo.sortTags() - - call s:RenderContent() - - execute curline -endfunction - -" Display {{{1 -" s:RenderContent() {{{2 -function! s:RenderContent(...) - call s:LogDebugMessage('RenderContent called') - - if a:0 == 1 - let fileinfo = a:1 - else - let fileinfo = s:known_files.getCurrent() - endif - - if empty(fileinfo) - call s:LogDebugMessage('Empty fileinfo, returning') - return - endif - - let tagbarwinnr = bufwinnr('__Tagbar__') - - if &filetype == 'tagbar' - let in_tagbar = 1 - else - let in_tagbar = 0 - let prevwinnr = winnr() - execute tagbarwinnr . 'wincmd w' - endif - - if !empty(s:known_files.getCurrent()) && - \ fileinfo.fpath ==# s:known_files.getCurrent().fpath - " We're redisplaying the same file, so save the view - call s:LogDebugMessage('Redisplaying file' . fileinfo.fpath) - let saveline = line('.') - let savecol = col('.') - let topline = line('w0') - endif - - let lazyredraw_save = &lazyredraw - set lazyredraw - let eventignore_save = &eventignore - set eventignore=all - - setlocal modifiable - - silent %delete _ - - call s:PrintHelp() - - let typeinfo = s:known_types[fileinfo.ftype] - - " Print tags - call s:PrintKinds(typeinfo, fileinfo) - - " Delete empty lines at the end of the buffer - for linenr in range(line('$'), 1, -1) - if getline(linenr) =~ '^$' - execute 'silent ' . linenr . 'delete _' - else - break - endif - endfor - - setlocal nomodifiable - - if !empty(s:known_files.getCurrent()) && - \ fileinfo.fpath ==# s:known_files.getCurrent().fpath - let scrolloff_save = &scrolloff - set scrolloff=0 - - call cursor(topline, 1) - normal! zt - call cursor(saveline, savecol) - - let &scrolloff = scrolloff_save - else - " Make sure as much of the Tagbar content as possible is shown in the - " window by jumping to the top after drawing - execute 1 - call winline() - - " Invalidate highlight cache from old file - let s:last_highlight_tline = 0 - endif - - let &lazyredraw = lazyredraw_save - let &eventignore = eventignore_save - - if !in_tagbar - execute prevwinnr . 'wincmd w' - endif -endfunction - -" s:PrintKinds() {{{2 -function! s:PrintKinds(typeinfo, fileinfo) - call s:LogDebugMessage('PrintKinds called') - - let first_tag = 1 - - for kind in a:typeinfo.kinds - let curtags = filter(copy(a:fileinfo.tags), - \ 'v:val.fields.kind ==# kind.short') - call s:LogDebugMessage('Printing kind: ' . kind.short . - \ ', number of (top-level) tags: ' . len(curtags)) - - if empty(curtags) - continue - endif - - if has_key(a:typeinfo, 'kind2scope') && - \ has_key(a:typeinfo.kind2scope, kind.short) - " Scoped tags - for tag in curtags - if g:tagbar_compact && first_tag && s:short_help - silent 0put =tag.str() - else - silent put =tag.str() - endif - - " Save the current tagbar line in the tag for easy - " highlighting access - let curline = line('.') - let tag.tline = curline - let a:fileinfo.tline[curline] = tag - - " Print children - if tag.isFoldable() && !tag.isFolded() - for ckind in a:typeinfo.kinds - let childtags = filter(copy(tag.children), - \ 'v:val.fields.kind ==# ckind.short') - if len(childtags) > 0 - " Print 'kind' header of following children - if !has_key(a:typeinfo.kind2scope, ckind.short) - silent put =' [' . ckind.long . ']' - let a:fileinfo.tline[line('.')] = tag - endif - for childtag in childtags - call s:PrintTag(childtag, 1, - \ a:fileinfo, a:typeinfo) - endfor - endif - endfor - endif - - if !g:tagbar_compact - silent put _ - endif - - let first_tag = 0 - endfor - else - " Non-scoped tags - let kindtag = curtags[0].parent - - if kindtag.isFolded() - let foldmarker = s:icon_closed - else - let foldmarker = s:icon_open - endif - - if g:tagbar_compact && first_tag && s:short_help - silent 0put =foldmarker . ' ' . kind.long - else - silent put =foldmarker . ' ' . kind.long - endif - - let curline = line('.') - let kindtag.tline = curline - let a:fileinfo.tline[curline] = kindtag - - if !kindtag.isFolded() - for tag in curtags - let str = tag.str() - silent put =' ' . str - - " Save the current tagbar line in the tag for easy - " highlighting access - let curline = line('.') - let tag.tline = curline - let a:fileinfo.tline[curline] = tag - let tag.depth = 1 - endfor - endif - - if !g:tagbar_compact - silent put _ - endif - - let first_tag = 0 - endif - endfor -endfunction - -" s:PrintTag() {{{2 -function! s:PrintTag(tag, depth, fileinfo, typeinfo) - " Print tag indented according to depth - silent put =repeat(' ', a:depth * 2) . a:tag.str() - - " Save the current tagbar line in the tag for easy - " highlighting access - let curline = line('.') - let a:tag.tline = curline - let a:fileinfo.tline[curline] = a:tag - - " Recursively print children - if a:tag.isFoldable() && !a:tag.isFolded() - for ckind in a:typeinfo.kinds - let childtags = filter(copy(a:tag.children), - \ 'v:val.fields.kind ==# ckind.short') - if len(childtags) > 0 - " Print 'kind' header of following children - if !has_key(a:typeinfo.kind2scope, ckind.short) - silent put =' ' . repeat(' ', a:depth * 2) . - \ '[' . ckind.long . ']' - let a:fileinfo.tline[line('.')] = a:tag - endif - for childtag in childtags - call s:PrintTag(childtag, a:depth + 1, - \ a:fileinfo, a:typeinfo) - endfor - endif - endfor - endif -endfunction - -" s:PrintHelp() {{{2 -function! s:PrintHelp() - if !g:tagbar_compact && s:short_help - silent 0put ='\" Press <F1> for help' - silent put _ - elseif !s:short_help - silent 0put ='\" Tagbar keybindings' - silent put ='\"' - silent put ='\" --------- General ---------' - silent put ='\" <Enter> : Jump to tag definition' - silent put ='\" <Space> : Display tag prototype' - silent put ='\"' - silent put ='\" ---------- Folds ----------' - silent put ='\" +, zo : Open fold' - silent put ='\" -, zc : Close fold' - silent put ='\" o, za : Toggle fold' - silent put ='\" *, zR : Open all folds' - silent put ='\" =, zM : Close all folds' - silent put ='\"' - silent put ='\" ---------- Misc -----------' - silent put ='\" s : Toggle sort' - silent put ='\" x : Zoom window in/out' - silent put ='\" q : Close window' - silent put ='\" <F1> : Remove help' - silent put _ - endif -endfunction - -" s:RenderKeepView() {{{2 -" The gist of this function was taken from NERDTree by Martin Grenfell. -function! s:RenderKeepView(...) - if a:0 == 1 - let line = a:1 - else - let line = line('.') - endif - - let curcol = col('.') - let topline = line('w0') - - call s:RenderContent() - - let scrolloff_save = &scrolloff - set scrolloff=0 - - call cursor(topline, 1) - normal! zt - call cursor(line, curcol) - - let &scrolloff = scrolloff_save - - redraw -endfunction - -" User actions {{{1 -" s:HighlightTag() {{{2 -function! s:HighlightTag() - let tagline = 0 - - let tag = s:GetNearbyTag() - if !empty(tag) - let tagline = tag.tline - endif - - " Don't highlight the tag again if it's the same one as last time. - " This prevents the Tagbar window from jumping back after scrolling with - " the mouse. - if tagline == s:last_highlight_tline - return - else - let s:last_highlight_tline = tagline - endif - - let eventignore_save = &eventignore - set eventignore=all - - let tagbarwinnr = bufwinnr('__Tagbar__') - let prevwinnr = winnr() - execute tagbarwinnr . 'wincmd w' - - match none - - " No tag above cursor position so don't do anything - if tagline == 0 - execute prevwinnr . 'wincmd w' - let &eventignore = eventignore_save - redraw - return - endif - - if g:tagbar_autoshowtag - call s:OpenParents(tag) - endif - - " Check whether the tag is inside a closed fold and highlight the parent - " instead in that case - let tagline = tag.getClosedParentTline() - - " Go to the line containing the tag - execute tagline - - " Make sure the tag is visible in the window - call winline() - - let foldpat = '[' . s:icon_open . s:icon_closed . ' ]' - let pattern = '/^\%' . tagline . 'l\s*' . foldpat . '[-+# ]\zs[^( ]\+\ze/' - execute 'match TagbarHighlight ' . pattern - - execute prevwinnr . 'wincmd w' - - let &eventignore = eventignore_save - - redraw -endfunction - -" s:JumpToTag() {{{2 -function! s:JumpToTag(stay_in_tagbar) - let taginfo = s:GetTagInfo(line('.'), 1) - - let autoclose = w:autoclose - - if empty(taginfo) || has_key(taginfo, 'numtags') - return - endif - - let tagbarwinnr = winnr() - - let eventignore_save = &eventignore - set eventignore=all - - " This elaborate construct will try to switch to the correct - " buffer/window; if the buffer isn't currently shown in a window it will - " open it in the first window with a non-special buffer in it - wincmd p - let filebufnr = bufnr(taginfo.fileinfo.fpath) - if bufnr('%') != filebufnr - let filewinnr = bufwinnr(filebufnr) - if filewinnr != -1 - execute filewinnr . 'wincmd w' - else - for i in range(1, winnr('$')) - execute i . 'wincmd w' - if &buftype == '' - execute 'buffer ' . filebufnr - break - endif - endfor - endif - " To make ctrl-w_p work we switch between the Tagbar window and the - " correct window once - execute tagbarwinnr . 'wincmd w' - wincmd p - endif - - " Mark current position so it can be jumped back to - mark ' - - " Jump to the line where the tag is defined. Don't use the search pattern - " since it doesn't take the scope into account and thus can fail if tags - " with the same name are defined in different scopes (e.g. classes) - execute taginfo.fields.line - - " If the file has been changed but not saved, the tag may not be on the - " saved line anymore, so search for it in the vicinity of the saved line - if match(getline('.'), taginfo.pattern) == -1 - let interval = 1 - let forward = 1 - while search(taginfo.pattern, 'W' . forward ? '' : 'b') == 0 - if !forward - if interval > line('$') - break - else - let interval = interval * 2 - endif - endif - let forward = !forward - endwhile - endif - - " If the tag is on a different line after unsaved changes update the tag - " and file infos/objects - let curline = line('.') - if taginfo.fields.line != curline - let taginfo.fields.line = curline - let taginfo.fileinfo.fline[curline] = taginfo - endif - - " Center the tag in the window - normal! z. - - if foldclosed('.') != -1 - .foldopen! - endif - - redraw - - let &eventignore = eventignore_save - - if a:stay_in_tagbar - call s:HighlightTag() - execute tagbarwinnr . 'wincmd w' - elseif g:tagbar_autoclose || autoclose - call s:CloseWindow() - else - call s:HighlightTag() - endif -endfunction - -" s:ShowPrototype() {{{2 -function! s:ShowPrototype() - let taginfo = s:GetTagInfo(line('.'), 1) - - if empty(taginfo) - return - endif - - echo taginfo.getPrototype() -endfunction - -" s:ToggleHelp() {{{2 -function! s:ToggleHelp() - let s:short_help = !s:short_help - - " Prevent highlighting from being off after adding/removing the help text - match none - - call s:RenderContent() - - execute 1 - redraw -endfunction - -" s:GotoNextToplevelTag() {{{2 -function! s:GotoNextToplevelTag(direction) - let curlinenr = line('.') - let newlinenr = line('.') - - if a:direction == 1 - let range = range(line('.') + 1, line('$')) - else - let range = range(line('.') - 1, 1, -1) - endif - - for tmplinenr in range - let taginfo = s:GetTagInfo(tmplinenr, 0) - - if empty(taginfo) - continue - elseif empty(taginfo.parent) - let newlinenr = tmplinenr - break - endif - endfor - - if curlinenr != newlinenr - execute newlinenr - call winline() - endif - - redraw -endfunction - -" Folding {{{1 -" s:OpenFold() {{{2 -function! s:OpenFold() - let fileinfo = s:known_files.getCurrent() - if empty(fileinfo) - return - endif - - let curline = line('.') - - let tag = s:GetTagInfo(curline, 0) - if empty(tag) - return - endif - - call tag.openFold() - - call s:RenderKeepView() -endfunction - -" s:CloseFold() {{{2 -function! s:CloseFold() - let fileinfo = s:known_files.getCurrent() - if empty(fileinfo) - return - endif - - match none - - let curline = line('.') - - let curtag = s:GetTagInfo(curline, 0) - if empty(curtag) - return - endif - - let newline = curtag.closeFold() - - call s:RenderKeepView(newline) -endfunction - -" s:ToggleFold() {{{2 -function! s:ToggleFold() - let fileinfo = s:known_files.getCurrent() - if empty(fileinfo) - return - endif - - match none - - let curtag = s:GetTagInfo(line('.'), 0) - if empty(curtag) - return - endif - - let newline = line('.') - - if curtag.isKindheader() - call curtag.toggleFold() - elseif curtag.isFoldable() - if curtag.isFolded() - call curtag.openFold() - else - let newline = curtag.closeFold() - endif - else - let newline = curtag.closeFold() - endif - - call s:RenderKeepView(newline) -endfunction - -" s:SetFoldLevel() {{{2 -function! s:SetFoldLevel(level) - if a:level < 0 - echoerr 'Foldlevel can''t be negative' - return - endif - - let fileinfo = s:known_files.getCurrent() - if empty(fileinfo) - return - endif - - call s:SetFoldLevelRecursive(fileinfo, fileinfo.tags, a:level) - - let typeinfo = s:known_types[fileinfo.ftype] - - " Apply foldlevel to 'kind's - if a:level == 0 - for kind in typeinfo.kinds - call fileinfo.closeKindFold(kind) - endfor - else - for kind in typeinfo.kinds - call fileinfo.openKindFold(kind) - endfor - endif - - let fileinfo.foldlevel = a:level - - call s:RenderContent() -endfunction - -" s:SetFoldLevelRecursive() {{{2 -" Apply foldlevel to normal tags -function! s:SetFoldLevelRecursive(fileinfo, tags, level) - for tag in a:tags - if tag.depth >= a:level - call tag.setFolded(1) - else - call tag.setFolded(0) - endif - - if has_key(tag, 'children') - call s:SetFoldLevelRecursive(a:fileinfo, tag.children, a:level) - endif - endfor -endfunction - -" s:OpenParents() {{{2 -function! s:OpenParents(...) - let tagline = 0 - - if a:0 == 1 - let tag = a:1 - else - let tag = s:GetNearbyTag() - endif - - call tag.openParents() - - call s:RenderKeepView() -endfunction - -" Helper functions {{{1 -" s:CleanUp() {{{2 -function! s:CleanUp() - silent autocmd! TagbarAutoCmds - - unlet s:is_maximized - unlet s:compare_typeinfo - unlet s:short_help -endfunction - -" s:CleanupFileinfo() {{{2 -function! s:CleanupFileinfo(fname) - call s:known_files.rm(a:fname) -endfunction - -" s:QuitIfOnlyWindow() {{{2 -function! s:QuitIfOnlyWindow() - " Before quitting Vim, delete the tagbar buffer so that - " the '0 mark is correctly set to the previous buffer. - if winbufnr(2) == -1 - " Check if there is more than one tab page - if tabpagenr('$') == 1 - bdelete - quit - else - close - endif - endif -endfunction - -" s:AutoUpdate() {{{2 -function! s:AutoUpdate(fname) - call s:LogDebugMessage('AutoUpdate called on ' . a:fname) - - " Don't do anything if tagbar is not open or if we're in the tagbar window - let tagbarwinnr = bufwinnr('__Tagbar__') - if tagbarwinnr == -1 || &filetype == 'tagbar' - call s:LogDebugMessage('Tagbar window not open or in Tagbar window') - return - endif - - " Only consider the main filetype in cases like 'python.django' - let ftype = get(split(&filetype, '\.'), 0, '') - call s:LogDebugMessage('Vim filetype: ' . &filetype . - \ ', sanitized filetype: ' . ftype) - - " Don't do anything if the file isn't supported - if !s:IsValidFile(a:fname, ftype) - call s:LogDebugMessage('Not a valid file, stopping processing') - return - endif - - " Process the file if it's unknown or the information is outdated - " Also test for entries that exist but are empty, which will be the case - " if there was an error during the ctags execution - if s:known_files.has(a:fname) && !empty(s:known_files.get(a:fname)) - if s:known_files.get(a:fname).mtime != getftime(a:fname) - call s:LogDebugMessage('Filedata outdated, updating ' . a:fname) - call s:ProcessFile(a:fname, ftype) - endif - elseif !s:known_files.has(a:fname) - call s:LogDebugMessage('Unknown file, processing ' . a:fname) - call s:ProcessFile(a:fname, ftype) - endif - - let fileinfo = s:known_files.get(a:fname) - - " If we don't have an entry for the file by now something must have gone - " wrong, so don't change the tagbar content - if empty(fileinfo) - call s:LogDebugMessage('fileinfo empty after processing: ' . a:fname) - return - endif - - " Display the tagbar content - call s:RenderContent(fileinfo) - - " Call setCurrent after rendering so RenderContent can check whether the - " same file is redisplayed - if !empty(fileinfo) - call s:LogDebugMessage('Setting current file to ' . a:fname) - call s:known_files.setCurrent(fileinfo) - endif - - call s:HighlightTag() - call s:LogDebugMessage('AutoUpdate finished successfully') -endfunction - -" s:IsValidFile() {{{2 -function! s:IsValidFile(fname, ftype) - if a:fname == '' || a:ftype == '' - call s:LogDebugMessage('Empty filename or type') - return 0 - endif - - if !filereadable(a:fname) - call s:LogDebugMessage('File not readable') - return 0 - endif - - if !has_key(s:known_types, a:ftype) - call s:LogDebugMessage('Unsupported filetype: ' . a:ftype) - return 0 - endif - - return 1 -endfunction - -" s:EscapeCtagsCmd() {{{2 -" Assemble the ctags command line in a way that all problematic characters are -" properly escaped and converted to the system's encoding -" Optional third parameter is a file name to run ctags on -function! s:EscapeCtagsCmd(ctags_bin, args, ...) - call s:LogDebugMessage('EscapeCtagsCmd called') - call s:LogDebugMessage('ctags_bin: ' . a:ctags_bin) - call s:LogDebugMessage('ctags_args: ' . a:args) - - if exists('+shellslash') - let shellslash_save = &shellslash - set noshellslash - endif - - if a:0 == 1 - let fname = shellescape(a:1) - else - let fname = '' - endif - - let ctags_cmd = shellescape(a:ctags_bin) . ' ' . a:args . ' ' . fname - - if exists('+shellslash') - let &shellslash = shellslash_save - endif - - " Needed for cases where 'encoding' is different from the system's - " encoding - if g:tagbar_systemenc != &encoding - let ctags_cmd = iconv(ctags_cmd, &encoding, g:tagbar_systemenc) - elseif $LANG != '' - let ctags_cmd = iconv(ctags_cmd, &encoding, $LANG) - endif - - call s:LogDebugMessage('Escaped ctags command: ' . ctags_cmd) - - if ctags_cmd == '' - echoerr 'Tagbar: Encoding conversion failed!' - \ 'Please make sure your system is set up correctly' - \ 'and that Vim is compiled with the "iconv" feature.' - endif - - return ctags_cmd -endfunction - -" s:ExecuteCtags() {{{2 -" Execute ctags with necessary shell settings -" Partially based on the discussion at -" http://vim.1045645.n5.nabble.com/bad-default-shellxquote-in-Widows-td1208284.html -function! s:ExecuteCtags(ctags_cmd) - if exists('+shellslash') - let shellslash_save = &shellslash - set noshellslash - endif - - if &shell =~ 'cmd\.exe' - let shellxquote_save = &shellxquote - set shellxquote=\" - let shellcmdflag_save = &shellcmdflag - set shellcmdflag=/s\ /c - endif - - let ctags_output = system(a:ctags_cmd) - - if &shell =~ 'cmd\.exe' - let &shellxquote = shellxquote_save - let &shellcmdflag = shellcmdflag_save - endif - - if exists('+shellslash') - let &shellslash = shellslash_save - endif - - return ctags_output -endfunction - -" s:GetTagInfo() {{{2 -" Return the info dictionary of the tag on the specified line. If the line -" does not contain a valid tag (for example because it is empty or only -" contains a pseudo-tag) return an empty dictionary. -function! s:GetTagInfo(linenr, ignorepseudo) - let fileinfo = s:known_files.getCurrent() - - if empty(fileinfo) - return {} - endif - - " Don't do anything in empty and comment lines - let curline = getline(a:linenr) - if curline =~ '^\s*$' || curline[0] == '"' - return {} - endif - - " Check if there is a tag on the current line - if !has_key(fileinfo.tline, a:linenr) - return {} - endif - - let taginfo = fileinfo.tline[a:linenr] - - " Check if the current tag is not a pseudo-tag - if a:ignorepseudo && taginfo.isPseudoTag() - return {} - endif - - return taginfo -endfunction - -" s:GetNearbyTag() {{{2 -" Get the tag info for a file near the cursor in the current file -function! s:GetNearbyTag() - let fileinfo = s:known_files.getCurrent() - - let curline = line('.') - let tag = {} - - " If a tag appears in a file more than once (for example namespaces in - " C++) only one of them has a 'tline' entry and can thus be highlighted. - " The only way to solve this would be to go over the whole tag list again, - " making everything slower. Since this should be a rare occurence and - " highlighting isn't /that/ important ignore it for now. - for line in range(curline, 1, -1) - if has_key(fileinfo.fline, line) - let tag = fileinfo.fline[line] - break - endif - endfor - - return tag -endfunction - -" s:CheckMouseClick() {{{2 -function! s:CheckMouseClick() - let line = getline('.') - let curcol = col('.') - - if (match(line, s:icon_open . '[-+ ]') + 1) == curcol - call s:CloseFold() - elseif (match(line, s:icon_closed . '[-+ ]') + 1) == curcol - call s:OpenFold() - elseif g:tagbar_singleclick - call s:JumpToTag(0) - endif -endfunction - -" s:DetermineFiletype() {{{2 -function! s:DetectFiletype(bufnr) - " Filetype has already been detected for loaded buffers, but not - " necessarily for unloaded ones - let ftype = getbufvar(a:bufnr, '&filetype') - - if bufloaded(a:bufnr) - return ftype - endif - - if ftype != '' - return ftype - endif - - " Unloaded buffer with non-detected filetype, need to detect filetype - " manually - let bufname = bufname(a:bufnr) - - let eventignore_save = &eventignore - set eventignore=FileType - let filetype_save = &filetype - - exe 'doautocmd filetypedetect BufRead ' . bufname - let ftype = &filetype - - let &filetype = filetype_save - let &eventignore = eventignore_save - - return ftype -endfunction - - -" TagbarBalloonExpr() {{{2 -function! TagbarBalloonExpr() - let taginfo = s:GetTagInfo(v:beval_lnum, 1) - - if empty(taginfo) - return - endif - - return taginfo.getPrototype() -endfunction - -" TagbarGenerateStatusline() {{{2 -function! TagbarGenerateStatusline() - if g:tagbar_sort - let text = '[Name]' - else - let text = '[Order]' - endif - - if !empty(s:known_files.getCurrent()) - let filename = fnamemodify(s:known_files.getCurrent().fpath, ':t') - let text .= ' ' . filename - endif - - return text -endfunction - -" Debugging {{{1 -" s:StartDebug() {{{2 -function! s:StartDebug(filename) - if empty(a:filename) - let s:debug_file = 'tagbardebug.log' - else - let s:debug_file = a:filename - endif - - " Empty log file - exe 'redir! > ' . s:debug_file - redir END - - " Check whether the log file could be created - if !filewritable(s:debug_file) - echomsg 'Tagbar: Unable to create log file ' . s:debug_file - let s:debug_file = '' - return - endif - - let s:debug = 1 -endfunction - -" s:StopDebug() {{{2 -function! s:StopDebug() - let s:debug = 0 - let s:debug_file = '' -endfunction - -" s:LogDebugMessage() {{{2 -function! s:LogDebugMessage(msg) - if s:debug - exe 'redir >> ' . s:debug_file - silent echon strftime('%H:%M:%S') . ': ' . a:msg . "\n" - redir END - endif -endfunction - -" Autoload functions {{{1 -function! tagbar#ToggleWindow() - call s:ToggleWindow() -endfunction - -function! tagbar#OpenWindow(...) - let flags = a:0 > 0 ? a:1 : '' - call s:OpenWindow(flags) -endfunction - -function! tagbar#CloseWindow() - call s:CloseWindow() -endfunction - -function! tagbar#SetFoldLevel(...) - call s:SetFoldLevel(a:1) -endfunction - -function! tagbar#OpenParents() - call s:OpenParents() -endfunction - -function! tagbar#StartDebug(...) - let filename = a:0 > 0 ? a:1 : '' - call s:StartDebug(filename) -endfunction - -function! tagbar#StopDebug() - call s:StopDebug() -endfunction - -function! tagbar#RestoreSession() - call s:RestoreSession() -endfunction - -" Automatically open Tagbar if one of the open buffers contains a supported -" file -function! tagbar#autoopen() - call s:Init() - - for bufnr in range(1, bufnr('$')) - if buflisted(bufnr) - let ftype = s:DetectFiletype(bufnr) - if s:IsValidFile(bufname(bufnr), ftype) - call s:OpenWindow('') - return - endif - endif - endfor -endfunction - -" Modeline {{{1 -" vim: ts=8 sw=4 sts=4 et foldenable foldmethod=marker foldcolumn=1 diff --git a/vim/bundle/gist-vim b/vim/bundle/gist-vim new file mode 160000 +Subproject cd6e94648e081e6cfe5edd1abf246b0010347cb diff --git a/vim/bundle/searchfold.vim b/vim/bundle/searchfold.vim new file mode 160000 +Subproject f2b988c592bc8989c2b9300f241ebb0aefde43e diff --git a/vim/bundle/supertab b/vim/bundle/supertab new file mode 160000 +Subproject 94b62deb9fa3f9084154221aed053bf6031af8a diff --git a/vim/bundle/syntastic b/vim/bundle/syntastic new file mode 160000 +Subproject 4428f7e54f65800089b162a134a895fd3454ecd diff --git a/vim/bundle/tagbar b/vim/bundle/tagbar new file mode 160000 +Subproject 2ebd2a1392493940a82ef4de76604182e069e0b diff --git a/vim/bundle/taglist b/vim/bundle/taglist new file mode 160000 +Subproject 53041fbc45398a9af631a20657e109707a45533 diff --git a/vim/bundle/tlib_vim b/vim/bundle/tlib_vim new file mode 160000 +Subproject 70e614d608386b92af3b3ec73d2f25704162fbf diff --git a/vim/bundle/vim-addon-mw-utils b/vim/bundle/vim-addon-mw-utils new file mode 160000 +Subproject 0c5612fa31ee434ba055e21c76f456244b3b510 diff --git a/vim/bundle/vim-fugitive b/vim/bundle/vim-fugitive new file mode 160000 +Subproject 3b5f715262e0ec03cbdd80d8858039b47af3436 diff --git a/vim/bundle/vim-indent-object b/vim/bundle/vim-indent-object new file mode 160000 +Subproject 78fffa609b3e6b84ef01ee4c9aba6d7435d7b18 diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails new file mode 160000 +Subproject add3463d50b2a9a95586bbaa3303006837755e6 diff --git a/vim/bundle/vim-showmarks b/vim/bundle/vim-showmarks new file mode 160000 +Subproject 4cf8089a78fbbd9793de9c6c202757d4141af94 diff --git a/vim/bundle/vim-snipmate b/vim/bundle/vim-snipmate new file mode 160000 +Subproject a6c5d6a56a4e79fd3ec3fb3c8de2453c9e897eb diff --git a/vim/bundle/vim-surround b/vim/bundle/vim-surround new file mode 160000 +Subproject 02199ea0080d744ec76b79d74ce56d51d25cf7a diff --git a/vim/bundle/vim-unimpaired b/vim/bundle/vim-unimpaired new file mode 160000 +Subproject 48d1cb6bf0000159291014226d8d8d3330ad875 diff --git a/vim/doc/command-t.txt b/vim/doc/command-t.txt deleted file mode 100644 index d7e8c41..0000000 --- a/vim/doc/command-t.txt +++ /dev/null @@ -1,817 +0,0 @@ -*command-t.txt* Command-T plug-in for Vim *command-t* - -CONTENTS *command-t-contents* - - 1. Introduction |command-t-intro| - 2. Requirements |command-t-requirements| - 3. Installation |command-t-installation| - 3. Managing using Pathogen |command-t-pathogen| - 4. Trouble-shooting |command-t-trouble-shooting| - 5. Usage |command-t-usage| - 6. Commands |command-t-commands| - 7. Mappings |command-t-mappings| - 8. Options |command-t-options| - 9. Authors |command-t-authors| -10. Website |command-t-website| -11. Donations |command-t-donations| -12. License |command-t-license| -13. History |command-t-history| - - -INTRODUCTION *command-t-intro* - -The Command-T plug-in provides an extremely fast, intuitive mechanism for -opening files and buffers with a minimal number of keystrokes. It's named -"Command-T" because it is inspired by the "Go to File" window bound to -Command-T in TextMate. - -Files are selected by typing characters that appear in their paths, and are -ordered by an algorithm which knows that characters that appear in certain -locations (for example, immediately after a path separator) should be given -more weight. - -To search efficiently, especially in large projects, you should adopt a -"path-centric" rather than a "filename-centric" mentality. That is you should -think more about where the desired file is found rather than what it is -called. This means narrowing your search down by including some characters -from the upper path components rather than just entering characters from the -filename itself. - -Screencasts demonstrating the plug-in can be viewed at: - - https://wincent.com/products/command-t - - -REQUIREMENTS *command-t-requirements* - -The plug-in requires Vim compiled with Ruby support, a compatible Ruby -installation at the operating system level, and a C compiler to build -the Ruby extension. - - -1. Vim compiled with Ruby support - -You can check for Ruby support by launching Vim with the --version switch: - - vim --version - -If "+ruby" appears in the version information then your version of Vim has -Ruby support. - -Another way to check is to simply try using the :ruby command from within Vim -itself: - - :ruby 1 - -If your Vim lacks support you'll see an error message like this: - - E319: Sorry, the command is not available in this version - -The version of Vim distributed with Mac OS X does not include Ruby support, -while MacVim does; it is available from: - - http://github.com/b4winckler/macvim/downloads - -For Windows users, the Vim 7.2 executable available from www.vim.org does -include Ruby support, and is recommended over version 7.3 (which links against -Ruby 1.9, but apparently has some bugs that need to be resolved). - - -2. Ruby - -In addition to having Ruby support in Vim, your system itself must have a -compatible Ruby install. "Compatible" means the same version as Vim itself -links against. If you use a different version then Command-T is unlikely -to work (see TROUBLE-SHOOTING below). - -On Mac OS X Snow Leopard, the system comes with Ruby 1.8.7 and all recent -versions of MacVim (the 7.2 snapshots and 7.3) are linked against it. - -On Linux and similar platforms, the linked version of Ruby will depend on -your distribution. You can usually find this out by examining the -compilation and linking flags displayed by the |:version| command in Vim, and -by looking at the output of: - - :ruby puts RUBY_VERSION - -A suitable Ruby environment for Windows can be installed using the Ruby -1.8.7-p299 RubyInstaller available at: - - http://rubyinstaller.org/downloads/archives - -If using RubyInstaller be sure to download the installer executable, not the -7-zip archive. When installing mark the checkbox "Add Ruby executables to your -PATH" so that Vim can find them. - - -3. C compiler - -Part of Command-T is implemented in C as a Ruby extension for speed, allowing -it to work responsively even on directory hierarchies containing enormous -numbers of files. As such, a C compiler is required in order to build the -extension and complete the installation. - -On Mac OS X, this can be obtained by installing the Xcode Tools that come on -the Mac OS X install disc. - -On Windows, the RubyInstaller Development Kit can be used to conveniently -install the necessary tool chain: - - http://rubyinstaller.org/downloads/archives - -At the time of writing, the appropriate development kit for use with Ruby -1.8.7 is DevKit-3.4.5r3-20091110. - -To use the Development Kit extract the archive contents to your C:\Ruby -folder. - - -INSTALLATION *command-t-installation* - -Command-T is distributed as a "vimball" which means that it can be installed -by opening it in Vim and then sourcing it: - - :e command-t.vba - :so % - -The files will be installed in your |'runtimepath'|. To check where this is -you can issue: - - :echo &rtp - -The C extension must then be built, which can be done from the shell. If you -use a typical |'runtimepath'| then the files were installed inside ~/.vim and -you can build the extension with: - - cd ~/.vim/ruby/command-t - ruby extconf.rb - make - -Note: If you are an RVM user, you must perform the build using the same -version of Ruby that Vim itself is linked against. This will often be the -system Ruby, which can be selected before issuing the "make" command with: - - rvm use system - - -MANAGING USING PATHOGEN *command-t-pathogen* - -Pathogen is a plugin that allows you to maintain plugin installations in -separate, isolated subdirectories under the "bundle" directory in your -|'runtimepath'|. The following examples assume that you already have -Pathogen installed and configured, and that you are installing into -~/.vim/bundle. For more information about Pathogen, see: - - http://www.vim.org/scripts/script.php?script_id=2332 - -If you manage your entire ~/.vim folder using Git then you can add the -Command-T repository as a submodule: - - cd ~/.vim - git submodule add git://git.wincent.com/command-t.git bundle/command-t - git submodule init - -Or if you just wish to do a simple clone instead of using submodules: - - cd ~/.vim - git clone git://git.wincent.com/command-t.git bundle/command-t - -Once you have a local copy of the repository you can update it at any time -with: - - cd ~/.vim/bundle/command-t - git pull - -Or you can switch to a specific release with: - - cd ~/.vim/bundle/command-t - git checkout 0.8b - -After installing or updating you must build the extension: - - cd ~/.vim/bundle/command-t - rake make - -While the Vimball installation automatically generates the help tags, under -Pathogen it is necessary to do so explicitly from inside Vim: - - :call pathogen#helptags() - - -TROUBLE-SHOOTING *command-t-trouble-shooting* - -Most installation problems are caused by a mismatch between the version of -Ruby on the host operating system, and the version of Ruby that Vim itself -linked against at compile time. For example, if one is 32-bit and the other is -64-bit, or one is from the Ruby 1.9 series and the other is from the 1.8 -series, then the plug-in is not likely to work. - -As such, on Mac OS X, I recommend using the standard Ruby that comes with the -system (currently 1.8.7) along with the latest version of MacVim (currently -version 7.3). If you wish to use custom builds of Ruby or of MacVim (not -recommmended) then you will have to take extra care to ensure that the exact -same Ruby environment is in effect when building Ruby, Vim and the Command-T -extension. - -For Windows, the following combination is known to work: - - - Vim 7.2 from http://www.vim.org/download.php: - ftp://ftp.vim.org/pub/vim/pc/gvim72.exe - - Ruby 1.8.7-p299 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/71492/rubyinstaller-1.8.7-p299.exe - - DevKit 3.4.5r3-20091110 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/66888/devkit-3.4.5r3-20091110.7z - -If a problem occurs the first thing you should do is inspect the output of: - - ruby extconf.rb - make - -During the installation, and: - - vim --version - -And compare the compilation and linker flags that were passed to the -extension and to Vim itself when they were built. If the Ruby-related -flags or architecture flags are different then it is likely that something -has changed in your Ruby environment and the extension may not work until -you eliminate the discrepancy. - - -USAGE *command-t-usage* - -Bring up the Command-T file window by typing: - - <Leader>t - -This mapping is set up automatically for you, provided you do not already have -a mapping for <Leader>t or |:CommandT|. You can also bring up the file window -by issuing the command: - - :CommandT - -A prompt will appear at the bottom of the screen along with a file window -showing all of the files in the current directory (as returned by the -|:pwd| command). - -For the most efficient file navigation within a project it's recommended that -you |:cd| into the root directory of your project when starting to work on it. -If you wish to open a file from outside of the project folder you can pass in -an optional path argument (relative or absolute) to |:CommandT|: - - :CommandT ../path/to/other/files - -Type letters in the prompt to narrow down the selection, showing only the -files whose paths contain those letters in the specified order. Letters do not -need to appear consecutively in a path in order for it to be classified as a -match. - -Once the desired file has been selected it can be opened by pressing <CR>. -(By default files are opened in the current window, but there are other -mappings that you can use to open in a vertical or horizontal split, or in -a new tab.) Note that if you have |'nohidden'| set and there are unsaved -changes in the current window when you press <CR> then opening in the current -window would fail; in this case Command-T will open the file in a new split. - -The following mappings are active when the prompt has focus: - - <BS> delete the character to the left of the cursor - <Del> delete the character at the cursor - <Left> move the cursor one character to the left - <C-h> move the cursor one character to the left - <Right> move the cursor one character to the right - <C-l> move the cursor one character to the right - <C-a> move the cursor to the start (left) - <C-e> move the cursor to the end (right) - <C-u> clear the contents of the prompt - <Tab> change focus to the file listing - -The following mappings are active when the file listing has focus: - - <Tab> change focus to the prompt - -The following mappings are active when either the prompt or the file listing -has focus: - - <CR> open the selected file - <C-CR> open the selected file in a new split window - <C-s> open the selected file in a new split window - <C-v> open the selected file in a new vertical split window - <C-t> open the selected file in a new tab - <C-j> select next file in the file listing - <C-n> select next file in the file listing - <Down> select next file in the file listing - <C-k> select previous file in the file listing - <C-p> select previous file in the file listing - <Up> select previous file in the file listing - <C-c> cancel (dismisses file listing) - -The following is also available on terminals which support it: - - <Esc> cancel (dismisses file listing) - -Note that the default mappings can be overriden by setting options in your -~/.vimrc file (see the OPTIONS section for a full list of available options). - -In addition, when the file listing has focus, typing a character will cause -the selection to jump to the first path which begins with that character. -Typing multiple characters consecutively can be used to distinguish between -paths which begin with the same prefix. - - -COMMANDS *command-t-commands* - - *:CommandT* -|:CommandT| Brings up the Command-T file window, starting in the - current working directory as returned by the|:pwd| - command. - - *:CommandTBuffer* -|:CommandTBuffer|Brings up the Command-T buffer window. - This works exactly like the standard file window, - except that the selection is limited to files that - you already have open in buffers. - - *:CommandTJumps* -|:CommandTJump| Brings up the Command-T jumplist window. - This works exactly like the standard file window, - except that the selection is limited to files that - you already have in the jumplist. Note that jumps - can persist across Vim sessions (see Vim's |jumplist| - documentation for more info). - - *:CommandTFlush* -|:CommandTFlush|Instructs the plug-in to flush its path cache, causing - the directory to be rescanned for new or deleted paths - the next time the file window is shown. In addition, all - configuration settings are re-evaluated, causing any - changes made to settings via the |:let| command to be picked - up. - - -MAPPINGS *command-t-mappings* - -By default Command-T comes with only two mappings: - - <Leader>t bring up the Command-T file window - <Leader>b bring up the Command-T buffer window - -However, Command-T won't overwrite a pre-existing mapping so if you prefer -to define different mappings use lines like these in your ~/.vimrc: - - nnoremap <silent> <Leader>t :CommandT<CR> - nnoremap <silent> <Leader>b :CommandTBuffer<CR> - -Replacing "<Leader>t" or "<Leader>b" with your mapping of choice. - -Note that in the case of MacVim you actually can map to Command-T (written -as <D-t> in Vim) in your ~/.gvimrc file if you first unmap the existing menu -binding of Command-T to "New Tab": - - if has("gui_macvim") - macmenu &File.New\ Tab key=<nop> - map <D-t> :CommandT<CR> - endif - -When the Command-T window is active a number of other additional mappings -become available for doing things like moving between and selecting matches. -These are fully described above in the USAGE section, and settings for -overriding the mappings are listed below under OPTIONS. - - -OPTIONS *command-t-options* - -A number of options may be set in your ~/.vimrc to influence the behaviour of -the plug-in. To set an option, you include a line like this in your ~/.vimrc: - - let g:CommandTMaxFiles=20000 - -To have Command-T pick up new settings immediately (that is, without having -to restart Vim) you can issue the |:CommandTFlush| command after making -changes via |:let|. - -Following is a list of all available options: - - *g:CommandTMaxFiles* - |g:CommandTMaxFiles| number (default 10000) - - The maximum number of files that will be considered when scanning the - current directory. Upon reaching this number scanning stops. This - limit applies only to file listings and is ignored for buffer - listings. - - *g:CommandTMaxDepth* - |g:CommandTMaxDepth| number (default 15) - - The maximum depth (levels of recursion) to be explored when scanning the - current directory. Any directories at levels beyond this depth will be - skipped. - - *g:CommandTMaxCachedDirectories* - |g:CommandTMaxCachedDirectories| number (default 1) - - The maximum number of directories whose contents should be cached when - recursively scanning. With the default value of 1, each time you change - directories the cache will be emptied and Command-T will have to - rescan. Higher values will make Command-T hold more directories in the - cache, bringing performance at the cost of memory usage. If set to 0, - there is no limit on the number of cached directories. - - *g:CommandTMaxHeight* - |g:CommandTMaxHeight| number (default: 0) - - The maximum height in lines the match window is allowed to expand to. - If set to 0, the window will occupy as much of the available space as - needed to show matching entries. - - *g:CommandTAlwaysShowDotFiles* - |g:CommandTAlwaysShowDotFiles| boolean (default: 0) - - When showing the file listing Command-T will by default show dot-files - only if the entered search string contains a dot that could cause a - dot-file to match. When set to a non-zero value, this setting instructs - Command-T to always include matching dot-files in the match list - regardless of whether the search string contains a dot. See also - |g:CommandTNeverShowDotFiles|. Note that this setting only influences - the file listing; the buffer listing treats dot-files like any other - file. - - *g:CommandTNeverShowDotFiles* - |g:CommandTNeverShowDotFiles| boolean (default: 0) - - In the file listing, Command-T will by default show dot-files if the - entered search string contains a dot that could cause a dot-file to - match. When set to a non-zero value, this setting instructs Command-T to - never show dot-files under any circumstances. Note that it is - contradictory to set both this setting and - |g:CommandTAlwaysShowDotFiles| to true, and if you do so Vim will suffer - from headaches, nervous twitches, and sudden mood swings. This setting - has no effect in buffer listings, where dot files are treated like any - other file. - - *g:CommandTScanDotDirectories* - |g:CommandTScanDotDirectories| boolean (default: 0) - - Normally Command-T will not recurse into "dot-directories" (directories - whose names begin with a dot) while performing its initial scan. Set - this setting to a non-zero value to override this behavior and recurse. - Note that this setting is completely independent of the - |g:CommandTAlwaysShowDotFiles| and |g:CommandTNeverShowDotFiles| - settings; those apply only to the selection and display of matches - (after scanning has been performed), whereas - |g:CommandTScanDotDirectories| affects the behaviour at scan-time. - - Note also that even with this setting off you can still use Command-T to - open files inside a "dot-directory" such as ~/.vim, but you have to use - the |:cd| command to change into that directory first. For example: - - :cd ~/.vim - :CommandT - - *g:CommandTMatchWindowAtTop* - |g:CommandTMatchWindowAtTop| boolean (default: 0) - - When this setting is off (the default) the match window will appear at - the bottom so as to keep it near to the prompt. Turning it on causes the - match window to appear at the top instead. This may be preferable if you - want the best match (usually the first one) to appear in a fixed location - on the screen rather than moving as the number of matches changes during - typing. - - *g:CommandTMatchWindowReverse* - |g:CommandTMatchWindowReverse| boolean (default: 0) - - When this setting is off (the default) the matches will appear from - top to bottom with the topmost being selected. Turning it on causes the - matches to be reversed so the best match is at the bottom and the - initially selected match is the bottom most. This may be preferable if - you want the best match to appear in a fixed location on the screen - but still be near the prompt at the bottom. - -As well as the basic options listed above, there are a number of settings that -can be used to override the default key mappings used by Command-T. For -example, to set <C-x> as the mapping for cancelling (dismissing) the Command-T -window, you would add the following to your ~/.vimrc: - - let g:CommandTCancelMap='<C-x>' - -Multiple, alternative mappings may be specified using list syntax: - - let g:CommandTCancelMap=['<C-x>', '<C-c>'] - -Following is a list of all map settings and their defaults: - - Setting Default mapping(s) - - *g:CommandTBackspaceMap* - |g:CommandTBackspaceMap| <BS> - - *g:CommandTDeleteMap* - |g:CommandTDeleteMap| <Del> - - *g:CommandTAcceptSelectionMap* - |g:CommandTAcceptSelectionMap| <CR> - - *g:CommandTAcceptSelectionSplitMap* - |g:CommandTAcceptSelectionSplitMap| <C-CR> - <C-s> - - *g:CommandTAcceptSelectionTabMap* - |g:CommandTAcceptSelectionTabMap| <C-t> - - *g:CommandTAcceptSelectionVSplitMap* - |g:CommandTAcceptSelectionVSplitMap| <C-v> - - *g:CommandTToggleFocusMap* - |g:CommandTToggleFocusMap| <Tab> - - *g:CommandTCancelMap* - |g:CommandTCancelMap| <C-c> - <Esc> (not on all terminals) - - *g:CommandTSelectNextMap* - |g:CommandTSelectNextMap| <C-n> - <C-j> - <Down> - - *g:CommandTSelectPrevMap* - |g:CommandTSelectPrevMap| <C-p> - <C-k> - <Up> - - *g:CommandTClearMap* - |g:CommandTClearMap| <C-u> - - *g:CommandTCursorLeftMap* - |g:CommandTCursorLeftMap| <Left> - <C-h> - - *g:CommandTCursorRightMap* - |g:CommandTCursorRightMap| <Right> - <C-l> - - *g:CommandTCursorEndMap* - |g:CommandTCursorEndMap| <C-e> - - *g:CommandTCursorStartMap* - |g:CommandTCursorStartMap| <C-a> - -In addition to the options provided by Command-T itself, some of Vim's own -settings can be used to control behavior: - - *command-t-wildignore* - |'wildignore'| string (default: '') - - Vim's |'wildignore'| setting is used to determine which files should be - excluded from listings. This is a comma-separated list of glob patterns. - It defaults to the empty string, but common settings include "*.o,*.obj" - (to exclude object files) or ".git,.svn" (to exclude SCM metadata - directories). For example: - - :set wildignore+=*.o,*.obj,.git - - A pattern such as "vendor/rails/**" would exclude all files and - subdirectories inside the "vendor/rails" directory (relative to - directory Command-T starts in). - - See the |'wildignore'| documentation for more information. - - -AUTHORS *command-t-authors* - -Command-T is written and maintained by Wincent Colaiuta <win@wincent.com>. -Other contributors that have submitted patches include (in alphabetical -order): - - Anthony Panozzo - Daniel Hahler - Lucas de Vries - Marian Schubert - Matthew Todd - Mike Lundy - Scott Bronson - Steven Moazami - Sung Pae - Victor Hugo Borja - Woody Peterson - Zak Johnson - -As this was the first Vim plug-in I had ever written I was heavily influenced -by the design of the LustyExplorer plug-in by Stephen Bach, which I understand -is one of the largest Ruby-based Vim plug-ins to date. - -While the Command-T codebase doesn't contain any code directly copied from -LustyExplorer, I did use it as a reference for answers to basic questions (like -"How do you do 'X' in a Ruby-based Vim plug-in?"), and also copied some basic -architectural decisions (like the division of the code into Prompt, Settings -and MatchWindow classes). - -LustyExplorer is available from: - - http://www.vim.org/scripts/script.php?script_id=1890 - - -WEBSITE *command-t-website* - -The official website for Command-T is: - - https://wincent.com/products/command-t - -The latest release will always be available from there. - -Development in progress can be inspected via the project's Git repository -browser at: - - https://wincent.com/repos/command-t - -A copy of each release is also available from the official Vim scripts site -at: - - http://www.vim.org/scripts/script.php?script_id=3025 - -Bug reports should be submitted to the issue tracker at: - - https://wincent.com/issues - - -DONATIONS *command-t-donations* - -Command-T itself is free software released under the terms of the BSD license. -If you would like to support further development you can make a donation via -PayPal to win@wincent.com: - - https://wincent.com/products/command-t/donations - - -LICENSE *command-t-license* - -Copyright 2010-2011 Wincent Colaiuta. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -HISTORY *command-t-history* - -1.3.1 (18 December 2011) - -- fix jumplist navigation under Ruby 1.9.x (patch from Woody Peterson) - -1.3 (27 November 2011) - -- added the option to maintain multiple caches when changing among - directories; see the accompanying |g:CommandTMaxCachedDirectories| setting -- added the ability to navigate using the Vim jumplist (patch from Marian - Schubert) - -1.2.1 (30 April 2011) - -- Remove duplicate copy of the documentation that was causing "Duplicate tag" - errors -- Mitigate issue with distracting blinking cursor in non-GUI versions of Vim - (patch from Steven Moazami) - -1.2 (30 April 2011) - -- added |g:CommandTMatchWindowReverse| option, to reverse the order of items - in the match listing (patch from Steven Moazami) - -1.1b2 (26 March 2011) - -- fix a glitch in the release process; the plugin itself is unchanged since - 1.1b - -1.1b (26 March 2011) - -- add |:CommandTBuffer| command for quickly selecting among open buffers - -1.0.1 (5 January 2011) - -- work around bug when mapping |:CommandTFlush|, wherein the default mapping - for |:CommandT| would not be set up -- clean up when leaving the Command-T buffer via unexpected means (such as - with <C-W k> or similar) - -1.0 (26 November 2010) - -- make relative path simplification work on Windows - -1.0b (5 November 2010) - -- work around platform-specific Vim 7.3 bug seen by some users (wherein - Vim always falsely reports to Ruby that the buffer numbers is 0) -- re-use the buffer that is used to show the match listing, rather than - throwing it away and recreating it each time Command-T is shown; this - stops the buffer numbers from creeping up needlessly - -0.9 (8 October 2010) - -- use relative paths when opening files inside the current working directory - in order to keep buffer listings as brief as possible (patch from Matthew - Todd) - -0.8.1 (14 September 2010) - -- fix mapping issues for users who have set |'notimeout'| (patch from Sung - Pae) - -0.8 (19 August 2010) - -- overrides for the default mappings can now be lists of strings, allowing - multiple mappings to be defined for any given action -- <Leader>t mapping only set up if no other map for |:CommandT| exists - (patch from Scott Bronson) -- prevent folds from appearing in the match listing -- tweaks to avoid the likelihood of "Not enough room" errors when trying to - open files -- watch out for "nil" windows when restoring window dimensions -- optimizations (avoid some repeated downcasing) -- move all Ruby files under the "command-t" subdirectory and avoid polluting - the "Vim" module namespace - -0.8b (11 July 2010) - -- large overhaul of the scoring algorithm to make the ordering of returned - results more intuitive; given the scope of the changes and room for - optimization of the new algorithm, this release is labelled as "beta" - -0.7 (10 June 2010) - -- handle more |'wildignore'| patterns by delegating to Vim's own |expand()| - function; with this change it is now viable to exclude patterns such as - 'vendor/rails/**' in addition to filename-only patterns like '*.o' and - '.git' (patch from Mike Lundy) -- always sort results alphabetically for empty search strings; this eliminates - filesystem-specific variations (patch from Mike Lundy) - -0.6 (28 April 2010) - -- |:CommandT| now accepts an optional parameter to specify the starting - directory, temporarily overriding the usual default of Vim's |:pwd| -- fix truncated paths when operating from root directory - -0.5.1 (11 April 2010) - -- fix for Ruby 1.9 compatibility regression introduced in 0.5 -- documentation enhancements, specifically targetted at Windows users - -0.5 (3 April 2010) - -- |:CommandTFlush| now re-evaluates settings, allowing changes made via |let| - to be picked up without having to restart Vim -- fix premature abort when scanning very deep directory hierarchies -- remove broken |<Esc>| key mapping on vt100 and xterm terminals -- provide settings for overriding default mappings -- minor performance optimization - -0.4 (27 March 2010) - -- add |g:CommandTMatchWindowAtTop| setting (patch from Zak Johnson) -- documentation fixes and enhancements -- internal refactoring and simplification - -0.3 (24 March 2010) - -- add |g:CommandTMaxHeight| setting for controlling the maximum height of the - match window (patch from Lucas de Vries) -- fix bug where |'list'| setting might be inappropriately set after dismissing - Command-T -- compatibility fix for different behaviour of "autoload" under Ruby 1.9.1 -- avoid "highlight group not found" warning when run under a version of Vim - that does not have syntax highlighting support -- open in split when opening normally would fail due to |'hidden'| and - |'modified'| values - -0.2 (23 March 2010) - -- compatibility fixes for compilation under Ruby 1.9 series -- compatibility fixes for compilation under Ruby 1.8.5 -- compatibility fixes for Windows and other non-UNIX platforms -- suppress "mapping already exists" message if <Leader>t mapping is already - defined when plug-in is loaded -- exclude paths based on |'wildignore'| setting rather than a hardcoded - regular expression - -0.1 (22 March 2010) - -- initial public release - ------------------------------------------------------------------------------- -vim:tw=78:ft=help: diff --git a/vim/doc/conque_term.txt b/vim/doc/conque_term.txt deleted file mode 100644 index ff8ca54..0000000 --- a/vim/doc/conque_term.txt +++ /dev/null @@ -1,156 +0,0 @@ -*ConqueTerm* Plugin to run a shell in a buffer - -The ConqueTerm plugin will convert a buffer into a terminal emulator, allowing -you to run a shell or shell application in the buffer. - - *conque_term-usage* - -Type :ConqueTerm <command> to launch an application in the current buffer. E.g. - - :ConqueTerm bash - :ConqueTerm mysql -h localhost -u joe_lunchbox Menu - :ConqueTerm man top - -Use :ConqueTermSplit or :ConqueTermVSplit to open Conque in a new horizontal -or vertical buffer. - -Keys pressed in insert mode will be sent to the shell, along with output from -the 'p' command in normal mode. - -Press the <Esc> key twice to send a single <Esc> to the shell. Pressing this -key once will leave insert mode like normal. - -Press <F9> in any buffer to send a visual selection to the shell. - - - *conque_term-settings* - -Set the following in your .vimrc (default values shown) - -" Enable colors. Setting this to 0 will make your terminal faster. -let g:ConqueTerm_Color = 1 - -" Set your terminal type. I strong recommend leaving this as vt100, -" however more features may be enabled with xterm. -let g:ConqueTerm_TERM = 'vt100' - -" Set buffer syntax. Conque has highlighting for MySQL, but not much else. -let g:ConqueTerm_Syntax = 'conque' - -" Continue updating shell when it's not the current, focused buffer -let g:ConqueTerm_ReadUnfocused = 1 - - - *conque_term-requirements* - -The following minimum requirements are needed to run Conque. Conque will not -run on Windows without a Cygwin-like environment. - - - Vim 7.1 - - Python 2.3 - - Supported operating systems: *nix, Mac, or Cygwin - -Tested on: - - Vim 7.2 / Python 2.6 / Ubuntu 9.10 (Gnome & GTK) - - Vim 7.2 / Python 2.6 / FreeBSD 8.0 (GTK) - - Vim 7.1 / Python 2.6 / FreeBSD 8.0 (GTK) - x Vim 7.0 / Python 2.6 / FreeBSD 8.0 (GTK) - * feedkeys() doesn't restart updatetime - - Vim 7.2 / Python 2.4 / OpenSolaris 2009.06 (Gnome) - - Vim 7.2 / Python 2.4 / CentOS 5.3 (no GUI) - - Vim 7.1 / Python 2.3 / RHEL 4 (no GUI) - - Vim 7.2 / Python 2.5 / Cygwin (Windows Vista 64b) - - MacVim 7.2 / Python 2.3 / OS X 10.6.2 - - *conque_term-bugs* - -The following are known limitations: - - - Font/color highlighting is imperfect and slow. If you don't care about - color in your shell, set g:ConqueTerm_Color = 0 in your .vimrc - - Conque only supports the extended ASCII character set for input, not utf-8. - - VT100 escape sequence support is not complete. - - Alt/Meta key support in Vim isn't great in general, and conque is no - exception. Pressing <Esc><Esc>x or <Esc><M-x> instead of <M-x> works in - most cases. - - *conque_term-todo* - - - Fix pasting from named registers - - Polling unfucused conque buffers (Top explodes when window resizes) - - Enable graphics character set - - Consider supporting xterm escapes - - Improve color logic - - Find a solution to UTF-8 input (See InsertCharPre in Vim todo.txt) - - Find an alternative to updatetime polling (See Vim todo.txt) - - Find a graceful solution to Meta key input - - Windows support - (See PyConsole http://www.vim.org/scripts/script.php?script_id=1974) - - Always: look for performance improvements - - - *conque_term-contribute* - -The two contributions most in need are improvements to Vim itself. I currently -use hacks to simulate a key press event and repeating CursorHold event. The -Vim todo.txt document lists proposed improvements to give users this behavior -without hacks. Having a key press event should allow Conque to work with multi- -byte input. If you are a Vim developer, please consider prioritizing these two -items: - - - todo.txt (Autocommands, line ~3137) - 8 Add an event like CursorHold that is triggered repeatedly, not just - once after typing something. - - - todo.txt (Autocommands, proposed event list, line ~3189) - InsertCharPre - user typed character Insert mode, before inserting the - char. Pattern is matched with text before the cursor. Set v:char to the - character, can be changed. (not triggered when 'paste' is set). - -Bugs, suggestions and patches are all welcome. - -For more information visit http://conque.googlecode.com - -Check out the latest from svn at http://conque.googlecode.com/svn/trunk/ - - *conque_term-changelog* - - - 1.0 / 2010-02- - * Complete python rewrite - * Add support for ncurses based applications - * Add continuous polling, instead of using <Tab> - * Improve speed - * Improve syntax highlighting - - - 0.6 / 2009-12-18 - * Fix GVim errors with non-english locale - * No functional changes - - - 0.5 / 2009-12-02 - * Various performance enhancements and bugfixes. - * Rewritten escape sequence processing - - - 0.4 / 2009-10-30 - * Improved history and tab completion - * Fix escape sequence formatting and improve highlighting - * Send selected text to shell from any buffer - * Add special handling of "vi" and "man" commands - * Improve error handling - * Add key mappings for <C-p> <C-n> <C-l> <C-j> - * Various bugfixes - - - 0.3 / 2009-10-13 - * Apply escape sequence coloring to output, e.g. ls --color - * Clean up syntax files for portability - * Fix several Vim 7.1 bugs - * Bugfixes for multiple shell buffers - * Add experimental shell folding option - - - 0.2 / 2009-10-01 - * Rewritten subprocess management module in python instead of c - * Added support for OS X, partial support for Windows - * Improved tab completion - - - 0.1 / 2009-09-03 - * Initial release - diff --git a/vim/doc/fugitive.txt b/vim/doc/fugitive.txt deleted file mode 100644 index e2ae323..0000000 --- a/vim/doc/fugitive.txt +++ /dev/null @@ -1,269 +0,0 @@ -*fugitive.txt* A Git wrapper so awesome, it should be illegal - -Author: Tim Pope <http://tpo.pe/> -License: Same terms as Vim itself (see |license|) - -This plugin is only available if 'compatible' is not set. - -INTRODUCTION *fugitive* - -Whenever you edit a file from a Git repository, a set of commands is defined -that serve as a gateway to Git. - -COMMANDS *fugitive-commands* - -These commands are local to the buffers in which they work (generally, buffers -that are part of Git repositories). - - *fugitive-:Git* -:Git [args] Run an arbitrary git command. Similar to :!git [args] - but chdir to the repository tree first. - - *fugitive-:Git!* -:Git! [args] Like |:Git|, but capture the output into a temp file, - and edit that temp file. - - *fugitive-:Gcd* -:Gcd [directory] |:cd| relative to the repository. - - *fugitive-:Glcd* -:Glcd [directory] |:lcd| relative to the repository. - - *fugitive-:Gstatus* -:Gstatus Bring up the output of git-status in the preview - window. The following maps, which work on the cursor - line file where sensible, are provided: - - <C-N> next file - <C-P> previous file - <CR> |:Gedit| - - |:Git| add - - |:Git| reset (staged files) - C |:Gcommit| - cA |Gcommit| --amend --reuse-message=HEAD - ca |Gcommit| --amend - D |:Gdiff| - ds |:Gsdiff| - dp |:Git!| diff (p for patch; use :Gw to apply) - dp |:Git| add --intent-to-add (untracked files) - dv |:Gvdiff| - O |:Gtabedit| - o |:Gsplit| - p |:Git| add --patch - p |:Git| reset --patch (staged files) - q close status - R reload status - - *fugitive-:Gcommit* -:Gcommit [args] A wrapper around git-commit. If there is nothing - to commit, |:Gstatus| is called instead. Unless the - arguments given would skip the invocation of an editor - (e.g., -m), a split window will be used to obtain a - commit message. Write and close that window (:wq or - |:Gwrite|) to finish the commit. Unlike when running - the actual git-commit command, it is possible (but - unadvisable) to muck with the index with commands like - git-add and git-reset while a commit message is - pending. - - *fugitive-:Ggrep* -:Ggrep [args] |:grep| with git-grep as 'grepprg'. - - *fugitive-:Glog* -:Glog [args] Load all previous revisions of the current file into - the quickfix list. Additional git-log arguments can - be given (for example, --reverse). If "--" appears as - an argument, no file specific filtering is done, and - commits are loaded into the quickfix list. - - *fugitive-:Gedit* *fugitive-:Ge* -:Gedit [revision] |:edit| a |fugitive-revision|. - - *fugitive-:Gsplit* -:Gsplit [revision] |:split| a |fugitive-revision|. - - *fugitive-:Gvsplit* -:Gvsplit [revision] |:vsplit| a |fugitive-revision|. - - *fugitive-:Gtabedit* -:Gtabedit [revision] |:tabedit| a |fugitive-revision|. - - *fugitive-:Gpedit* -:Gpedit [revision] |:pedit| a |fugitive-revision|. - -:Gsplit! [args] *fugitive-:Gsplit!* *fugitive-:Gvsplit!* -:Gvsplit! [args] *fugitive-:Gtabedit!* *fugitive-:Gpedit!* -:Gtabedit! [args] Like |:Git!|, but open the resulting temp file in a -:Gpedit! [args] split, tab, or preview window. - - *fugitive-:Gread* -:Gread [revision] Empty the buffer and |:read| a |fugitive-revision|. - When the argument is omitted, this is similar to - git-checkout on a work tree file or git-add on a stage - file, but without writing anything to disk. - -:{range}Gread [revision] - |:read| in a |fugitive-revision| after {range}. - - *fugitive-:Gread!* -:Gread! [args] Empty the buffer and |:read| the output of a Git - command. For example, :Gread! show HEAD:%. - -:{range}Gread! [args] |:read| the output of a Git command after {range}. - - *fugitive-:Gwrite* -:Gwrite Write to the current file's path and stage the results. - When run in a work tree file, it is effectively git - add. Elsewhere, it is effectively git-checkout. A - great deal of effort is expended to behave sensibly - when the work tree or index version of the file is - open in another buffer. - -:Gwrite {path} You can give |:Gwrite| an explicit path of where in - the work tree to write. You can also give a path like - :0:foo.txt or even :0 to write to just that stage in - the index. - - *fugitive-:Gwq* -:Gwq [path] Like |:Gwrite| followed by |:quit| if the write - succeeded. - -:Gwq! [path] Like |:Gwrite|! followed by |:quit|! if the write - succeeded. - - *fugitive-:Gdiff* -:Gdiff [revision] Perform a |vimdiff| against the current file in the - given revision. With no argument, the version in the - index is used (which means a three-way diff during a - merge conflict, making it a git-mergetool - alternative). The newer of the two files is placed - to the right. Use |do| and |dp| and write to the - index file to simulate "git add --patch". - - *fugitive-:Gsdiff* -:Gsdiff [revision] Like |:Gdiff|, but split horizontally. - - *fugitive-:Gvdiff* -:Gvdiff [revision] Identical to |:Gdiff|. For symmetry with |:Gsdiff|. - - *fugitive-:Gmove* -:Gmove {destination} Wrapper around git-mv that renames the buffer - afterward. The destination is relative to the current - directory except when started with a /, in which case - it is relative to the work tree. Add a ! to pass -f. - - *fugitive-:Gremove* -:Gremove Wrapper around git-rm that deletes the buffer - afterward. When invoked in an index file, --cached is - passed. Add a ! to pass -f and forcefully discard the - buffer. - - *fugitive-:Gblame* -:Gblame [flags] Run git-blame on the file and open the results in a - scroll bound vertical split. Press enter on a line to - reblame the file as it was in that commit. You can - give any of ltwfsMC as flags and they will be passed - along to git-blame. - - In a blame buffer on any line, one can press <CR> to - reblame at that commit, ~ to reblame at that commit's - [count]th first grandparent (like HEAD~[count]), or P - to reblame at that commit's [count]th parent (like - HEAD^[count]). Press o or O to open up that commit - in a horizontal of vertical split. Pressing q will - close the blame buffer. - -:[range]Gblame [flags] Run git-blame on the given range. - - *fugitive-:Gbrowse* -:[range]Gbrowse If the remote for the current branch is on GitHub, - open the current file, blob, tree, commit, or tag - (with git-web--browse) on GitHub. Otherwise, open the - current file, blob, tree, commit, or tag in - git-instaweb (if you have issues, verify you can run - "git instaweb" from a terminal). If a range is given, - it is appropriately appended to the URL as an anchor. - -:[range]Gbrowse! Like :Gbrowse, but put the URL on the clipboard rather - than opening it. - -:[range]Gbrowse {revision} - Like :Gbrowse, but for a given |fugitive-revision|. A - useful value here is -, which ties the URL to the - latest commit rather than a volatile branch. - -:[range]Gbrowse [...]@{remote} - Force using the given remote rather than the remote - for the current branch. The remote is used to - determine which GitHub repository to link to. - -MAPPINGS *fugitive-mappings* - -These maps are available in Git objects. - - *fugitive-<CR>* -<CR> Jump to the revision under the cursor. - - *fugitive-o* -o Jump to the revision under the cursor in a new split. - - *fugitive-O* -O Jump to the revision under the cursor in a new tab. - - *fugitive-~* -~ Go to the current file in the [count]th first - ancestor. - - *fugitive-P* -P Go to the current file in the [count]th parent. - - *fugitive-C* -C Go to the commit containing the current file. - - *fugitive-a* -a Show the current tag, commit, or tree in an alternate - format. - -SPECIFYING REVISIONS *fugitive-revision* - -Fugitive revisions are similar to Git revisions as defined in the "SPECIFYING -REVISIONS" section in the git-rev-parse man page. For commands that accept an -optional revision, the default is the file in the index for work tree files -and the work tree file for everything else. Example revisions follow. - -Revision Meaning ~ -HEAD .git/HEAD -master .git/refs/heads/master -HEAD^{} The commit referenced by HEAD -HEAD^ The parent of the commit referenced by HEAD -HEAD: The tree referenced by HEAD -/HEAD The file named HEAD in the work tree -Makefile The file named Makefile in the work tree -HEAD^:Makefile The file named Makefile in the parent of HEAD -:Makefile The file named Makefile in the index (writable) -- The current file in HEAD -^ The current file in the previous commit -~3 The current file 3 commits ago -: .git/index (Same as |:Gstatus|) -:0 The current file in the index -:1 The current file's common ancestor during a conflict -:2 The current file in the target branch during a conflict -:3 The current file in the merged branch during a conflict -:/foo The most recent commit with "foo" in the message - -STATUSLINE *fugitive-statusline* - - *fugitive#statusline()* -Add %{fugitive#statusline()} to your statusline to get an indicator including -the current branch and the currently edited file's commit. If you don't have -a statusline, this one matches the default when 'ruler' is set: -> - set statusline=%<%f\ %h%m%r%{fugitive#statusline()}%=%-14.(%l,%c%V%)\ %P -< -ABOUT *fugitive-about* - -Grab the latest version or report a bug on GitHub: - -http://github.com/tpope/vim-fugitive - - vim:tw=78:et:ft=help:norl: diff --git a/vim/doc/gist-vim.txt b/vim/doc/gist-vim.txt deleted file mode 100644 index 36ef71c..0000000 --- a/vim/doc/gist-vim.txt +++ /dev/null @@ -1,182 +0,0 @@ -*Gist.vim* Vimscript for creating gists (http://gist.github.com) - -Usage |gist-vim-usage| -Tips |gist-vim-tips| -Requirements |gist-vim-requirements| -License |gist-vim-license| -Install |gist-vim-install| - -This is a vimscript for creating gists (http://gist.github.com) - -For the latest version please see https://github.com/mattn/gist-vim. - -============================================================================== -USAGE *:Gist* *gist-vim-usage* - -- Post current buffer to gist, using default privacy option. > - - :Gist -< -- Post selected text to gist, using defualt privacy option. - This applies to all permutations listed below (except multi). > - - :'<,'>Gist -< -- Create a private gist. > - - :Gist -p -< -- Create a public gist. - (Only relevant if you've set gists to be private by default.) > - - :Gist -P -< -- Post whole text to gist as public. - This is only relevant if you've set gists to be private by default; - if you get an empty gist list, try ":Gist --abandon". > - - :Gist -P -< -- Post whole text to gist as public. - This is only relevant if you've set gists to be private by default. - If you get an empty gist list, try ":Gist --abandon". > - - :Gist -P -< -- Create a gist anonymously. > - - :Gist -a -< -- Create a gist with all open buffers. > - - :Gist -m -< -- Edit the gist (you need to have opened the gist buffer first). - You can update the gist with the {:w} command within the gist buffer. > - - :Gist -e -< -- Edit the gist with name "foo.js" (you need to have opened the gist buffer - first). > - - :Gist -e foo.js -< -- Delete the gist (you need to have opened the gist buffer first). - Password authentication is needed. > - - :Gist -d -< -- Fork the gist (you need to have opened the gist buffer first). - Password authentication is needed. > - - :Gist -f -< -- Get gist XXXXX. > - - :Gist XXXXX -< -- Get gist XXXXX and add to clipboard. > - - :Gist -c XXXXX -< -- List your public gists. > - - :Gist -l -< -- List gists from user "mattn". > - - :Gist -l mattn -< -- List all (public and private) of your gists. > - - :Gist -la -< - -============================================================================== -TIPS *gist-vim-tips* - -If you set "g:gist_clip_command", gist.vim will copy the gist code with option -"-c". - - - Mac: > - let g:gist_clip_command = 'pbcopy' -< - - Linux: > - let g:gist_clip_command = 'xclip -selection clipboard' -< - - Others (cygwin?): > - let g:gist_clip_command = 'putclip' -< -If you want to detect filetype from the filename: > - - let g:gist_detect_filetype = 1 -< -If you want to open the browser after the post: > - - let g:gist_open_browser_after_post = 1 -< -If you want to change the browser: > - - let g:gist_browser_command = 'w3m %URL%' -< -or: > - - let g:gist_browser_command = 'opera %URL% &' -< -On windows, this should work with your user settings. - -If you want to show your private gists with ":Gist -l": > - - let g:gist_show_privates = 1 -< -If you get problems when creating gists try: > - - :Gist --abandon -< - -============================================================================== -REQUIREMENTS *gist-vim-requirements* - - - Curl command (http://curl.haxx.se/) - - and, if you want to use your git profile, the git command-line client. - -============================================================================== -LICENSE *gist-vim-license* - - - Copyright 2010 by Yasuhiro Matsumoto - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - OF THE POSSIBILITY OF SUCH DAMAGE. - -============================================================================== -INSTALL *gist-vim-install* - -Copy gist.vim to your plugin directory. - -gist.vim will create a curl cookie-jar file in your runtimepath. - -rtp: - - plugin/gist.vim - - cookies/github - -If you want to uninstall gist.vim, remember to also remove "cookies/github". - - vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/indent-object.txt b/vim/doc/indent-object.txt deleted file mode 100644 index 5b58102..0000000 --- a/vim/doc/indent-object.txt +++ /dev/null @@ -1,120 +0,0 @@ -*indent-object.txt* Text objects based on indent levels.
-
- Copyright (c) 2010 Michael Smith
-
-Indent Text Objects
-
-INTRODUCTION |idntobj-introduction|
-TEXT OBJECTS |idntobj-objects|
-BLANK LINES |idntobj-blanklines|
-ABOUT |idntobj-about|
-
-
-==============================================================================
-INTRODUCTION *idntobj-introduction*
-
-Vim text objects provide a convenient way to select and operate on various
-types of objects. These objects include regions surrounded by various types of
-brackets and various parts of language (ie sentences, paragraphs, etc).
-
-This plugin defines a new text object, based on indentation levels. This is
-very useful in languages such as Python, in which the syntax defines scope in
-terms of indentation. Using the objects defined in this plugin, an entire if
-structure can be quickly selected, for example.
-
-
-==============================================================================
-TEXT OBJECTS *ai* *ii* *aI* *iI* *idntobj-objects*
-
-This plugin defines two new text objects. These are very similar - they differ
-only in whether they include the line below the block or not.
-
- Key Mapping Description ~
->
- <count>ai (A)n (I)ndentation level and line above.
- <count>ii (I)nner (I)ndentation level (no line above).
- <count>aI (A)n (I)ndentation level and lines above/below.
- <count>iI (I)nner (I)ndentation level (no lines above/below).
-<
-
-Note that the iI mapping is mostly included simply for completeness, it is
-effectively a synonym for ii.
-
-Just like regular text objects, these mappings can be used either with
-operators expecting a motion, such as 'd' or 'c', as well as in visual mode.
-In visual mode the mapping can be repeated, which has the effect of
-iteratively increasing the scope of indentation block selected. Specifying a
-count can be used to achieve the same effect.
-
-The difference between |ai| and |aI| is that |ai| includes the line
-immediately above the indentation block, whereas aI includes not only that,
-but also the line below. Which of these is most useful largely depends on the
-structure of the language being edited.
-
-For example, when editing the Python code, |ai| is generally more useful, as
-the line above the indentation block is usually related to it. For example, in
-the following code (* is used to indicate the cursor position):
->
- if foo > 3:
- log("foo is big") *
- foo = 3
- do_something_else()
-<
-the if clause is logically related to the code block, whereas the function
-call below is not. It is unlikely we would want to select the line below when
-we are interested in the if block.
-
-However, in other languages, such as Vim scripts, control structures are
-usually terminated with something like 'endif'. Therefore, in this example:
->
- if foo > 3
- echo "foo is big" *
- let foo = 3
- endif
- call do_something_else()
-<
-we would more likely want to include the endif when we select the if
-structure.
-
-
-==============================================================================
-BLANK LINES *idntobj-blanklines*
-
-When scanning code blocks, the plugin usually ignores blank lines. There is an
-exception to this, however, when the block being selected is not indented. In
-this case if blank lines are ignored, then the entire file would be selected.
-Instead when code at the top level is being indented blank lines are
-considered to delimit the block.
-
-
-==============================================================================
-ABOUT *idntobj-about*
-
-vim-indent-object was written by Michael Smith <msmith@msmith.id.au>. The
-project repository is kept at:
-
-http://github.com/michaeljsmith/vim-indent-object
-
-Any feedback or criticism is welcome, and can be mailed to the author at the
-above email address. Alternatively issues can be raised on the project
-website.
-
-Licence:
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/vim/doc/rails.txt b/vim/doc/rails.txt deleted file mode 100644 index 6dbbb1e..0000000 --- a/vim/doc/rails.txt +++ /dev/null @@ -1,1020 +0,0 @@ -*rails.txt* Plugin for working with Ruby on Rails applications - -Author: Tim Pope <http://tpo.pe/> - -|rails-introduction| Introduction and Feature Summary -|rails-commands| General Commands -|rails-navigation| Navigation -|rails-gf| File Under Cursor - gf -|rails-alternate-related| Alternate and Related Files -|rails-type-navigation| File Type Commands -|rails-custom-navigation| Custom Navigation Commands -|rails-rake| Rake -|rails-scripts| Script Wrappers -|rails-refactoring| Refactoring Helpers -|rails-partials| Partial Extraction -|rails-migrations| Migration Inversion -|rails-integration| Integration -|rails-vim-integration| Integration with the Vim Universe -|rails-rails-integration| Integration with the Rails Universe -|rails-abbreviations| Abbreviations -|rails-syntax| Syntax Highlighting -|rails-options| Managed Vim Options -|rails-configuration| Configuration -|rails-global-settings| Global Settings -|rails-about| About rails.vim -|rails-license| License - -This plugin is only available if 'compatible' is not set. - -{Vi does not have any of this} - -INTRODUCTION *rails-introduction* *rails* - -Whenever you edit a file in a Rails application, this plugin will be -automatically activated. This sets various options and defines a few -buffer-specific commands. - -If you are in a hurry to get started, with a minimal amount of reading, you -are encouraged to at least skim through the headings and command names in this -file, to get a better idea of what is offered. If you only read one thing, -make sure it is the navigation section: |rails-navigation|. - -GENERAL COMMANDS *rails-commands* - -All commands are buffer local, unless otherwise stated. This means you must -actually edit a file from a Rails application. - - *rails-:Rails* -:Rails new {directory} The only global command. Creates a new Rails - application in {directory}, and loads the README. - -:Rails! Show the version of rails.vim installed. If rails.vim - is active for the current buffer, also show the type - of Rails file detected. - - *rails-:Rcd* -:Rcd [{directory}] |:cd| to /path/to/railsapp/{directory}. - - *rails-:Rlcd* -:Rlcd [{directory}] |:lcd| to /path/to/railsapp/{directory}. - - *rails-:Rdoc* -:Rdoc Browse to the Rails API, either in doc/api in the - current Rails application, gem_server if it is - running, or http://api.rubyonrails.org/ . Requires - :OpenURL to be defined (see |rails-:OpenURL|). - - *rails-:Rdoc!* -:Rdoc! Make the appropriate |:helptags| call and invoke - |:help| rails. - - *rails-:Redit* -:Redit {file} Deprecated in favor of |:R|. - - *rails-:Rfind* -:Rfind [{file}] Deprecated in favor of |:R| or |:find|. - - *rails-:Rlog* -:Rlog [{logfile}] Split window and open {logfile} ($RAILS_ENV or - development by default). The control characters used - for highlighting are removed. If you have a :Tail - command (provided by |tailminusf|.vim), that is used; - otherwise, the file does NOT reload upon change. - Use |:checktime| to tell Vim to check for changes. - |G| has been mapped to do just that prior to jumping - to the end of the file, and q is mapped to close the - window. If the delay in loading is too long, you - might like :Rake log:clear. - - *rails-:Rpreview* -:Rpreview [{path}] Creates a URL from http://localhost:3000/ and the - {path} given. The not too useful default is to then - edit this URL using Vim itself, allowing |netrw| to - download it. More useful is to define a :OpenURL - command, which will be used instead (see - |rails-:OpenURL|). If {path} is omitted, a sensible - default is used (considers the current - controller/template, but does not take routing into - account). The default is overridden by comments like - the following that are either before the current - method call or at the top of the file: > - # GET /users - # PUT /users/1 -< - *rails-:Rpreview!* -:Rpreview! [{path}] As with :Rpreview, except :OpenURL is never used. - - *rails-:Rtags* -:Rtags Calls ctags -R on the current application root and - writes the result to tmp/tags. Exuberant ctags must - be installed. Additional arguments can be passed to - ctags with |g:rails_ctags_arguments|. - - *rails-:Rrefresh* -:Rrefresh Refreshes certain cached settings. Most noticeably, - this clears the cached list of classes that are syntax - highlighted as railsUserClass. - - *rails-:Rrefresh!* -:Rrefresh! As above, and also reloads rails.vim. - - *rails-:OpenURL* -:OpenURL {url} This is not a command provided by the plugin, but - rather provided by user and utilized by other plugin - features. This command should be defined to open the - provided {url} in a web browser. An example command - on a Mac might be: > - :command -bar -nargs=1 OpenURL :!open <args> -< The following appears to work on Windows: > - :command -bar -nargs=1 OpenURL :!start cmd /cstart /b <args> -< On Debian compatible distributions, the following is - the preferred method: > - :command -bar -nargs=1 OpenURL :!sensible-browser <args> -< If exists("$SECURITYSESSIONID"), has("gui_win32"), or - executable("sensible-browser") is true, the - corresponding command above will be automatically - defined. Otherwise, you must provide your own (which - is recommended, regardless). - -NAVIGATION *rails-navigation* - -Navigation is where the real power of this plugin lies. Efficient use of the -following features will greatly ease navigating the Rails file structure. - -The 'path' has been modified to include all the best places to be. -> - :find application_controller.rb -< -File Under Cursor - gf ~ - *rails-gf* -The |gf| command, which normally edits the current file under the cursor, has -been remapped to take context into account. |CTRL-W_f| (open in new window) -and |CTRL-W_gf| (open in new tab) are also remapped. - -Example uses of |gf|, and where they might lead. -(* indicates cursor position) -> - Pos*t.first -< app/models/post.rb ~ -> - has_many :c*omments -< app/models/comment.rb ~ -> - link_to 'Home', :controller => 'bl*og' -< app/controllers/blog_controller.rb ~ -> - <%= render 'sh*ared/sidebar' %> -< app/views/shared/_sidebar.html.erb ~ -> - <%= stylesheet_link_tag 'scaf*fold' %> -< public/stylesheets/scaffold.css ~ -> - class BlogController < Applica*tionController -< app/controllers/application_controller.rb ~ -> - class ApplicationController < ActionCont*roller::Base -< .../action_controller/base.rb ~ -> - fixtures :pos*ts -< test/fixtures/posts.yml ~ -> - layout :pri*nt -< app/views/layouts/print.html.erb ~ -> - <%= link_to "New", new_comme*nt_path %> -< app/controllers/comments_controller.rb (jumps to def new) ~ - -In the last example, the controller and action for the named route are -determined by evaluating routes.rb as Ruby and doing some introspection. This -means code from the application is executed. Keep this in mind when -navigating unfamiliar applications. - -Alternate and Related Files ~ - *rails-alternate-related* -Two commands, :A and :R, are used quickly jump to an "alternate" and a -"related" file, defined below. - - *rails-:A* *rails-:AE* *rails-:AS* *rails-:AV* *rails-:AT* *rails-:AD* -:A These commands were picked to mimic Michael Sharpe's -:AE a.vim. Briefly, they edit the "alternate" file, in -:AS either the same window (:A and :AE), a new split -:AV window (:AS), a new vertically split window (:AV), a -:AT new tab (:AT), or read it into the current buffer -:AD (:AD). - - *rails-:R* *rails-:RE* *rails-:RS* *rails-:RV* *rails-:RT* *rails-:RD* -:R These are similar |rails-:A| and friends above, only -:RE they jump to the "related" file rather than the -:RS "alternate." With a file name argument, they edit -:RV a file relative to the application root (:R Rakefile), -:RT and with a count and a file name argument, they find a -:RD file in 'path' (e.g., :1R PostsController.) You can - also append a line number (post.rb:42) or a method - (PostsController#32) to both forms. - - *rails-alternate* *rails-related* -The alternate file is most frequently the test file, though there are -exceptions. The related file varies, and is sometimes dependent on current -location in the file. For example, when editing a controller, the related -file is template for the method currently being edited. - -The easiest way to learn these commands is to experiment. A few examples of -alternate and related files for a Test::Unit application follow: - -Current file Alternate file Related file ~ -model unit test schema definition -controller (in method) functional test template (view) -template (view) functional test controller (jump to method) -migration previous migration next migration -config/database.yml config/routes.rb config/environments/*.rb - -Suggestions for further contexts to consider for the alternate file, related -file, and file under the cursor are welcome. They are subtly tweaked from -release to release. - -File Type Navigation Commands ~ - *rails-type-navigation* -For the less common cases, a more deliberate set of commands are provided. -Each of the upcoming commands takes an optional argument (with tab completion) -but defaults to a reasonable guess. Commands that default to the current -model or controller generally behave like you'd expect in other file types. -For example, in app/helpers/posts_helper.rb, the current controller is -"posts", and in test/fixtures/comments.yml, the current model is "comment". -In model related files, the current controller is the pluralized model name, -and in controller related files, the current model is the singularized -controller name. - -Each of the following commands has variants for splitting, vertical splitting, -opening in a new tab, and reading the file into the current buffer. For -:Rmodel, those variants would be :RSmodel, :RVmodel, :RTmodel, and :RDmodel. -There is also :REmodel which is a synonym for :Rmodel (future versions might -allow customization of the behavior of :Rmodel). They also allow for jumping -to methods or line numbers using the same syntax as |:R|, and file creation -can be forced by adding a ! after the filename (not after the command -itself!). - -:Rcontroller |rails-:Rcontroller| -:Renvironment |rails-:Renvironment| -:Rfixtures |rails-:Rfixtures| -:Rfunctionaltest |rails-:Rfunctionaltest| -:Rhelper |rails-:Rhelper| -:Rinitializer |rails-:Rinitializer| -:Rintegrationtest |rails-:Rintegrationtest| -:Rjavascript |rails-:Rjavascript| -:Rlayout |rails-:Rlayout| -:Rlib |rails-:Rlib| -:Rlocale |rails-:Rlocale| -:Rmailer |rails-:Rmailer| -:Rmetal |rails-:Rmetal| -:Rmigration |rails-:Rmigration| -:Rmodel |rails-:Rmodel| -:Robserver |rails-:Robserver| -:Rplugin |rails-:Rplugin| -:Rspec |rails-:Rspec| -:Rstylesheet |rails-:Rstylesheet| -:Rtask |rails-:Rtask| -:Runittest |rails-:Runittest| -:Rview |rails-:Rview| - - *rails-:Rcontroller* -:Rcontroller [{name}] Edit the specified or current controller. - - *rails-:Renvironment* -:Renvironment [{name}] Edit the config/environments file specified. With no - argument, defaults to editing config/application.rb - or config/environment.rb. - - *rails-:Rfixtures* -:Rfixtures [{name}] Edit the fixtures for the given or current model. If - an argument is given, it must be pluralized, like the - final filename (this may change in the future). If - omitted, the current model is pluralized. An optional - extension can be given, to distinguish between YAML - and CSV fixtures. - - *rails-:Rfunctionaltest* -:Rfunctionaltest [{name}] - Edit the functional test or controller spec for the - specified or current controller. - - *rails-:Rhelper* -:Rhelper [{name}] Edit the helper for the specified name or current - controller. - - *rails-:Rinitializer* -:Rinitializer [{name}] Edit the config/initializers file specified. With no - argument, defaults to editing config/routes.rb. - - *rails-:Rintegrationtest* -:Rintegrationtest [{name}] - Edit the integration test, integration spec, or - cucumber feature specified. With no argument, - defaults to editing test/test_helper.rb. - - *rails-:Rjavascript* -:Rjavascript [{name}] Edit the JavaScript for the specified name or current - controller. Also supports CoffeeScript in - app/scripts/. - - *rails-:Rlayout* -:Rlayout [{name}] Edit the specified layout. Defaults to the layout for - the current controller, or the application layout if - that cannot be found. A new layout will be created if - an extension is given. - - *rails-:Rlib* -:Rlib [{name}] Edit the library from the lib directory for the - specified name. If the current file is part of a - plugin, the libraries from that plugin can be - specified as well. With no argument, defaults to - editing db/seeds.rb. - - *rails-:Rlocale* -:Rlocale [{name}] Edit the config/locale file specified, optionally - adding a yml or rb extension if none is given. With - no argument, checks config/environment.rb for the - default locale. - - *rails-:Rmailer* -:Rmailer [{name}] Edit the mailer specified. This looks in both - app/mailers for Rails 3 and app/models for older - versions of Rails but only tab completes the former. - - *rails-:Rmetal* -:Rmetal [{name}] Edit the app/metal file specified. With no argument, - defaults to editing config/boot.rb. - - *rails-:Rmigration* -:Rmigration [{pattern}] If {pattern} is a number, find the migration for that - particular set of digits, zero-padding if necessary. - Otherwise, find the newest migration containing the - given pattern. Omitting the pattern selects the - latest migration. Give a numeric argument of 0 to edit - db/schema.rb. - - *rails-:Rmodel* -:Rmodel [{name}] Edit the specified or current model. - - *rails-:Robserver* -:Robserver [{name}] Find the observer with a name like - {model}_observer.rb. When in an observer, most - commands (like :Rmodel) will seek based on the - observed model ({model}) and not the actual observer - ({model}_observer). However, for the command - :Runittest, a file of the form - {model}_observer_test.rb will be found. - - *rails-:Rplugin* -:Rplugin [{plugin}[/{path}]] - Edits a file within a plugin. If the path to the file - is omitted, it defaults to init.rb. If no argument is - given, it defaults to editing the application Gemfile. - - *rails-:Rspec* -:Rspec [{name}] Edit the given spec. With no argument, defaults to - editing spec/spec_helper.rb (If you want to jump to - the spec for the given file, use |:A| instead). This - command is only defined if there is a spec folder in - the root of the application. - - *rails-:Rstylesheet* -:Rstylesheet [{name}] Edit the stylesheet for the specified name or current - controller. Also supports Sass and SCSS. - - *rails-:Rtask* -:Rtask [{name}] Edit the .rake file from lib/tasks for the specified - name. If the current file is part of a plugin, the - tasks for that plugin can be specified as well. If no - argument is given, either the current plugin's - Rakefile or the application Rakefile will be edited. - - *rails-:Runittest* -:Runittest [{name}] Edit the unit test or model spec for the specified - name or current model. - - *rails-:Rview* -:Rview [[{controller}/]{view}] - Edit the specified view. The controller will default - sensibly, and the view name can be omitted when - editing a method of a controller. If a view name is - given with an extension, a new file will be created. - This is a quick way to create a new view. - -Custom Navigation Commands ~ - *rails-custom-navigation* - -It is also possible to create custom navigation commands. This is best done -in an initialization routine of some sort (e.g., an autocommand); see -|rails-configuration| for details. - - *rails-:Rnavcommand* -:Rnavcommand [options] {name} [{path} ...] - Create a navigation command with the supplied - name, looking in the supplied paths, using the - supplied options. The -suffix option specifies what - suffix to filter on, and strip from the filename, and - defaults to -suffix=.rb . The -glob option specifies - a file glob to use to find files, _excluding_ the - suffix. Useful values include -glob=* and -glob=**/*. - The -default option specifies a default argument (not - a full path). If it is specified as -default=model(), - -default=controller(), or -default=both(), the current - model, controller, or both (as with :Rintegrationtest) - is used as a default. - - *rails-:Rcommand* -:Rcommand Obsolete alias for |:Rnavcommand|. - -Examples: > - Rnavcommand api app/apis -glob=**/* -suffix=_api.rb - Rnavcommand config config -glob=*.* -suffix= -default=routes.rb - Rnavcommand concern app/concerns -glob=**/* - Rnavcommand exemplar test/exemplars spec/exemplars -glob=**/* - \ -default=model() -suffix=_exemplar.rb - -Finally, one Vim feature that proves helpful in conjunction with all of the -above is |CTRL-^|. This keystroke edits the previous file, and is helpful to -back out of any of the above commands. - -RAKE *rails-rake* - -Rake integration happens through the :Rake command. - - *rails-:Rake* -:[range]Rake {targets} Calls |:make!| {targets} (with 'makeprg' being rake, - or `bundle exec rake` if bundler.vim is active) and - opens the quickfix window if there were any errors. - An argument of "-" reruns the last task. If {targets} - are omitted, :Rake defaults to something sensible as - described below. Giving a line number argument may - affect that default. - - *rails-:Rake!* -:[range]Rake! {targets} Called with a bang, :Rake will forgo opening the - quickfix window. - - *rails-rake-defaults* - -Generally, the default task is one that runs the test you'd expect. For -example, if you're in a view in an RSpec application, the view spec is run, -but if it's a Test::Unit application, the functional test for the -corresponding controller is run. The following table lists the most -interesting mappings: - -File Task ~ -unit test test:units TEST=... -functional test test:functionals TEST=... -integration test test:integration TEST=... -spec spec SPEC=... -feature cucumber FEATURE=... -model test:units TEST=... spec SPEC=... -controller test:functionals TEST=... spec SPEC=... -helper test:functionals TEST=... spec SPEC=... -view test:functionals TEST=... spec SPEC=... -fixtures db:fixtures:load FIXTURES=... -migration db:migrate VERSION=... -config/routes.rb routes -db/seeds.rb db:seed - -Additionally, when :Rake is given a line number (e.g., :.Rake), the following -additional tasks can be invoked: - -File Task ~ -unit test test:units TEST=... TESTOPTS=-n... -functional test test:functionals TEST=... TESTOPTS=-n... -integration test test:integration TEST=... TESTOPTS=-n... -spec spec SPEC=...:... -feature cucumber FEATURE=...:... -controller routes CONTROLLER=... -fixtures db:fixtures:identify LABEL=... -migration in self.up db:migrate:up VERSION=... -migration in self.down db:migrate:down VERSION=... -migration elsewhere db:migrate:redo VERSION=... -task ... (try to guess currently edited declaration) - -Finally, you can override the default task with a comment like "# rake ..." -before the method pointed to by [range] or at the top of the file. - -SCRIPT WRAPPERS *rails-scripts* - -The following commands are wrappers around the scripts in the script directory -of the Rails application. Most have extra features beyond calling the script. -A limited amount of completion with <Tab> is supported. - - *rails-:Rscript* -:Rscript {script} {options} - Call ruby script/{script} {options}. Defaults to - calling script/console. - - *rails-:Rconsole* -:Rconsole {options} Obsolete. Call |:Rscript| instead. - - *rails-:Rrunner* -:[range]Rrunner {code} Executes {code} with script/runner. Differs from - :Rscript runner {code} in that the code is passed as - one argument. Also, |system()| is used instead of - |:!|. This is to help eliminate annoying "Press - ENTER" prompts. If a line number is given in the - range slot, the output is pasted into the buffer after - that line. - - *rails-:Rp* -:[range]Rp {code} Like :Rrunner, but call the Ruby p method on the - result. Literally "p begin {code} end". - - *rails-:Rpp* *rails-:Ry* -:[range]Rpp {code} Like :Rp, but with pp (pretty print) or y (YAML -:[range]Ry {code} output). - - *rails-:Rgenerate* -:Rgenerate {options} Calls script/generate {options}, and then edits the - first file generated. - - *rails-:Rdestroy* -:Rdestroy {options} Calls script/destroy {options}. - - *rails-:Rserver* -:Rserver {options} Launches script/server {options} in the background. - On win32, this means |!start|. On other systems, this - uses the --daemon option. - - *rails-:Rserver!* -:Rserver! {options} Same as |:Rserver|, only first attempts to kill any - other server using the same port. On non-Windows - systems, lsof must be installed for this to work. - -REFACTORING HELPERS *rails-refactoring* - -A few features are dedicated to helping you refactor your code. - -Partial Extraction ~ - *rails-partials* - -The :Rextract command can be used to extract a partial to a new file. - - *rails-:Rextract* -:[range]Rextract [{controller}/]{name} - Create a {name} partial from [range] lines (default: - current line). - - *rails-:Rpartial* -:[range]Rpartial [{controller}/]{name} - Obsolete alias for :Rextract. - -If this is your file, in app/views/blog/show.html.erb: > - - 1 <div> - 2 <h2><%= @post.title %></h2> - 3 <p><%= @post.body %></p> - 4 </div> - -And you issue this command: > - - :2,3Rextract post - -Your file will change to this: > - - 1 <div> - 2 <%= render :partial => 'post' %> - 3 </div> - -And app/views/blog/_post.html.erb will now contain: > - - 1 <h2><%= post.title %></h2> - 2 <p><%= post.body %></p> - -As a special case, if the file had looked like this: > - - 1 <% for object in @posts -%> - 2 <h2><%= object.title %></h2> - 3 <p><%= object.body %></p> - 4 <% end -%> -< -The end result would have been this: > - - 1 <%= render :partial => 'post', :collection => @posts %> -< -The easiest way to choose what to extract is to use |linewise-visual| mode. -Then, a simple > - :'<,'>Rextract blog/post -will suffice. (Note the use of a controller name in this example.) - -Migration Inversion ~ - *rails-migrations* *rails-:Rinvert* -:Rinvert In a migration, rewrite the self.up method into a - self.down method. If self.up is empty, the process is - reversed. This chokes on more complicated - instructions, but works reasonably well for simple - calls to create_table, add_column, and the like. - -INTEGRATION *rails-integration* - -Having one foot in Rails and one in Vim, rails.vim has two worlds with which -to interact. - -Integration with the Vim Universe ~ - *rails-vim-integration* - -A handful of Vim plugins are enhanced by rails.vim. All plugins mentioned can -be found at http://www.vim.org/. Cream and GUI menus (for lack of a better -place) are also covered in this section. - - *rails-:Rtree* -:Rtree [{arg}] If |NERDTree| is installed, open a tree for the - application root or the given subdirectory. - - *rails-:Rdbext* *rails-dbext* -:Rdbext [{environment}] This command is only provided when the |dbext| plugin - is installed. Loads the {environment} configuration - (defaults to $RAILS_ENV or development) from - config/database.yml and uses it to configure dbext. - The configuration is cached on a per application - basis. With dbext version 8.00 and newer, this - command is called automatically when needed. When - dbext is configured, you can execute SQL directly from - Vim: > - :Select * from posts order by id desc - :Update comments set author_id = 1 -< - *rails-surround* -The |surround| plugin available from vim.org enables adding and removing -"surroundings" like parentheses, quotes, and HTML tags. Even by itself, it is -quite useful for Rails development, particularly eRuby editing. When coupled -with this plugin, a few additional replacement surroundings are available in -eRuby files. See the |surround| documentation for details on how to use them. -The table below uses ^ to represent the position of the surrounded text. - -Key Surrounding ~ -= <%= ^ %> -- <% ^ -%> -# <%# ^ %> -<C-E> <% ^ -%>\n<% end -%> - -The last surrounding is particularly useful in insert mode with the following -map in one's vimrc. Use Alt+o to open a new line below the current one. This -works nicely even in a terminal (where most alt/meta maps will fail) because -most terminals send <M-o> as <Esc>o anyways. -> - imap <M-o> <Esc>o -< -One can also use the <C-E> surrounding in a plain Ruby file to append a bare -"end" on the following line. - - *rails-abolish* -Among the many features of |abolish| on vim.org is the ability to change the -inflection of the word under the cursor. For example, one can hit crs to -change from MixedCase to snake_case. This plugin adds two additional -inflections: crl for alternating between the singular and plural, and crt for -altering between tableize and classify. The latter is useful in changing -constructs like BlogPost.all to current_user.blog_posts.all and vice versa. - - *rails-cream* -This plugin provides a few additional key bindings if it is running under -Cream, the user friendly editor which uses Vim as a back-end. Ctrl+Enter -finds the file under the cursor (as in |rails-gf|), and Alt+[ and Alt+] find -the alternate (|rails-alternate|) and related (|rails-related|) files. - - *rails-menu* -If the GUI is running, a menu for several commonly used features is provided. -Also on this menu is a list of recently accessed projects. This list of -projects can persist across restarts if a 'viminfo' flag is set to enable -retaining certain global variables. If this interests you, add something like -the following to your vimrc: > - set viminfo^=! -< -Integration with the Rails Universe ~ - *rails-rails-integration* -The general policy of rails.vim is to focus exclusively on the Ruby on Rails -core. Supporting plugins and other add-ons to Rails has the potential to -rapidly get out of hand. However, a few pragmatic exceptions have been made. - - *rails-template-types* -Commands like :Rview use a hardwired list of extensions (erb, rjs, etc.) -when searching for files. In order to facilitate working with non-standard -template types, several popular extensions are featured in this list, -including haml, liquid, and mab (markaby). These extensions will disappear -once a related configuration option is added to rails.vim. - - *rails-rspec* -The presence of a spec directory causes several additional behaviors to -activate. :A knows about specs and will jump to them (but Test::Unit files -still get priority). The associated controller or model of a spec is -detected, so all navigation commands should work as expected inside a spec -file. :Rake in a spec runs just that spec, and in a model, controller, or -helper, runs the associated spec. - -|:Runittest| and |:Rfunctionaltest| lead double lives, handling model and -controller specs respectively. For helper and view specs, you can use -|:Rspec| or define your own navigation commands: -> - Rnavcommand spechelper spec/helpers -glob=**/* - \ -suffix=_helper_spec.rb -default=controller() - Rnavcommand specview spec/views -glob=**/* -suffix=_spec.rb -< -ABBREVIATIONS *rails-abbreviations* *rails-snippets* - -Abbreviations are "snippets lite". They may later be extracted into a -separate plugin, or removed entirely. - - *rails-:Rabbrev* -:Rabbrev List all Rails abbreviations. - -:Rabbrev {abbr} {expn} [{extra}] - Define a new Rails abbreviation. {extra} is permitted - if and only if {expn} ends with "(". - - *rails-:Rabbrev!* -:Rabbrev! {abbr} Remove an abbreviation. - -Rails abbreviations differ from regular abbreviations in that they only expand -after a <C-]> (see |i_CTRL-]|) or a <Tab> (if <Tab> does not work, it is -likely mapped by another plugin). If the abbreviation ends in certain -punctuation marks, additional expansions are possible. A few examples will -hopefully clear this up (all of the following are enabled by default in -appropriate file types). - -Command Sequence typed Resulting text ~ -Rabbrev rp( render :partial\ => rp( render(:partial => -Rabbrev rp( render :partial\ => rp<Tab> render :partial => -Rabbrev vs( validates_size_of vs( validates_size_of( -Rabbrev pa[ params pa[:id] params[:id] -Rabbrev pa[ params pa<C-]> params -Rabbrev pa[ params pa.inspect params.inspect -Rabbrev AR:: ActionRecord AR::Base ActiveRecord::Base -Rabbrev :a :action\ =>\ render :a<Tab> render :action => - -In short, ( expands on (, :: expands on . and :, and [ expands on . and [. -These trailing punctuation marks are NOT part of the final abbreviation, and -you cannot have two mappings that differ only by punctuation. - -You must escape spaces in your expansion, either as "\ " or as "<Space>". For -an abbreviation ending with "(", you may define where to insert the -parenthesis by splitting the expansion into two parts (divided by an unescaped -space). - -Many abbreviations are provided by default: use :Rabbrev to list them. They -vary depending on the type of file (models have different abbreviations than -controllers). There is one "smart" abbreviation, :c, which expands to -":controller => ", ":collection => ", or ":conditions => " depending on -context. - -SYNTAX HIGHLIGHTING *rails-syntax* - -Syntax highlighting is by and large a transparent process. For the full -effect, however, you need a colorscheme which accentuates rails.vim -extensions. One such colorscheme is vividchalk, available from vim.org. - -The following is a summary of the changes made by rails.vim to the standard -syntax highlighting. - - *rails-syntax-keywords* -Rails specific keywords are highlighted in a filetype specific manner. For -example, in a model, has_many is highlighted, whereas in a controller, -before_filter is highlighted. A wide variety of syntax groups are used but -they all link by default to railsMethod. - -If you feel a method has been wrongfully omitted, submit it to the -|rails-plugin-author|. - - *rails-syntax-classes* -Models, helpers, and controllers are given special highlighting. Depending on -the version of Vim installed, you may need a rails.vim aware colorscheme in -order to see this. Said colorscheme needs to provide highlighting for the -railsUserClass syntax group. - -The class names are determined by camelizing filenames from certain -directories of your application. If app/models/line_item.rb exists, the class -"LineItem" will be highlighted. - -The list of classes is refreshed automatically after certain commands like -|:Rgenerate|. Use |:Rrefresh| to trigger the process manually. - - *rails-syntax-assertions* -If you define custom assertions in test_helper.rb, these will be highlighted -in your tests. These are found by scanning test_helper.rb for lines of the -form " def assert_..." and extracting the method name. The railsUserMethod -syntax group is used. The list of assertions can be refreshed with -|:Rrefresh|. - - *rails-syntax-strings* -In the following line of code, the "?" in the conditions clause and the "ASC" -in the order clause will be highlighted: > - Post.find(:all, :conditions => ["body like ?","%e%"], :order => "title ASC") -< -A string literal using %Q<> or %<> delimiters will have its contents -highlighted as HTML. This is sometimes useful when writing helpers. > - link = %<<a href="http://www.vim.org">Vim</a>> -< - *rails-syntax-yaml* -YAML syntax highlighting has been extended to highlight eRuby, which can be -used in most Rails YAML files (including database.yml and fixtures). - -MANAGED VIM OPTIONS *rails-options* - -The following options are set local to buffers where the plugin is active. - - *rails-'shiftwidth'* *rails-'sw'* - *rails-'softtabstop'* *rails-'sts'* - *rails-'expandtab'* *rails-'et'* -A value of 2 is used for 'shiftwidth' (and 'softtabstop'), and 'expandtab' is -enabled. This is a strong convention in Rails, so the conventional wisdom -that this is a user preference has been ignored. - - *rails-'path'* *rails-'pa'* -All the relevant directories from your application are added to your 'path'. -This makes it easy to access a buried file: > - :find blog_controller.rb -< - *rails-'suffixesadd'* *rails-'sua'* -This is filetype dependent, but typically includes .rb, .rake, and several -others. This allows shortening the above example: > - :find blog_controller -< - *rails-'includeexpr'* *rails-'inex'* -The 'includeexpr' option is set to enable the magic described in |rails-gf|. - - *rails-'filetype'* *rails-'ft'* -The 'filetype' is sometimes adjusted for Rails files. Most notably, *.rxml -and *.rjs are treated as Ruby files, and files that have been falsely -identified as Mason sources are changed back to eRuby files (but only when -they are part of a Rails application). - - *rails-'completefunc'* *rails-'cfu'* -A 'completefunc' is provided (if not already set). It is very simple, as it -uses syntax highlighting to make its guess. See |i_CTRL-X_CTRL-U|. - -CONFIGURATION *rails-configuration* - -Very little configuration is actually required; this plugin automatically -detects your Rails application and adjusts Vim sensibly. - - *rails-:autocmd* *rails-autocommands* -If you would like to set your own custom Vim settings whenever a Rails file is -loaded, you can use an autocommand like the following in your vimrc: > - autocmd User Rails silent! Rlcd - autocmd User Rails map <buffer> <F9> :Rake<CR> -You can also have autocommands that only apply to certain types of files. -These are based off the information shown when running the |:Rails!| -command, with hyphens changed to periods. A few examples: > - autocmd User Rails.controller* iabbr <buffer> wsn wsdl_service_name - autocmd User Rails.model.arb* iabbr <buffer> vfo validates_format_of - autocmd User Rails.view.erb* imap <buffer> <C-Z> <%= %><C-O>3h -End all such Rails autocommands with asterisks, even if you have an exact -specification, to allow for more specific subtypes to be added in the future. -There is also a filename matching syntax: > - autocmd User Rails/config/environment.rb Rabbrev c config - autocmd User Rails/**/foo_bar.rb Rabbrev FB:: FooBar -Use the filetype based syntax whenever possible, reserving the filename based -syntax for more advanced cases. - - *macros/rails.vim* -If you have several commands to run on initialization for all file types, they -can be placed in a "macros/rails.vim" file in the 'runtimepath' (for example, -"~/.vim/macros/rails.vim"). This file is sourced by rails.vim each time a -Rails file is loaded. - - *config/rails.vim* -If you have settings particular to a specific project, they can be put in a -config/rails.vim file in the root directory of the application. The file is -sourced in the |sandbox| for security reasons. - - *rails-:Rset* -:Rset {option}[={value}] - Query or set a local option. This command may be - called directly, from an autocommand, or from - config/rails.vim. - -Options may be set in one of four scopes, which may be indicated by an -optional prefix. These scopes determine how broadly an option will apply. -Generally, the default scope is sufficient. - -Scope Description ~ -a: All files in one Rails application -b: Buffer (file) specific -g: Global to all applications -l: Local to method (same as b: in non-Ruby files) - -Options are shown below with their default scope, which should be omitted. -While you may override the scope with a prefix, this is rarely necessary and -oftentimes useless. (For example, setting g:task is useless because the -default rake task will apply before considering this option.) - -Option Meaning ~ -b:alternate Custom alternate file for :A, relative to the Rails root -b:controller Default controller for certain commands (e.g., :Rhelper) -b:model Default model for certain commands (e.g., :Rfixtures) -l:related Custom related file for :R, relative to the Rails root -a:root_url Root URL for commands like :Rpreview - -Examples: > - :Rset root_url=http://localhost:12345 - :Rset related=app/views/blog/edit.html.erb -< - *rails-modelines* -If |g:rails_modelines| is enabled, these options can also be set from -modelines near the beginning or end of the file. These modelines will always -set buffer-local options; scope should never be specified. Examples: > - # Rset task=db:schema:load - <%# Rset alternate=app/views/layouts/application.html.erb %> -Modelines can also be local to a method. Example: > - def test_comment - # rset alternate=app/models/comment.rb -These two forms differ only in case. - -Modelines are deprecated. - -GLOBAL SETTINGS *rails-global-settings* - -A few global variables control the behavior of this plugin. In general, they -can be enabled by setting them to 1 in your vimrc, and disabled by setting -them to 0. > - let g:rails_some_option=1 - let g:rails_some_option=0 -Most of these seldom need to be used. So seldom, in fact, that you should -notify the |rails-plugin-author| if you find any of them useful, as nearly all -are being considered for removal. - - *g:loaded_rails* > - let g:loaded_rails=1 -Set this include guard to prevent the plugin from being loaded. - - *g:rails_abbreviations* -Enable Rails abbreviations. See |rails-abbreviations|. Enabled by default. - - *g:rails_ctags_arguments* > - let g:rails_ctags_arguments='--languages=-javascript' -Additional arguments to pass to ctags from |:Rtags|. Defaults to ignoring -JavaScript files, since ctags has a tendency to choke on those. - - *g:rails_default_file* > - let g:rails_default_file='config/database.yml' -File to load when a new Rails application is created. Defaults to the README. - - *rails-screen* *g:rails_gnu_screen* > - let g:rails_gnu_screen=1 -Use GNU Screen or Tmux (if it is running) to launch |:Rscript| console and -|:Rserver| in the background. Enabled by default. - - *g:rails_history_size* > - let g:rails_history_size=5 -Number of projects to remember. Set to 0 to disable. See |rails-menu| for -information on retaining these projects across a restart. - - *g:rails_mappings* > - let g:rails_mappings=1 -Enables a few mappings (mostly for |rails-navigation|). Enabled by default. - - *g:rails_modelines* > - let g:rails_modelines=1 -Enable modelines like the following: > - # Rset task=db:schema:load -Modelines set buffer-local options using the :Rset command. -Also enables method specific modelines (note the case difference): > - def show - # rset preview=blog/show/1 -Modelines are deprecated and disabled by default. - - *g:rails_menu* > - let g:rails_menu=1 -When 2, a Rails menu is created. When 1, this menu is a submenu under the -Plugin menu. The default is 0, as the menu is slated for removal from future -versions of rails.vim. - - *g:rails_url* > - let g:rails_url='http://localhost:3000/' -Used for the |:Rpreview| command. Default is as shown above. Overridden by -b:rails_url. - - *g:rails_syntax* > - let g:rails_syntax=1 -When enabled, this tweaks the syntax highlighting to be more Rails friendly. -Enabled by default. See |rails-syntax|. - - *rails-tabs* *g:rails_tabstop* > - let g:rails_tabstop=4 -This option now requires the plugin railstab.vim from vim.org: - http://www.vim.org/scripts/script.php?script_id=2253 - -If your goal is simply just override this plugin's settings and use your own -custom 'shiftwidth', adjust things manually in an autocommand: > - autocmd User Rails set sw=4 sts=4 noet -This is highly discouraged: don't fight Rails. - -ABOUT *rails-about* *rails-plugin-author* - -This plugin was written by Tim Pope. Email all comments, complaints, and compliments to him at vim at tpope. org. - -The latest stable version can be found at - http://www.vim.org/scripts/script.php?script_id=1567 - -Bugs can be reported and the very latest development version can be retrieved -from GitHub: - https://github.com/tpope/vim-rails - git clone git://github.com/tpope/vim-rails.git - - *rails-license* -Copyright (c) Tim Pope. Distributed under the same terms as Vim itself. -See |license|. - - vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/snipMate.txt b/vim/doc/snipMate.txt deleted file mode 100644 index 521235d..0000000 --- a/vim/doc/snipMate.txt +++ /dev/null @@ -1,322 +0,0 @@ -*snipMate.txt* Plugin for using TextMate-style snippets in Vim. - -snipMate *snippet* *snippets* *snipMate* -Last Change: December 27, 2009 - -|snipMate-description| Description -|snipMate-syntax| Snippet syntax -|snipMate-usage| Usage -|snipMate-settings| Settings -|snipMate-features| Features -|snipMate-disadvantages| Disadvantages to TextMate -|snipMate-contact| Contact -|snipMate-license| License - -For Vim version 7.0 or later. -This plugin only works if 'compatible' is not set. -{Vi does not have any of these features.} - -============================================================================== -DESCRIPTION *snipMate-description* - -snipMate.vim implements some of TextMate's snippets features in Vim. A -snippet is a piece of often-typed text that you can insert into your -document using a trigger word followed by a <tab>. - -For instance, in a C file using the default installation of snipMate.vim, if -you type "for<tab>" in insert mode, it will expand a typical for loop in C: > - - for (i = 0; i < count; i++) { - - } - - -To go to the next item in the loop, simply <tab> over to it; if there is -repeated code, such as the "i" variable in this example, you can simply -start typing once it's highlighted and all the matches specified in the -snippet will be updated. To go in reverse, use <shift-tab>. - -============================================================================== -SYNTAX *snippet-syntax* - -Snippets can be defined in two ways. They can be in their own file, named -after their trigger in 'snippets/<filetype>/<trigger>.snippet', or they can be -defined together in a 'snippets/<filetype>.snippets' file. Note that dotted -'filetype' syntax is supported -- e.g., you can use > - - :set ft=html.eruby - -to activate snippets for both HTML and eRuby for the current file. - -The syntax for snippets in *.snippets files is the following: > - - snippet trigger - expanded text - more expanded text - -Note that the first hard tab after the snippet trigger is required, and not -expanded in the actual snippet. The syntax for *.snippet files is the same, -only without the trigger declaration and starting indentation. - -Also note that snippets must be defined using hard tabs. They can be expanded -to spaces later if desired (see |snipMate-indenting|). - -"#" is used as a line-comment character in *.snippets files; however, they can -only be used outside of a snippet declaration. E.g.: > - - # this is a correct comment - snippet trigger - expanded text - snippet another_trigger - # this isn't a comment! - expanded text -< -This should hopefully be obvious with the included syntax highlighting. - - *snipMate-${#}* -Tab stops ~ - -By default, the cursor is placed at the end of a snippet. To specify where the -cursor is to be placed next, use "${#}", where the # is the number of the tab -stop. E.g., to place the cursor first on the id of a <div> tag, and then allow -the user to press <tab> to go to the middle of it: - > - snippet div - <div id="${1}"> - ${2} - </div> -< - *snipMate-placeholders* *snipMate-${#:}* *snipMate-$#* -Placeholders ~ - -Placeholder text can be supplied using "${#:text}", where # is the number of -the tab stop. This text then can be copied throughout the snippet using "$#", -given # is the same number as used before. So, to make a C for loop: > - - snippet for - for (${2:i}; $2 < ${1:count}; $1++) { - ${4} - } - -This will cause "count" to first be selected and change if the user starts -typing. When <tab> is pressed, the "i" in ${2}'s position will be selected; -all $2 variables will default to "i" and automatically be updated if the user -starts typing. -NOTE: "$#" syntax is used only for variables, not for tab stops as in TextMate. - -Variables within variables are also possible. For instance: > - - snippet opt - <option value="${1:option}">${2:$1}</option> - -Will, as usual, cause "option" to first be selected and update all the $1 -variables if the user starts typing. Since one of these variables is inside of -${2}, this text will then be used as a placeholder for the next tab stop, -allowing the user to change it if he wishes. - -To copy a value throughout a snippet without supplying default text, simply -use the "${#:}" construct without the text; e.g.: > - - snippet foo - ${1:}bar$1 -< *snipMate-commands* -Interpolated Vim Script ~ - -Snippets can also contain Vim script commands that are executed (via |eval()|) -when the snippet is inserted. Commands are given inside backticks (`...`); for -TextMates's functionality, use the |system()| function. E.g.: > - - snippet date - `system("date +%Y-%m-%d")` - -will insert the current date, assuming you are on a Unix system. Note that you -can also (and should) use |strftime()| for this example. - -Filename([{expr}] [, {defaultText}]) *snipMate-filename* *Filename()* - -Since the current filename is used often in snippets, a default function -has been defined for it in snipMate.vim, appropriately called Filename(). - -With no arguments, the default filename without an extension is returned; -the first argument specifies what to place before or after the filename, -and the second argument supplies the default text to be used if the file -has not been named. "$1" in the first argument is replaced with the filename; -if you only want the filename to be returned, the first argument can be left -blank. Examples: > - - snippet filename - `Filename()` - snippet filename_with_default - `Filename('', 'name')` - snippet filename_foo - `filename('$1_foo')` - -The first example returns the filename if it the file has been named, and an -empty string if it hasn't. The second returns the filename if it's been named, -and "name" if it hasn't. The third returns the filename followed by "_foo" if -it has been named, and an empty string if it hasn't. - - *multi_snip* -To specify that a snippet can have multiple matches in a *.snippets file, use -this syntax: > - - snippet trigger A description of snippet #1 - expand this text - snippet trigger A description of snippet #2 - expand THIS text! - -In this example, when "trigger<tab>" is typed, a numbered menu containing all -of the descriptions of the "trigger" will be shown; when the user presses the -corresponding number, that snippet will then be expanded. - -To create a snippet with multiple matches using *.snippet files, -simply place all the snippets in a subdirectory with the trigger name: -'snippets/<filetype>/<trigger>/<name>.snippet'. - -============================================================================== -USAGE *snipMate-usage* - - *'snippets'* *g:snippets_dir* -Snippets are by default looked for any 'snippets' directory in your -'runtimepath'. Typically, it is located at '~/.vim/snippets/' on *nix or -'$HOME\vimfiles\snippets\' on Windows. To change that location or add another -one, change the g:snippets_dir variable in your |.vimrc| to your preferred -directory, or use the |ExtractSnips()|function. This will be used by the -|globpath()| function, and so accepts the same syntax as it (e.g., -comma-separated paths). - -ExtractSnipsFile({directory}, {filetype}) *ExtractSnipsFile()* *.snippets* - -ExtractSnipsFile() extracts the specified *.snippets file for the given -filetype. A .snippets file contains multiple snippet declarations for the -filetype. It is further explained above, in |snippet-syntax|. - -ExtractSnips({directory}, {filetype}) *ExtractSnips()* *.snippet* - -ExtractSnips() extracts *.snippet files from the specified directory and -defines them as snippets for the given filetype. The directory tree should -look like this: 'snippets/<filetype>/<trigger>.snippet'. If the snippet has -multiple matches, it should look like this: -'snippets/<filetype>/<trigger>/<name>.snippet' (see |multi_snip|). - -ResetAllSnippets() *ResetAllSnippets()* -ResetAllSnippets() removes all snippets from memory. This is useful to put at -the top of a snippet setup file for if you would like to |:source| it multiple -times. - -ResetSnippets({filetype}) *ResetSnippets()* -ResetSnippets() removes all snippets from memory for the given filetype. - -ReloadAllSnippets() *ReloadAllSnippets()* -ReloadAllSnippets() reloads all snippets for all filetypes. This is useful for -testing and debugging. - -ReloadSnippets({filetype}) *ReloadSnippets()* -ReloadSnippets() reloads all snippets for the given filetype. - - *list-snippets* *i_CTRL-R_<Tab>* -If you would like to see what snippets are available, simply type <c-r><tab> -in the current buffer to show a list via |popupmenu-completion|. - -============================================================================== -SETTINGS *snipMate-settings* *g:snips_author* - -The g:snips_author string (similar to $TM_FULLNAME in TextMate) should be set -to your name; it can then be used in snippets to automatically add it. E.g.: > - - let g:snips_author = 'Hubert Farnsworth' - snippet name - `g:snips_author` -< - *snipMate-expandtab* *snipMate-indenting* -If you would like your snippets to be expanded using spaces instead of tabs, -just enable 'expandtab' and set 'softtabstop' to your preferred amount of -spaces. If 'softtabstop' is not set, 'shiftwidth' is used instead. - - *snipMate-remap* -snipMate does not come with a setting to customize the trigger key, but you -can remap it easily in the two lines it's defined in the 'after' directory -under 'plugin/snipMate.vim'. For instance, to change the trigger key -to CTRL-J, just change this: > - - ino <tab> <c-r>=TriggerSnippet()<cr> - snor <tab> <esc>i<right><c-r>=TriggerSnippet()<cr> - -to this: > - ino <c-j> <c-r>=TriggerSnippet()<cr> - snor <c-j> <esc>i<right><c-r>=TriggerSnippet()<cr> - -============================================================================== -FEATURES *snipMate-features* - -snipMate.vim has the following features among others: - - The syntax of snippets is very similar to TextMate's, allowing - easy conversion. - - The position of the snippet is kept transparently (i.e. it does not use - markers/placeholders written to the buffer), which allows you to escape - out of an incomplete snippet, something particularly useful in Vim. - - Variables in snippets are updated as-you-type. - - Snippets can have multiple matches. - - Snippets can be out of order. For instance, in a do...while loop, the - condition can be added before the code. - - [New] File-based snippets are supported. - - [New] Triggers after non-word delimiters are expanded, e.g. "foo" - in "bar.foo". - - [New] <shift-tab> can now be used to jump tab stops in reverse order. - -============================================================================== -DISADVANTAGES *snipMate-disadvantages* - -snipMate.vim currently has the following disadvantages to TextMate's snippets: - - There is no $0; the order of tab stops must be explicitly stated. - - Placeholders within placeholders are not possible. E.g.: > - - '<div${1: id="${2:some_id}}">${3}</div>' -< - In TextMate this would first highlight ' id="some_id"', and if - you hit delete it would automatically skip ${2} and go to ${3} - on the next <tab>, but if you didn't delete it it would highlight - "some_id" first. You cannot do this in snipMate.vim. - - Regex cannot be performed on variables, such as "${1/.*/\U&}" - - Placeholders cannot span multiple lines. - - Activating snippets in different scopes of the same file is - not possible. - -Perhaps some of these features will be added in a later release. - -============================================================================== -CONTACT *snipMate-contact* *snipMate-author* - -To contact the author (Michael Sanders), please email: - msanders42+snipmate <at> gmail <dot> com - -I greatly appreciate any suggestions or improvements offered for the script. - -============================================================================== -LICENSE *snipMate-license* - -snipMate is released under the MIT license: - -Copyright 2009-2010 Michael Sanders. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The software is provided "as is", without warranty of any kind, express or -implied, including but not limited to the warranties of merchantability, -fitness for a particular purpose and noninfringement. In no event shall the -authors or copyright holders be liable for any claim, damages or other -liability, whether in an action of contract, tort or otherwise, arising from, -out of or in connection with the software or the use or other dealings in the -software. - -============================================================================== - -vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/supertab.txt b/vim/doc/supertab.txt deleted file mode 100644 index 038bcb5..0000000 --- a/vim/doc/supertab.txt +++ /dev/null @@ -1,307 +0,0 @@ -*supertab.txt* - -Authors: - Original: Gergely Kontra <kgergely@mcl.hu> - Current: Eric Van Dewoestine <ervandew@gmail.com> (as of version 0.4) - -Contributors: - Christophe-Marie Duquesne <chm.duquesne@gmail.com> (documentation) - -Please direct all correspondence to Eric. - -This plugin is licensed under the terms of the BSD License. Please see -supertab.vim for the license in its entirety. - -============================================================================== -Supertab *supertab* - -1. Introduction |supertab-intro| -2. Supertab Usage |supertab-usage| -3. Supertab Options |supertab-options| - Default completion type |supertab-defaultcompletion| - Secondary default completion type |supertab-contextdefault| - Completion contexts |supertab-completioncontexts| - Context text |supertab-contexttext| - Context Discover |supertab-contextdiscover| - Example |supertab-contextexample| - Completion Duration |supertab-duration| - Preventing Completion After/Before... |supertab-preventcomplete| - Changing default mapping |supertab-forwardbackward| - Inserting true tabs |supertab-mappingtabliteral| - Enhanced longest match support |supertab-longestenhanced| - Preselecting the first entry |supertab-longesthighlight| - -============================================================================== -1. Introduction *supertab-intro* - -Supertab is a plugin which allows you to perform all your insert completion -(|ins-completion|) using the tab key. - -Supertab requires Vim version 7.0 or above. - -============================================================================== -2. Supertab usage *supertab-usage* - -Using Supertab is as easy as hitting <Tab> or <S-Tab> (shift+tab) while in -insert mode, with at least one non whitespace character before the cursor, to -start the completion and then <Tab> or <S-Tab> again to cycle forwards or -backwards through the available completions. - -Example ('|' denotes the cursor location): - -bar -baz -b|<Tab> Hitting <Tab> here will start the completion, allowing you to - then cycle through the suggested words ('bar' and 'baz'). - -============================================================================== -3. Supertab Options *supertab-options* - -Supertab is configured via several global variables that you can set in your -|vimrc| file according to your needs. Below is a comprehensive list of -the variables available. - - -Default Completion Type *supertab-defaultcompletion* - *g:SuperTabDefaultCompletionType* - -g:SuperTabDefaultCompletionType (default value: "<c-p>") - -Used to set the default completion type. There is no need to escape this -value as that will be done for you when the type is set. - - Example: setting the default completion to 'user' completion: - - let g:SuperTabDefaultCompletionType = "<c-x><c-u>" - -Note: a special value of 'context' is supported which will result in -super tab attempting to use the text preceding the cursor to decide which -type of completion to attempt. Currently super tab can recognize method -calls or attribute references via '.', '::' or '->', and file path -references containing '/'. - - let g:SuperTabDefaultCompletionType = "context" - - /usr/l<tab> # will use filename completion - myvar.t<tab> # will use user completion if completefunc set, - # or omni completion if omnifunc set. - myvar-><tab> # same as above - -When using context completion, super tab will fall back to a secondary default -completion type set by |g:SuperTabContextDefaultCompletionType|. - -Note: once the buffer has been initialized, changing the value of this setting -will not change the default complete type used. If you want to change the -default completion type for the current buffer after it has been set, perhaps -in an ftplugin, you'll need to call SuperTabSetDefaultCompletionType like so, -supplying the completion type you wish to switch to: - - call SuperTabSetDefaultCompletionType("<c-x><c-u>") - - -Secondary default completion type *supertab-contextdefault* - *g:SuperTabContextDefaultCompletionType* - -g:SuperTabContextDefaultCompletionType (default value: "<c-p>") - -Sets the default completion type used when g:SuperTabDefaultCompletionType is -set to 'context' and no completion type is returned by any of the configured -contexts. - - -Completion contexts *supertab-completioncontexts* - *g:SuperTabCompletionContexts* - -g:SuperTabCompletionContexts (default value: ['s:ContextText']) - -Sets the list of contexts used for context completion. This value should -be a list of function names which provide the context implementation. - -When supertab starts the default completion, each of these contexts will be -consulted, in the order they were supplied, to determine the completion type -to use. If a context returns a completion type, that type will be used, -otherwise the next context in the list will be consulted. If after executing -all the context functions, no completion type has been determined, then the -value of g:SuperTabContextDefaultCompletionType will be used. - -Built in completion contexts: - - s:ContextText *supertab-contexttext* - - The text context will examine the text near the cursor to decide which type - of completion to attempt. Currently the text context can recognize method - calls or attribute references via '.', '::' or '->', and file path - references containing '/'. - - /usr/l<tab> # will use filename completion - myvar.t<tab> # will use user completion if completefunc set, or - # omni completion if omnifunc set. - myvar-><tab> # same as above - - Supported configuration attributes: - - g:SuperTabContextTextFileTypeExclusions - List of file types for which the text context will be skipped. - - g:SuperTabContextTextOmniPrecedence - List of omni completion option names in the order of precedence that they - should be used if available. By default, user completion will be given - precedence over omni completion, but you can use this variable to give - omni completion higher precedence by placing it first in the list. - - s:ContextDiscover *supertab-contextdiscover* - - This context will use the 'g:SuperTabContextDiscoverDiscovery' variable to - determine the completion type to use. It will evaluate each value, in the - order they were defined, until a variable evaluates to a non-zero or - non-empty value, then the associated completion type is used. - - Supported configuration properties: - - g:SuperTabContextDiscoverDiscovery - List of variable:completionType mappings. - - Example context configuration: *supertab-contextexample* - - let g:SuperTabCompletionContexts = ['s:ContextText', 's:ContextDiscover'] - let g:SuperTabContextTextOmniPrecedence = ['&omnifunc', '&completefunc'] - let g:SuperTabContextDiscoverDiscovery = - \ ["&completefunc:<c-x><c-u>", "&omnifunc:<c-x><c-o>"] - - In addition to the default completion contexts, you can plug in your own - implementation by creating a globally accessible function that returns - the completion type to use (eg. "\<c-x>\<c-u>"). - - function MyTagContext() - if filereadable(expand('%:p:h') . '/tags') - return "\<c-x>\<c-]>" - endif - " no return will result in the evaluation of the next - " configured context - endfunction - let g:SuperTabCompletionContexts = - \ ['MyTagContext', 's:ContextText', 's:ContextDiscover'] - - Note: supertab also supports the b:SuperTabCompletionContexts variable - allowing you to set the list of contexts separately for the current buffer, - like from an ftplugin for example. - - -Completion Duration *supertab-duration* - *g:SuperTabRetainCompletionDuration* - -g:SuperTabRetainCompletionDuration (default value: 'insert') - -Determines if, and for how long, the current completion type is retained. -The possible values include: -'completion' - The current completion type is only retained for the - current completion. Once you have chosen a completion - result or exited the completion mode, the default - completion type is restored. -'insert' - The current completion type is saved until you exit insert - mode (via ESC). Once you exit insert mode the default - completion type is restored. (supertab default) -'session' - The current completion type is saved for the duration of - your vim session or until you enter a different completion - mode. - - -Preventing completion after... *supertab-preventcomplete* - *g:SuperTabNoCompleteBefore* - *g:SuperTabNoCompleteAfter* - -g:SuperTabNoCompleteBefore (default value: []) -g:SuperTabNoCompleteAfter (default value: ['\s']) - -These two variables are used to control when supertab will attempt completion -or instead fall back to inserting a literal <tab>, by specifying a list of -patterns which are tested against the text before and after the current cursor -position that when matched, prevent completion. So if you don't want supertab -to start completion after a comma or space, you can set -g:SuperTabNoCompleteAfter to [',', '\s']. - -Note: That a buffer local version of these variables -(b:SuperTabNoCompleteBefore, b:SuperTabNoCompleteAfter) is also supported -should you wish to have different values depending on the file type for -instance. - -Changing the default mapping *supertab-forwardbackward* - *g:SuperTabMappingForward* - *g:SuperTabMappingBackward* - -g:SuperTabMappingForward (default value: '<tab>') -g:SuperTabMappingBackward (default value: '<s-tab>') - -These two variables allow you to set the keys used to kick off the current -completion. By default this is <tab> and <s-tab>. To change to something -like <c-space> and <s-c-space>, you can add the following to your |vimrc|. - - let g:SuperTabMappingForward = '<c-space>' - let g:SuperTabMappingBackward = '<s-c-space>' - -Note: if the above does not have the desired effect (which may happen in -console version of vim), you can try the following mappings. Although the -backwards mapping still doesn't seem to work in the console for me, your -milage may vary. - - let g:SuperTabMappingForward = '<nul>' - let g:SuperTabMappingBackward = '<s-nul>' - - -Inserting true tabs *supertab-mappingtabliteral* - *g:SuperTabMappingTabLiteral* - -g:SuperTabMappingTabLiteral (default value: '<c-tab>') - -Sets the key mapping used to insert a literal tab where supertab would -otherwise attempt to kick off insert completion. The default is '<c-tab>' -(ctrl-tab) which unfortunately might not work at the console. So if you are -using a console vim and want this functionality, you may have to change it to -something that is supported. Alternatively, you can escape the <tab> with -<c-v> (see |i_CTRL-V| for more infos). - - -Enhanced longest match support *supertab-longestenhanced* - *g:SuperTabLongestEnhanced* - -g:SuperTabLongestEnhanced (default value: 0) - -When enabled and 'longest' is in your |completeopt| setting, supertab will -provide an enhanced longest match support where typing one or more letters and -hitting tab again while in a completion mode will complete the longest common -match using the new text in the buffer. - -For example, say you have a buffer with the following contents: - FooBarFoo - FooBar - Foo - FooBarBaz -And you then type F<tab>. Vim's builtin longest support will complete the -longest common text 'Foo' and offer 'FooBarFoo', 'FooBar', 'Foo', and -'FooBarBaz' as possible completions. With supertab's longest match -enhancement disabled, typing B<tab> while still in the completion mode will -end up completing 'FooBarBaz' or 'FooBarFoo' depending your settings, instead -of the next longest common match of 'FooBar'. With supertab's enhanced -longest match feature enabled, the typing of B<tab> will result in the next -longest text being completed. - - -Preselecting the first entry *supertab-longesthighlight* - *g:SuperTabLongestHighlight* - -g:SuperTabLongestHighlight (default value: 0) - -Sets whether or not to pre-highlight the first match when completeopt has the -popup menu enabled and the 'longest' option as well. When enabled, <tab> will -kick off completion and pre-select the first entry in the popup menu, allowing -you to simply hit <enter> to use it. - - -Mapping <cr> to end completion *supertab-crmapping* - *g:SuperTabCrMapping* - -g:SuperTabCrMapping (default value: 1) - -When enabled, <cr> will cancel completion mode preserving the current text. - -vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/surround.txt b/vim/doc/surround.txt deleted file mode 100644 index 4387fa2..0000000 --- a/vim/doc/surround.txt +++ /dev/null @@ -1,222 +0,0 @@ -*surround.txt* Plugin for deleting, changing, and adding "surroundings" - -Author: Tim Pope <vimNOSPAM@tpope.info> *surround-author* -License: Same terms as Vim itself (see |license|) - -This plugin is only available if 'compatible' is not set. - -INTRODUCTION *surround* - -This plugin is a tool for dealing with pairs of "surroundings." Examples -of surroundings include parentheses, quotes, and HTML tags. They are -closely related to what Vim refers to as |text-objects|. Provided -are mappings to allow for removing, changing, and adding surroundings. - -Details follow on the exact semantics, but first, consider the following -examples. An asterisk (*) is used to denote the cursor position. - - Old text Command New text ~ - "Hello *world!" ds" Hello world! - [123+4*56]/2 cs]) (123+456)/2 - "Look ma, I'm *HTML!" cs"<q> <q>Look ma, I'm HTML!</q> - if *x>3 { ysW( if ( x>3 ) { - my $str = *whee!; vlllls' my $str = 'whee!'; - -While a few features of this plugin will work in older versions of Vim, -Vim 7 is recommended for full functionality. - -MAPPINGS *surround-mappings* - -Delete surroundings is *ds* . The next character given determines the target -to delete. The exact nature of the target is explained in |surround-targets| -but essentially it is the last character of a |text-object|. This mapping -deletes the difference between the "i"nner object and "a"n object. This is -easiest to understand with some examples: - - Old text Command New text ~ - "Hello *world!" ds" Hello world! - (123+4*56)/2 ds) 123+456/2 - <div>Yo!*</div> dst Yo! - -Change surroundings is *cs* . It takes two arguments, a target like with -|ds|, and a replacement. Details about the second argument can be found -below in |surround-replacements|. Once again, examples are in order. - - Old text Command New text ~ - "Hello *world!" cs"' 'Hello world!' - "Hello *world!" cs"<q> <q>Hello world!</q> - (123+4*56)/2 cs)] [123+456]/2 - (123+4*56)/2 cs)[ [ 123+456 ]/2 - <div>Yo!*</div> cst<p> <p>Yo!</p> - -*ys* takes a valid Vim motion or text object as the first object, and wraps -it using the second argument as with |cs|. (Unfortunately there's no good -mnemonic for "ys".) - - Old text Command New text ~ - Hello w*orld! ysiw) Hello (world)! - -As a special case, *yss* operates on the current line, ignoring leading -whitespace. - - Old text Command New text ~ - Hello w*orld! yssB {Hello world!} - -There is also *yS* and *ySS* which indent the surrounded text and place it -on a line of its own. - -In visual mode, a simple "s" with an argument wraps the selection. This is -referred to as the *vS* mapping, although ordinarily there will be -additional keystrokes between the v and s. In linewise visual mode, the -surroundings are placed on separate lines and indented. In blockwise visual -mode, each line is surrounded. - -A "gS" in visual mode, known as *vgS* , behaves similarly. In linewise visual -mode, the automatic indenting is surpressed. In blockwise visual mode, this -enables surrounding past the end of the like with 'virtualedit' set (there -seems to be no way in Vim Script to differentiate between a jagged end of line -selection and a virtual block selected past the end of the line, so two maps -were needed). - -Additionally, there is a legacy "s" or *vs* mapping which is basically the -same as |vS|. Due to popular demand of wanting to use "s" as Vim does to mean -replacing the selection (also available as "c"), this mapping is going away. -If you were one of these people and would like to disable "s" with the current -release, indicate this to surround.vim by assigning the "s" mapping to -something else. -> - xmap <Leader>s <Plug>Vsurround -< - *i_CTRL-G_s* *i_CTRL-G_S* -Finally, there is an experimental insert mode mapping on <C-G>s and <C-S>. -Beware that the latter won't work on terminals with flow control (if you -accidentally freeze your terminal, use <C-Q> to unfreeze it). The mapping -inserts the specified surroundings and puts the cursor between them. If, -immediately after the mapping and before the replacement, a second <C-S> or -carriage return is pressed, the prefix, cursor, and suffix will be placed on -three separate lines. <C-G>S (not <C-G>s) also exhibits this behavior. - -TARGETS *surround-targets* - -The |ds| and |cs| commands both take a target as their first argument. The -possible targets are based closely on the |text-objects| provided by Vim. -In order for a target to work, the corresponding text object must be -supported in the version of Vim used (Vim 7 adds several text objects, and -thus is highly recommended). All targets are currently just one character. - -Eight punctuation marks, (, ), {, }, [, ], <, and >, represent themselves -and their counterparts. If the opening mark is used, contained whitespace is -also trimmed. The targets b, B, r, and a are aliases for ), }, ], and > -(the first two mirror Vim; the second two are completely arbitrary and -subject to change). - -Three quote marks, ', ", `, represent themselves, in pairs. They are only -searched for on the current line. - -A t is a pair of HTML or XML tags. See |tag-blocks| for details. Remember -that you can specify a numerical argument if you want to get to a tag other -than the innermost one. - -The letters w, W, and s correspond to a |word|, a |WORD|, and a |sentence|, -respectively. These are special in that they have nothing to delete, and -used with |ds| they are a no-op. With |cs|, one could consider them a -slight shortcut for ysi (cswb == ysiwb, more or less). - -A p represents a |paragraph|. This behaves similarly to w, W, and s above; -however, newlines are sometimes added and/or removed. - -REPLACEMENTS *surround-replacements* - -A replacement argument is a single character, and is required by |cs|, |ys|, -and |vs|. Undefined replacement characters (with the exception of alphabetic -characters) default to placing themselves at the beginning and end of the -destination, which can be useful for characters like / and |. - -If either ), }, ], or > is used, the text is wrapped in the appropriate pair -of characters. Similar behavior can be found with (, {, and [ (but not <), -which append an additional space to the inside. Like with the targets above, -b, B, r, and a are aliases for ), }, ], and >. To fulfill the common need for -code blocks in C-style languages, <C-}> (which is really <C-]>) adds braces on -lines separate from the content. - -If t or < is used, Vim prompts for an HTML/XML tag to insert. You may specify -attributes here and they will be stripped from the closing tag. End your -input by pressing <CR> or >. If <C-T> is used, the tags will appear on lines -by themselves. - -A deprecated replacement of a LaTeX environment is provided on \ and l. The -name of the environment and any arguments will be input from a prompt. This -will be removed once a more fully functional customization system is -implemented. The following shows the resulting environment from -csp\tabular}{lc<CR> -> - \begin{tabular}{lc} - \end{tabular} -< -CUSTOMIZING *surround-customizing* - -The following adds a potential replacement on "-" (ASCII 45) in PHP files. -(To determine the ASCII code to use, :echo char2nr("-")). The carriage -return will be replaced by the original text. -> - autocmd FileType php let b:surround_45 = "<?php \r ?>" -< -This can be used in a PHP file as in the following example. - - Old text Command New text ~ - print "Hello *world!" yss- <?php print "Hello world!" ?> - -Additionally, one can use a global variable for globally available -replacements. -> - let g:surround_45 = "<% \r %>" - let g:surround_61 = "<%= \r %>" -< -Advanced, experimental, and subject to change: One can also prompt for -replacement text. The syntax for this is to surround the replacement in pairs -of low numbered control characters. If this sounds confusing, that's because -it is (but it makes the parsing easy). Consider the following example for a -LaTeX environment on the "l" replacement. -> - let g:surround_108 = "\\begin{\1environment: \1}\r\\end{\1\1}" -< -When this replacement is used, the user is prompted with an "environment: " -prompt for input. This input is inserted between each set of \1's. -Additional inputs up to \7 can be used. - -Furthermore, one can specify a regular expression substitution to apply. -> - let g:surround_108 = "\\begin{\1environment: \1}\r\\end{\1\r}.*\r\1}" -< -This will remove anything after the first } in the input when the text is -placed within the \end{} slot. The first \r marks where the pattern begins, -and the second where the replacement text begins. - -Here's a second example for creating an HTML <div>. The substitution cleverly -prompts for an id, but only adds id="" if it is non-blank. You may have to -read this one a few times slowly before you understand it. -> - let g:surround_{char2nr("d")} = "<div\1id: \r..*\r id=\"&\"\1>\r</div>" -< -Inputting text replacements is a proof of concept at this point. The ugly, -unintuitive interface and the brevity of the documentation reflect this. - -Finally, It is possible to always append a string to surroundings in insert -mode (and only insert mode). This is useful with certain plugins and mappings -that allow you to jump to such markings. -> - let g:surround_insert_tail = "<++>" -< -ISSUES *surround-issues* - -Vim could potentially get confused when deleting/changing occurs at the very -end of the line. Please report any repeatable instances of this. - -Do we need to use |inputsave()|/|inputrestore()| with the tag replacement? - -Indenting is handled haphazardly. Need to decide the most appropriate -behavior and implement it. Right now one can do :let b:surround_indent = 1 -(or the global equivalent) to enable automatic re-indenting by Vim via |=|; -should this be the default? - - vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/syntastic.txt b/vim/doc/syntastic.txt deleted file mode 100644 index f0cede3..0000000 --- a/vim/doc/syntastic.txt +++ /dev/null @@ -1,574 +0,0 @@ -*syntastic.txt* Syntax checking on the fly has never been so pimp. -*syntastic* - - - It's a bird! It's a plane! ZOMG It's ... ~ - - _____ __ __ _ ~ - / ___/__ ______ / /_____ ______/ /_(_)____ ~ - \__ \/ / / / __ \/ __/ __ `/ ___/ __/ / ___/ ~ - ___/ / /_/ / / / / /_/ /_/ (__ ) /_/ / /__ ~ - /____/\__, /_/ /_/\__/\__,_/____/\__/_/\___/ ~ - /____/ ~ - - - - Reference Manual~ - - -============================================================================== -CONTENTS *syntastic-contents* - - 1.Intro...................................|syntastic-intro| - 2.Functionality provided..................|syntastic-functionality| - 2.1.The statusline flag...............|syntastic-statusline-flag| - 2.2.Error signs.......................|syntastic-error-signs| - 2.3.Error window......................|syntastic-error-window| - 3.Commands................................|syntastic-commands| - 4.Options.................................|syntastic-options| - 5.Writing syntax checkers.................|syntastic-syntax-checkers| - 6.About...................................|syntastic-about| - 7.Changelog...............................|syntastic-changelog| - 8.Credits.................................|syntastic-credits| - 9.License.................................|syntastic-license| - - -============================================================================== -1. Intro *syntastic-intro* - -Syntastic is a syntax checking plugin that runs files through external syntax -checkers. This can be done on demand, or automatically as files are saved and -opened. If syntax errors are detected, the user is notified and is happy -because they didn't have to compile their code or execute their script to find -them. - -Syntastic comes in two parts: the syntax checker plugins, and the core script -(i.e. syntastic.vim). The syntax checker plugins are defined on a per-filetype -basis where each one wraps up an external syntax checking program. The core -script delegates off to these plugins and uses their output to provide the -syntastic functionality. At the time of this writing, syntax checking plugins -exist for c, coffee, cpp, css, cucumber, cuda, docbk, erlang, eruby, fortran, -go, haml, haskell, html, javascript, less, lua, matlab, perl, php, puppet, -python, ruby, sass/scss, sh, tcl, tex, vala, xhtml, xml, xslt, zpt - -Take a look in the syntax_checkers directory for the most up to date list. - -If your language is not supported then see |syntastic-syntax-checkers| for -details on how to implement a syntax checking plugin, and be sure to send me a -patch ;-) - -This plugin is currently only recommended for *nix users. It is functional on -Windows, but since the syntax checking plugins shell out, the command window -briefly appears whenever one is executed. - - -============================================================================== -2. Functionality provided *syntastic-functionality* - -Syntax checking can be done automatically or on demand (see -|'syntastic_mode_map'| for configuring this). - -When syntax checking is done, the features below can be used to notify the -user of errors. See |syntastic-options| for how to configure and -activate/deactivate these features. - - * A configurable statusline flag - * Lines with errors can have |signs| placed beside them - where a different - sign is used for errors and warnings. - * A |location-list| can be displayed with error messages for erroneous - buffers. - * Offending parts of lines can be highlighted (this functionality is only - provided by some syntax checkers). - * Balloons (if compiled in) can be used to display error messages for - erroneous lines when hovering the mouse over them. - - -Note: This functionality is only available if a syntax checker plugin is -present for the filetype of the buffer in question. See -|syntastic-syntax-checkers| for details. - ------------------------------------------------------------------------------- -2.1. The statusline flag *syntastic-statusline-flag* - -To use the statusline flag, this must appear in your |'statusline'| setting > - %{SyntasticStatuslineFlag()} -< -Something like this could be more useful: > - set statusline+=%#warningmsg# - set statusline+=%{SyntasticStatuslineFlag()} - set statusline+=%* -< -When syntax errors are detected a flag will be shown. The content of the flag -is derived from the |syntastic_stl_format| option ------------------------------------------------------------------------------- -2.2. Error signs *syntastic-error-signs* - -Syntastic uses the |:sign| commands to mark lines with errors and warnings in -the sign column. To enable this feature, use the |'syntastic_enable_signs'| -option. - ------------------------------------------------------------------------------- -2.3. The error window *:Errors* *syntastic-error-window* - -You can use the :Errors command to display the errors for the current buffer -in the |location-list|. - -Note that when you use :Errors, the current location list is overwritten with -Syntastic's own location list. - - -============================================================================== -3. Commands *syntastic-commands* - -:Errors *:SyntasticErrors* - -When errors have been detected, use this command to pop up the |location-list| -and display the error messages. - - -:SyntasticToggleMode *:SyntasticToggleMode* - -Toggles syntastic between active and passive mode. See |'syntastic_mode_map'| -for more info. - - -:SyntasticCheck *:SyntasticCheck* - -Manually cause a syntax check to be done. Useful in passive mode, or if the -current filetype is set to passive. See |'syntastic_mode_map'| for more info. - - -============================================================================== -4. Options *syntastic-options* - - - *'syntastic_check_on_open'* -Default: 0 -If enabled, syntastic will do syntax checks when buffers are first loaded as -well as on saving > - let g:syntastic_check_on_open=1 -< - - *'syntastic_echo_current_error'* -Default: 1 -If enabled, syntastic will error message associated with the current line to -the command window. If multiple errors are found, the first will be used. > - let g:syntastic_echo_current_error=1 -< - - *'syntastic_enable_signs'* -Default: 1 -Use this option to tell syntastic whether to use the |:sign| interface to mark -syntax errors: > - let g:syntastic_enable_signs=1 -< - - *'syntastic_enable_balloons'* -Default: 1 -Use this option to tell syntastic whether to display error messages in balloons -when the mouse is hovered over erroneous lines: > - let g:syntastic_enable_balloons = 1 -< -Note that vim must be compiled with |+balloon_eval|. - - *'syntastic_enable_highlighting'* -Default: 1 -Use this option to tell syntastic whether to use syntax highlighting to mark -errors (where possible). Highlighting can be turned off with the following > - let g:syntastic_enable_highlighting = 0 -< - - *'syntastic_auto_jump'* -Default: 0 -Enable this option if you want the cursor to jump to the first detected error -when saving or opening a file: > - let g:syntastic_auto_jump=1 -< - - *'syntastic_auto_loc_list'* -Default: 2 -Use this option to tell syntastic to automatically open and/or close the -|location-list| (see |syntastic-error-window|). - -When set to 0 the error window will not be opened or closed automatically. > - let g:syntastic_auto_loc_list=0 -< - -When set to 1 the error window will be automatically opened when errors are -detected, and closed when none are detected. > - let g:syntastic_auto_loc_list=1 -< -When set to 2 the error window will be automatically closed when no errors are -detected, but not opened automatically. > - let g:syntastic_auto_loc_list=2 -< - - *'syntastic_loc_list_height'* -Default: 10 -Use this option to specify the height of the location lists that syntastic -opens. > - let g:syntastic_loc_list_height=5 -< - - - *'syntastic_mode_map'* -Default: { "mode": "active", - "active_filetypes": [], - "passive_filetypes": [] } - -Use this option to fine tune when automatic syntax checking is done (or not -done). - -The option should be set to something like: > - - let g:syntastic_mode_map = { 'mode': 'active', - \ 'active_filetypes': ['ruby', 'php'], - \ 'passive_filetypes': ['puppet'] } -< - -"mode" can be mapped to one of two values - "active" or "passive". When set to -active, syntastic does automatic checking whenever a buffer is saved or -initially opened. When set to "passive" syntastic only checks when the user -calls :SyntasticCheck. - -The exceptions to these rules are defined with "active_filetypes" and -"passive_filetypes". In passive mode, automatic checks are still done -for all filetypes in the "active_filetypes" array. In active mode, -automatic checks are not done for any filetypes in the -"passive_filetypes" array. - -At runtime, the |:SyntasticToggleMode| command can be used to switch between -active and passive mode. - -If any of "mode", "active_filetypes", or "passive_filetypes" are not specified -then they will default to their default value as above. - - *'syntastic_quiet_warnings'* - -Use this option if you only care about syntax errors, not warnings. When set, -this option has the following effects: - * no |signs| appear unless there is at least one error, whereupon both - errors and warnings are displayed - * the |'syntastic_auto_loc_list'| option only pops up the error window if - there's at least one error, whereupon both errors and warnings are - displayed -> - let g:syntastic_quiet_warnings=1 -< - - *'syntastic_stl_format'* - -Default: [Syntax: line:%F (%t)] -Use this option to control what the syntastic statusline text contains. Several -magic flags are availble to insert information: - %e - number of errors - %w - number of warnings - %t - total number of warnings and errors - %fe - line number of first error - %fw - line number of first warning - %F - line number of first warning or error - -Several additional flags are available to hide text under certain conditions: - %E{...} - hide the text in the brackets unless there are errors - %W{...} - hide the text in the brackets unless there are warnings - %B{...} - hide the text in the brackets unless there are both warnings AND - errors -These flags cant be nested. - -Example: > - let g:syntastic_stl_format = '[%E{Err: %fe #%e}%B{, }%W{Warn: %fw #%w}]' -< -If this format is used and the current buffer has 5 errors and 1 warning -starting on lines 20 and 10 respectively then this would appear on the -statusline: > - [Err: 20 #5, Warn: 10 #1] -< -If the buffer had 2 warnings, starting on line 5 then this would appear: > - [Warn: 5 #2] -< - - -============================================================================== -5. Writing syntax checkers *syntastic-syntax-checkers* - - -A syntax checker plugin is really nothing more than a single function. You -should define them in ~/.vim/syntax_checkers/<filetype>.vim, but this is -purely for convenience; Syntastic doesn't actually care where these functions -are defined. - -A syntax checker plugin must define a function of the form: -> - SyntaxCheckers_<filetype>_GetLocList() -< -The output of this function must be of the same format as that returned by -the |getloclist()| function. See |getloclist()| and |getqflist()| for -details. - -To achieve this, the function should call |SyntasticMake()| or shell out to a -syntax checker, parse the output and munge it into the format. - -There are several syntax checker plugins provided with this plugin. The ruby -one is a good example of |SyntasticMake()|, while the haml one is a good -example of how to create the data structure manually. - - -SyntasticMake({options}) *SyntasticMake()* - {options} must be a dictionary. It can contain "makeprg" and "errorformat" - as keys (both optional). - - SyntasticMake will run |:lmake| with the given |'makeprg'| and - |'errorformat'| (using the current settings if none are supplied). It will - store the resulting error list and use it to provide all of the - |syntastic-functionality|. The previous makeprg and errorformat settings - will then be restored, as well as the location list for the window. From - the user's perspective, it will be as though |:lmake| was never run. - - Note that the given "makeprg" and "errorformat" will be set using |:let-&|, - so you should not escape spaces. - - -============================================================================== -6. About *syntastic-about* - -The author of syntastic is a mighty wild stallion, hear him roar! > - _ _ _____ _____ ___ ___ ___ ____ _ _ _ - | \ | | ____| ____|_ _|_ _|_ _/ ___| | | | | - | \| | _| | _| | | | | | | | _| |_| | | - | |\ | |___| |___ | | | | | | |_| | _ |_| - |_| \_|_____|_____|___|___|___\____|_| |_(_) - -< -He likes to trot around in the back yard reading his emails and sipping a -scolding hot cup of Earl Grey. Email him at martin.grenfell at gmail dot com. -He can also be found trolling the #vim channel on the freenode IRC network as -scrooloose. - -Bug reports, feedback, suggestions etc are welcomed. - - -The latest official releases will be on vim.org at some point. - -The latest dev versions are on github - http://github.com/scrooloose/syntastic - -============================================================================== -7. Changelog *syntastic-changelog* - -2.3.0 - - Add syntastic_loc_list_height option - - Allow errors to have a "subtype" that is signed differently to standard - errors. Currently geared towards differentiating style errors from - syntax errors. Currently implemented for phpcs (technosophos). - - New checkers for: - - yaml - - haxe (davidB) - - ocaml (edwintorok) - - pylint (parantapa) - - rust (cjab) - - - Updates to existing checkers: - - jslint - - jshint (gillesruppert) - - fortran (bmattern) - - sass - - html (darcyparker) - - coffee (darcyparker) - - docbk (darcyparker) - - xml - - xslt - - less (irrationalfab) - - php (AD7six, technosophos) - - cuda - - python (mitchellh, pneff) - - perl (Anthony Carapetis) - - c (naoina, zsprackett) - - puppet (frimik) - -2.2.0 - - only do syntax checks when files are saved (not when first opened) - add - g:syntastic_check_on_open option to get the old behavior back - - bug fix with echoing error messages; fixes incompatability with cmd-t (datanoise) - - dont allow warnings to mask errors when signing/echoing errors (ashikase) - - auto close location list when leaving buffer. (millermedeiros) - - update errors appropriately when :SyntasticToggleMode is called - - updates/fixes to existing checkers: - - javascript/jshint (millermedeiros) - - javascript/jslint - - c (kongo2002) - - Support for new filetypes: - - JSON (millermedeiros, tocer) - - rst (reStructuredText files) (JNRowe) - - gentoo-metadata (JNRowe) - - -2.1.0 - - when the cursor is on a line containing an error, echo the - error msg (kevinw) - - various bug fixes and refactoring - - updates/fixes to existing checkers: - - html (millermedeiros) - - erlang - - coffeescript - - javascript - - sh - - php (add support for phpcs - technosophos) - - add an applescript checker (Zhai Cai) - - add support for hyphenated filetypes (JNRowe) - -2.0.0 - - Add support for highlighting the erroneous parts of lines (kstep) - - Add support for displaying errors via balloons (kstep) - - Add syntastic_mode_map option to give more control over when checking - should be done. - - Add :SyntasticCheck command to force a syntax check - useful in passive - mode (justone). - - Add the option to automatically close the location list, but not - automatically open it (milkypostman) - - Add syntastic_auto_jump option to automatically jump to the first - error (milkypostman) - - Only source syntax checkers as needed - instead of loading all of them - when vim starts - - - Support for new filetypes: - - less (julienXX) - - docbook (tpope) - - matlab (jasongraham) - - go (dtjm) - - puppet (uggedal, roman, zsprackett) - - haskell (baldo, roman) - - tcl (et) - - vala (kstep) - - cuda (temporaer) - - css (oryband, sitedyno) - - fortran (Karl Yngve Lervåg) - - xml (kusnier) - - xslt (kusnier) - - erlang (kTT) - - zpt (claytron) - - - updates to existing checkers: - - javascript (mogren, bryanforbes, cjab, ajduncan) - - sass/scss (tmm1, atourino, dlee, epeli) - - ruby (changa) - - perl (harleypig) - - haml (bmihelac) - - php (kstep, docteurklein) - - python (kstep, soli) - - lua (kstep) - - html (kstep) - - xhtml (kstep) - - c (kongo2002, brandonw) - - cpp (kongo2002) - - coffee (industrial) - - eruby (sergevm) - -1.2.0 - - New syntax checkers from github:kongo2002 - - c (thanks also to github:jperras) - - cpp - - lua - - sh (thanks also to github:jmcantrell) - - add coffee syntax checked by github:lstoll - - add tex syntax checker - - make html checker play nicer with html5, thanks to github:enaeseth - - escape filenames properly when invoking syntax checkers, thanks to - github:jmcantrell - - adjust the ruby syntax checker to avoid some common annoying warnings, - thanks to github:robertwahler - -1.1.0 [codenamed: tpimp] - - Dont load rubygems for ruby/eruby syntax checkers. Thanks tpope. - - Improve the javascript syntax checker to catch some warnings that were - getting missed. Thanks tpope. - - Dont automatically focus the error window. Thanks tpope. - - Add support for cucumber [tpope], haskell & perl [Anthony Carapetis], - and xhtml - - Add commands to enable/disable syntax checking at runtime. See :help - syntastic-commands. - - Add an option to specifiy syntax checkers that should be disabled by - default. See :help syntastic_disabled_filetypes. - - Dont use :signs if vim wasnt compiled with support for them. -) - -============================================================================== -8. Credits *syntastic-credits* - -Thanks to the following people for testing, bug reports, patches etc. They own, -hard. - - Mikael Fridh (frimik) - Patrice Neff (pneff ) - Gilles Ruppert (gillesruppert) - Naoya INADA (naoina) - Mitchell Hashimoto (mitchellh) - irrationalfab - Andy Dawson (AD7six) - Parantapa Bhattacharya (parantapa) - edwintorok - Darcy Parker (darcyparker) - bmattern - David Bernard (davidB) - Aleksey V. Zapparov (ixti) - Benji Fisher (benjifisher) - Lance Fetters (ashikase) - datanoise - Giuseppe Rota (grota) - tocer - James Rowe (JNRowe) - Zhai Cai - Matt Butcher (technosophos) - Kevin Watters (kevinw) - Miller Medeiros (millermedeiros) - Pawel Salata (kTT) - Fjölnir Ásgeirsson (aptiva) - Clayton Parker (claytron) - S. Zachariah Sprackett (zsprackett) - Sylvain Soliman (soli) - Ricardo Catalinas Jiménez (jimenezrick) - kusnier - Klein Florian (docteurklein) - sitedyno - Matthew Batema (mlb-) - Nate Jones (justone) - sergevm - Karl Yngve Lervåg - Pavel Argentov (argent-smith) - Andy Duncan (ajduncan) - Antonio Touriño (atourino) - Chad Jablonski (cjab) - Roman Gonzalez (roman) - Tom Wieland (industrial) - Ory Band (oryband) - Esa-Matti Suuronen (epeli) - Brandon Waskiewicz (brandonw) - dlee - temporaer - Jason Graham (jasongraham) - Sam Nguyen (dtjm) - Claes Mogren (mogren) - Eivind Uggedal (uggedal) - kstep - Andreas Baldeau (baldo) - Eric Thomas (et) - Brian Donovan (eventualbuddha) - Bryan Forbes (bryanforbes) - Aman Gupta (tmm1) - Donald Ephraim Curtis (milkypostman) - Dominique Rose-Rosette (changa) - Harley Pig (harleypig) - bmihelac - Julien Blanchard (julienXX) - Gregor Uhlenheuer (kongo2002) - Lincoln Stoll - Tim Carey-Smith (halorgium) - Tim Pope (tpope) - Travis Jeffery - Anthony Carapetis - - -============================================================================== -9. License *syntastic-license* - -Syntastic is released under the wtfpl. -See http://sam.zoy.org/wtfpl/COPYING. diff --git a/vim/doc/tagbar.txt b/vim/doc/tagbar.txt deleted file mode 100644 index cb9a3e3..0000000 --- a/vim/doc/tagbar.txt +++ /dev/null @@ -1,1016 +0,0 @@ -*tagbar.txt* Display tags of a file in their correct scope - -Author: Jan Larres <jan@majutsushi.net> -Licence: Vim licence, see |license| -Homepage: http://majutsushi.github.com/tagbar/ -Version: 2.3 - -============================================================================== -Contents *tagbar* *tagbar-contents* - - 1. Intro ........................... |tagbar-intro| - Pseudo-tags ................... |tagbar-pseudotags| - Supported features ............ |tagbar-features| - Other ctags-compatible programs |tagbar-other| - 2. Requirements .................... |tagbar-requirements| - 3. Installation .................... |tagbar-installation| - 4. Usage ........................... |tagbar-usage| - Commands ...................... |tagbar-commands| - Key mappings .................. |tagbar-keys| - 5. Configuration ................... |tagbar-configuration| - Highlight colours ............. |tagbar-highlight| - Automatically opening Tagbar .. |tagbar-autoopen| - 6. Extending Tagbar ................ |tagbar-extend| - 7. Troubleshooting & Known issues .. |tagbar-issues| - 8. History ......................... |tagbar-history| - 9. Todo ............................ |tagbar-todo| - 10. Credits ......................... |tagbar-credits| - -============================================================================== -1. Intro *tagbar-intro* - -Tagbar is a plugin for browsing the tags of source code files. It provides a -sidebar that displays the ctags-generated tags of the current file, ordered by -their scope. This means that for example methods in C++ are displayed under -the class they are defined in. - -Let's say we have the following code inside of a C++ file: -> - namespace { - char a; - - class Foo - { - public: - Foo(); - ~Foo(); - private: - int var; - }; - }; -< -Then Tagbar would display the tag information like so: -> - __anon1* : namespace - Foo : class - +Foo() - +~Foo() - -var - a -< -This example shows several important points. First, the tags are listed -indented below the scope they are defined in. Second, the type of a scope is -listed after its name and a colon. Third, tags for which the access/visibility -information is known are prefixed with a symbol indicating that. - ------------------------------------------------------------------------------- -PSEUDO-TAGS *tagbar-pseudotags* - -The example also introduces the concept of "pseudo-tags". Pseudo-tags are tags -that are not explicitly defined in the file but have children in it. In this -example the namespace doesn't have a name and thus ctags doesn't generate a -tag for it, but since it has children it still needs to be displayed using an -auto-generated name. - -Another case where pseudo-tags appear is in C++ implementation files. Since -classes are usually defined in a header file but the member methods and -variables in the implementation file the class itself won't generate a tag -in that file. - -Since pseudo-tags don't really exist they cannot be jumped to from the Tagbar -window. - -Pseudo-tags are denoted with an asterisk ('*') at the end of their name. - ------------------------------------------------------------------------------- -SUPPORTED FEATURES *tagbar-features* - -The following features are supported by Tagbar: - - - Display tags under their correct scope. - - Automatically update the tags when switching between buffers and editing - files. - - Display visibility information of tags if available. - - Highlight the tag near the cursor while editing files. - - Jump to a tag from the Tagbar window. - - Display the complete prototype of a tag. - - Tags can be sorted either by name or order of appearance in the file. - - Scopes can be folded to hide uninteresting information. - - Supports all of the languages that ctags does, i.e. Ant, Assembler, ASP, - Awk, Basic, BETA, C, C++, C#, COBOL, DosBatch, Eiffel, Erlang, Flex, - Fortran, HTML, Java, JavaScript, Lisp, Lua, Make, MatLab, OCaml, Pascal, - Perl, PHP, Python, REXX, Ruby, Scheme, Shell script, SLang, SML, SQL, Tcl, - Tex, Vera, Verilog, VHDL, Vim and YACC. - - Can be extended to support arbitrary new types. - ------------------------------------------------------------------------------- -OTHER CTAGS-COMPATIBLE PROGRAMS *tagbar-other* - -Tagbar theoretically also supports filetype-specific programs that can output -tag information that is compatible with ctags. However due to potential -incompatibilities this may not always completely work. Tagbar has been tested -with doctorjs/jsctags and will use that if present, other programs require -some configuration (see |tagbar-extend|). If a program does not work even with -correct configuration please contact me. - -Note: Please check |tagbar-issues| for some possible issues with jsctags. - -============================================================================== -2. Requirements *tagbar-requirements* - -The following requirements have to be met in order to be able to use tagbar: - - - Vim 7.0 or higher. Older versions will not work since Tagbar uses data - structures that were only introduced in Vim 7. - - Exuberant ctags 5.5 or higher. Ctags is the program that generates the - tag information that Tagbar uses. It is shipped with most Linux - distributions, otherwise it can be downloaded from the following - website: - - http://ctags.sourceforge.net/ - - Tagbar will work on any platform that ctags runs on -- this includes - UNIX derivatives, Mac OS X and Windows. Note that other versions like - GNU ctags will not work. - Tagbar generates the tag information by itself and doesn't need (or use) - already existing tag files. - - File type detection must be turned on in vim. This can be done with the - following command in your vimrc: -> - filetype on -< - See |filetype| for more information. - - Tagbar will not work in |restricted-mode| or with 'compatible' set. - -============================================================================== -3. Installation *tagbar-installation* - -Use the normal Vimball install method for installing tagbar.vba: -> - vim tagbar.vba - :so % - :q -< -Alternatively you can clone the git repository and then add the path to -'runtimepath' or use the pathogen plugin. Don't forget to run |:helptags| if -you're not using pathogen. - -If the ctags executable is not installed in one of the directories in your -$PATH environment variable you have to set the g:tagbar_ctags_bin variable, -see |g:tagbar_ctags_bin|. - -============================================================================== -4. Usage *tagbar-usage* - -There are essentially two ways to use Tagbar: - - 1. Have it running all the time in a window on the side of the screen. In - this case Tagbar will update its contents whenever the source file is - changed and highlight the tag the cursor is currently on in the file. If - a tag is selected in Tagbar the file window will jump to the tag and the - Tagbar window will stay open. |g:tagbar_autoclose| has to be unset for - this mode. - 2. Only open Tagbar when you want to jump to a specific tag and have it - close automatically once you have selected one. This can be useful for - example for small screens where a permanent window would take up too much - space. You have to set the option |g:tagbar_autoclose| in this case. The - cursor will also automatically jump to the Tagbar window when opening it. - -Opening and closing the Tagbar window~ -Use |:TagbarOpen| or |:TagbarToggle| to open the Tagbar window if it is -closed. By default the window is opened on the right side, set the option -|g:tagbar_left| to open it on the left instead. If the window is already open, -|:TagbarOpen| will jump to it and |:TagbarToggle| will close it again. -|:TagbarClose| will simply close the window if it is open. - -It is probably a good idea to assign a key to these commands. For example, put -this in your |vimrc|: -> - nnoremap <silent> <F9> :TagbarToggle<CR> -< -You can then open and close Tagbar by simply pressing the <F9> key. - -You can also use |:TagbarOpenAutoClose| to open the Tagbar window, jump to it -and have it close automatically on tag selection regardless of the -|g:tagbar_autoclose| setting. - -Jumping to tags~ -When you're inside the Tagbar window you can jump to the definition of a tag -by moving the cursor to a tag and pressing <Enter> or double-clicking on it -with the mouse. The source file will then move to the definition and put the -cursor in the corresponding line. This won't work for pseudo-tags. - -Sorting~ -You can sort the tags in the Tagbar window in two ways: by name or by file -order. Sorting them by name simply displays the tags in their alphabetical -order under their corresponding scope. Sorting by file order means that the -tags keep the order they have in the source file, but are still associated -with the correct scope. You can change the sort order by pressing the "s" key -in the Tagbar window. The current sort order is displayed in the statusbar of -the Tagbar window. - -Folding~ -The displayed scopes (and unscoped types) can be folded to hide uninteresting -information. Mappings similar to Vim's built-in ones are provided. Folds can -also be opened and closed by clicking on the fold icon with the mouse. - -Displaying the prototype of a tag~ -Tagbar can display the prototype of a tag. More precisely it can display the -line in which the tag is defined. This can be done by either pressing <Space> -when on a tag or hovering over a tag with the mouse. In the former case the -prototype will be displayed in the command line |Command-line|, in the latter -case it will be displayed in a pop-up window. The prototype will also be -displayed when the cursor stays on a tag for 'updatetime' milliseconds. - ------------------------------------------------------------------------------- -COMMANDS *tagbar-commands* - -:TagbarOpen [{flags}] - Open the Tagbar window if it is closed. - - Additional behaviour can be specified with the optional {flags} argument. - It is a string which can contain these character flags: - 'f' Jump to Tagbar window when opening (just as if |g:tagbar_autofocus| - were set to 1) - 'j' Jump to Tagbar window if already open - 'c' Close Tagbar on tag selection (just as if |g:tagbar_autoclose| were - set to 1, but doesn't imply 'f') - - For example, the following command would always jump to the Tagbar window, - opening it first if necessary, but keep it open after selecting a tag - (unless |g:tagbar_autoclose| is set): > - :TagbarOpen fj -< -:TagbarClose - Close the Tagbar window if it is open. - -:TagbarToggle - Open the Tagbar window if it is closed or close it if it is open. - -:TagbarOpenAutoClose - Open the Tagbar window, jump to it and close it on tag selection. This is - an alias for ":TagbarOpen fc". - -:TagbarSetFoldlevel {number} - Set the foldlevel of the tags of the current file to {number}. The - foldlevel of tags in other files remains unaffected. Works in the same way - as 'foldlevel'. - -:TagbarShowTag - Open the parent folds of the current tag in the file window as much as - needed for the tag to be visible in the Tagbar window. - -:TagbarDebug [logfile] - Start debug mode. This will write debug messages to file [logfile] while - using Tagbar. If no argument is given "tagbardebug.log" in the current - directory is used. Note: an existing file will be overwritten! - -:TagbarDebugEnd - End debug mode, debug messages will no longer be written to the logfile. - ------------------------------------------------------------------------------- -KEY MAPPINGS *tagbar-keys* - -The following mappings are valid in the Tagbar window: - -<F1> Display key mapping help. -<CR>/<Enter> Jump to the tag under the cursor. Doesn't work for pseudo-tags - or generic headers. -p Jump to the tag under the cursor, but stay in the Tagbar window. -<LeftMouse> When on a fold icon, open or close the fold depending on the - current state. -<2-LeftMouse> Same as <CR>. See |g:tagbar_singleclick| if you want to use a - single- instead of a double-click. -<Space> Display the prototype of the current tag (i.e. the line defining - it) in the command line. -+/zo Open the fold under the cursor. --/zc Close the fold under the cursor or the current one if there is - no fold under the cursor. -o/za Toggle the fold under the cursor or the current one if there is - no fold under the cursor. -*/zR Open all folds by setting foldlevel to 99. -=/zM Close all folds by setting foldlevel to 0. -<C-N> Go to the next top-level tag. -<C-P> Go to the previous top-level tag. -s Toggle sort order between name and file order. -x Toggle zooming the window. -q Close the Tagbar window. - -============================================================================== -5. Configuration *tagbar-configuration* - - *g:tagbar_ctags_bin* -g:tagbar_ctags_bin~ -Default: empty - -Use this option to specify the location of your ctags executable. Only needed -if it is not in one of the directories in your $PATH environment variable. - -Example: -> - let g:tagbar_ctags_bin = 'C:\Ctags5.8\ctags.exe' -< - - *g:tagbar_left* -g:tagbar_left~ -Default: 0 - -By default the Tagbar window will be opened on the right-hand side of vim. Set -this option to open it on the left instead. - -Example: -> - let g:tagbar_left = 1 -< - - *g:tagbar_width* -g:tagbar_width~ -Default: 40 - -Width of the Tagbar window in characters. - -Example: -> - let g:tagbar_width = 30 -< - - *g:tagbar_autoclose* -g:tagbar_autoclose~ -Default: 0 - -If you set this option the Tagbar window will automatically close when you -jump to a tag. This implies |g:tagbar_autofocus|. - -Example: -> - let g:tagbar_autoclose = 1 -< - - *g:tagbar_autofocus* -g:tagbar_autofocus~ -Default: 0 - -If you set this option the cursor will move to the Tagbar window when it is -opened. - -Example: -> - let g:tagbar_autofocus = 1 -< - - *g:tagbar_sort* -g:tagbar_sort~ -Default: 1 - -If this option is set the tags are sorted according to their name. If it is -unset they are sorted according to their order in the source file. Note that -in the second case Pseudo-tags are always sorted before normal tags of the -same kind since they don't have a real position in the file. - -Example: -> - let g:tagbar_sort = 0 -< - - *g:tagbar_compact* -g:tagbar_compact~ -Default: 0 - -Setting this option will result in Tagbar omitting the short help at the -top of the window and the blank lines in between top-level scopes in order to -save screen real estate. - -Example: -> - let g:tagbar_compact = 1 -< - - *g:tagbar_expand* -g:tagbar_expand~ -Default: 0 - -If this option is set the Vim window will be expanded by the width of the -Tagbar window if using a GUI version of Vim. - -Example: -> - let g:tagbar_expand = 1 -< - - *g:tagbar_singleclick* -g:tagbar_singleclick~ -Default: 0 - -If this option is set then a single- instead of a double-click is used to jump -to the tag definition. - -Example: -> - let g:tagbar_singleclick = 1 -< - - *g:tagbar_foldlevel* -g:tagbar_foldlevel~ -Default: 99 - -The initial foldlevel for folds in the Tagbar window. Fold with a level higher -than this number will be closed. - -Example: -> - let g:tagbar_foldlevel = 2 -< - - *g:tagbar_iconchars* -g:tagbar_iconchars~ - -Since the display of the icons used to indicate open or closed folds depends -on the actual font used, different characters may be optimal for different -fonts. With this variable you can set the icons to characters of your liking. -The first character in the list specifies the icon to use for a closed fold, -and the second one for an open fold. - -Examples (don't worry if some the characters aren't displayed correctly, just -choose other characters in that case): -> - let g:tagbar_iconchars = ['▶', '▼'] (default on Linux and Mac OS X) - let g:tagbar_iconchars = ['▾', '▸'] - let g:tagbar_iconchars = ['▷', '◢'] - let g:tagbar_iconchars = ['+', '-'] (default on Windows) -< - - *g:tagbar_autoshowtag* -g:tagbar_autoshowtag~ -Default: 0 - -If this variable is set and the current tag is inside of a closed fold then -the folds will be opened as much as needed for the tag to be visible so it can -be highlighted. If it is not set then the folds won't be opened and the parent -tag will be highlighted instead. You can use the TagbarShowTag command to open -the folds manually. - -Example: -> - let g:tagbar_autoshowtag = 1 -< - - *g:tagbar_updateonsave_maxlines* -g:tagbar_updateonsave_maxlines~ -Default: 5000 - -If the current file has fewer lines than the value of this variable, Tagbar -will update immediately after saving the file. If it is longer then the update -will only happen on the |CursorHold| event and when switching buffers (or -windows). This is to prevent the time it takes to save a large file from -becoming annoying in case you have a slow computer. If you have a fast -computer you can set it to a higher value. - -Example: -> - let g:tagbar_updateonsave_maxlines = 10000 -< - - *g:tagbar_systemenc* -g:tagbar_systemenc~ -Default: value of 'encoding' - -This variable is for cases where the character encoding of your operating -system is different from the one set in Vim, i.e. the 'encoding' option. For -example, if you use a Simplified Chinese Windows version that has a system -encoding of "cp936", and you have set 'encoding' to "utf-8", then you would -have to set this variable to "cp936". - -Example: -> - let g:tagbar_systemenc = 'cp936' -< - ------------------------------------------------------------------------------- -HIGHLIGHT COLOURS *tagbar-highlight* - -All of the colours used by Tagbar can be customized. Here is a list of the -highlight groups that are defined by Tagbar: - -TagbarComment - The help at the top of the buffer. - -TagbarKind - The header of generic "kinds" like "functions" and "variables". - -TagbarNestedKind - The "kind" headers in square brackets inside of scopes. - -TagbarScope - Tags that define a scope like classes, structs etc. - -TagbarType - The type of a tag or scope if available. - -TagbarSignature - Function signatures. - -TagbarPseudoID - The asterisk (*) that signifies a pseudo-tag. - -TagbarFoldIcon - The fold icon on the left of foldable tags. - -TagbarHighlight - The colour that is used for automatically highlighting the current tag. - -TagbarAccessPublic - The "public" visibility/access symbol. - -TagbarAccessProtected - The "protected" visibility/access symbol. - -TagbarAccessPrivate - The "private" visibility/access symbol. - -If you want to change any of those colours put a line like the following in -your vimrc: -> - highlight TagbarScope guifg=Green ctermfg=Green -< -See |:highlight| for more information. - ------------------------------------------------------------------------------- -AUTOMATICALLY OPENING TAGBAR *tagbar-autoopen* - -Since there are several different situations in which you might want to open -Tagbar automatically there is no single option to enable automatic opening. -Instead, autocommands can be used together with a convenience function that -opens Tagbar only if a supported file is open(ed). - -If you want to open Tagbar automatically on Vim startup no matter what put -this into your vimrc: -> - autocmd VimEnter * nested :TagbarOpen -< -If you want to open it only if you're opening Vim with a supported file/files -use this instead: -> - autocmd VimEnter * nested :call tagbar#autoopen() -< -For opening Tagbar also if you open a supported file in an already running -Vim: -> - autocmd FileType * nested :call tagbar#autoopen() -< -And if you only want to open Tagbar only for specific filetypes, not for all -of the supported ones: -> - autocmd FileType c,cpp nested :TagbarOpen -< -Check out |autocmd.txt| if you want it to open automatically in more -complicated cases. - -============================================================================== -6. Extending Tagbar *tagbar-extend* - -Tagbar has a flexible mechanism for extending the existing file type (i.e. -language) definitions. This can be used both to change the settings of the -existing types and to add completely new types. A complete configuration -consists of a type definition for Tagbar in your |vimrc| and optionally a -language definition for ctags in case you want to add a new language. - -Before writing your own extension have a look at the wiki -(https://github.com/majutsushi/tagbar/wiki/Support-for-additional-filetypes) -or try googling for existing ones. If you do end up creating your own -extension please consider adding it to the wiki so that others will be able to -use it, too. - -Every type definition in Tagbar is a dictionary with the following keys: - -ctagstype: The name of the language as recognized by ctags. Use the command > - ctags --list-languages -< to get a list of the languages ctags supports. The case doesn't - matter. -kinds: A list of the "language kinds" that should be listed in Tagbar, - ordered by the order they should appear in in the Tagbar window. - Use the command > - ctags --list-kinds={language name} -< to get a list of the kinds ctags supports for a given language. An - entry in this list is a string with two or three parts separated - by a colon: the first part is the one-character abbreviation that - ctags uses, and the second part is an arbitrary string that will - be used in Tagbar as the header for the tags of this kind that are - not listed under a specific scope. The optional third part - determines whether tags of this kind should be folded by default, - with 1 meaning they should be folded and 0 they should not. If - this part is omitted the tags will not be folded by default. For - example, the string > - "f:functions:1" -< would list all the function definitions in a file under the header - "functions" and fold them. -sro: The scope resolution operator. For example, in C++ it is "::" and - in Java it is ".". If in doubt run ctags as shown below and check - the output. -kind2scope: A dictionary describing the mapping of tag kinds (in their - one-character representation) to the scopes their children will - appear in, for example classes, structs etc. - Unfortunately there is no ctags option to list the scopes, you - have to look at the tags ctags generates manually. For example, - let's say we have a C++ file "test.cpp" with the following - contents: > - class Foo - { - public: - Foo(); - ~Foo(); - private: - int var; - }; -< We then run ctags in the following way: > - ctags -f - --format=2 --excmd=pattern --extra= --fields=nksaSmt test.cpp -< Then the output for the variable "var" would look like this: > - var tmp.cpp /^ int var;$/;" kind:m line:11 class:Foo access:private -< This shows that the scope name for an entry in a C++ class is - simply "class". So this would be the word that the "kind" - character of a class has to be mapped to. -scope2kind: The opposite of the above, mapping scopes to the kinds of their - parents. Most of the time it is the exact inverse of the above, - but in some cases it can be different, for example when more than - one kind maps to the same scope. If it is the exact inverse for - your language you only need to specify one of the two keys. -replace: If you set this entry to 1 your definition will completely replace -{optional} an existing default definition. This is useful if you want to - disable scopes for a file type for some reason. Note that in this - case you have to provide all the needed entries yourself! -sort: This entry can be used to override the global sort setting for -{optional} this specific file type. The meaning of the value is the same as - with the global setting, that is if you want to sort tags by name - set it to 1 and if you want to sort them according to their order - in the file set it to 0. -deffile: The path to a file with additional ctags definitions (see the -{optional} section below on adding a new definition for what exactly that - means). This is especially useful for ftplugins since they can - provide a complete type definition with ctags and Tagbar - configurations without requiring user intervention. - Let's say you have an ftplugin that adds support for the language - "mylang", and your directory structure looks like this: > - ctags/mylang.cnf - ftplugin/mylang.vim -< Then the "deffile" entry would look like this to allow for the - plugin to be installed in an arbitray location (for example - with pathogen): > - - 'deffile' : expand('<sfile>:p:h:h') . '/ctags/mylang.cnf' -< -ctagsbin: The path to a filetype-specific ctags-compatible program like -{optional} jsctags. Set it in the same way as |g:tagbar_ctags_bin|. jsctags is - used automatically if found in your $PATH and does not have to be - set in that case. If it is not in your path you have to set this - key, the rest of the configuration should not be necessary (unless - you want to change something, of course). -ctagsargs: The arguments to be passed to the filetype-specific ctags program -{optional} (without the filename). Make sure you set an option that makes the - program output its data on stdout. Not used for the normal ctags - program. - - -You then have to assign this dictionary to a variable in your vimrc with the -name -> - g:tagbar_type_{vim filetype} -< -For example, for C++ the name would be "g:tagbar_type_cpp". If you don't know -the vim file type then run the following command: -> - :set filetype? -< -and vim will display the file type of the current buffer. - -Example: C++~ -Here is a complete example that shows the default configuration for C++ as -used in Tagbar. This is just for illustration purposes since user -configurations will usually be less complicated. -> - let g:tagbar_type_cpp = { - \ 'ctagstype' : 'c++', - \ 'kinds' : [ - \ 'd:macros:1', - \ 'p:prototypes:1', - \ 'g:enums', - \ 'e:enumerators', - \ 't:typedefs', - \ 'n:namespaces', - \ 'c:classes', - \ 's:structs', - \ 'u:unions', - \ 'f:functions', - \ 'm:members', - \ 'v:variables' - \ ], - \ 'sro' : '::', - \ 'kind2scope' : { - \ 'g' : 'enum', - \ 'n' : 'namespace', - \ 'c' : 'class', - \ 's' : 'struct', - \ 'u' : 'union' - \ }, - \ 'scope2kind' : { - \ 'enum' : 'g', - \ 'namespace' : 'n', - \ 'class' : 'c', - \ 'struct' : 's', - \ 'union' : 'u' - \ } - \ } -< - -Which of the keys you have to specify depends on what you want to do. - -Changing an existing definition~ -If you want to change an existing definition you only need to specify the -parts that you want to change. It probably only makes sense to change "kinds" -and/or "scopes", which would be the case if you wanted to exclude certain -kinds from appearing in Tagbar or if you want to change their order. As an -example, if you didn't want Tagbar to show prototypes for C++ files and switch -the order of enums and typedefs, you would do it like this: -> - let g:tagbar_type_cpp = { - \ 'kinds' : [ - \ 'd:macros:1', - \ 'g:enums', - \ 't:typedefs', - \ 'e:enumerators', - \ 'n:namespaces', - \ 'c:classes', - \ 's:structs', - \ 'u:unions', - \ 'f:functions', - \ 'm:members', - \ 'v:variables' - \ ] - \ } -< -Compare with the complete example above to see the difference. - -Adding a definition for a new language/file type~ -In order to be able to add a new language to Tagbar you first have to create a -configuration for ctags that it can use to parse the files. This can be done -in two ways: - - 1. Use the --regex argument for specifying regular expressions that are used - to parse the files. An example of this is given below. A disadvantage of - this approach is that you can't specify scopes. - 2. Write a parser plugin in C for ctags. This approach is much more powerful - than the regex approach since you can make use of all of ctags' - functionality but it also requires much more work. Read the ctags - documentation for more information about how to do this. - -For the first approach the only keys that are needed in the Tagbar definition -are "ctagstype" and "kinds". A definition that supports scopes has to define -those two and in addition "scopes", "sro" and at least one of "kind2scope" and -"scope2kind". - -Let's assume we want to add support for LaTeX to Tagbar using the regex -approach. First we put the following text into ~/.ctags or a file pointed to -by the "deffile" definition entry: -> - --langdef=latex - --langmap=latex:.tex - --regex-latex=/^\\tableofcontents/TABLE OF CONTENTS/s,toc/ - --regex-latex=/^\\frontmatter/FRONTMATTER/s,frontmatter/ - --regex-latex=/^\\mainmatter/MAINMATTER/s,mainmatter/ - --regex-latex=/^\\backmatter/BACKMATTER/s,backmatter/ - --regex-latex=/^\\bibliography\{/BIBLIOGRAPHY/s,bibliography/ - --regex-latex=/^\\part[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/PART \2/s,part/ - --regex-latex=/^\\part[[:space:]]*\*[[:space:]]*\{([^}]+)\}/PART \1/s,part/ - --regex-latex=/^\\chapter[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/CHAP \2/s,chapter/ - --regex-latex=/^\\chapter[[:space:]]*\*[[:space:]]*\{([^}]+)\}/CHAP \1/s,chapter/ - --regex-latex=/^\\section[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/\. \2/s,section/ - --regex-latex=/^\\section[[:space:]]*\*[[:space:]]*\{([^}]+)\}/\. \1/s,section/ - --regex-latex=/^\\subsection[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/\.\. \2/s,subsection/ - --regex-latex=/^\\subsection[[:space:]]*\*[[:space:]]*\{([^}]+)\}/\.\. \1/s,subsection/ - --regex-latex=/^\\subsubsection[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/\.\.\. \2/s,subsubsection/ - --regex-latex=/^\\subsubsection[[:space:]]*\*[[:space:]]*\{([^}]+)\}/\.\.\. \1/s,subsubsection/ - --regex-latex=/^\\includegraphics[[:space:]]*(\[[^]]*\])?[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/\3/g,graphic+listing/ - --regex-latex=/^\\lstinputlisting[[:space:]]*(\[[^]]*\])?[[:space:]]*(\[[^]]*\])?[[:space:]]*\{([^}]+)\}/\3/g,graphic+listing/ - --regex-latex=/\\label[[:space:]]*\{([^}]+)\}/\1/l,label/ - --regex-latex=/\\ref[[:space:]]*\{([^}]+)\}/\1/r,ref/ - --regex-latex=/\\pageref[[:space:]]*\{([^}]+)\}/\1/p,pageref/ -< -This will create a new language definition with the name "latex" and associate -it with files with the extension ".tex". It will also define the kinds "s" for -sections, chapters and the like, "g" for included graphics, "l" for labels, -"r" for references and "p" for page references. See the ctags documentation -for more information about the exact syntax. - -Now we have to create the Tagbar language definition in our vimrc: -> - let g:tagbar_type_tex = { - \ 'ctagstype' : 'latex', - \ 'kinds' : [ - \ 's:sections', - \ 'g:graphics', - \ 'l:labels', - \ 'r:refs:1', - \ 'p:pagerefs:1' - \ ], - \ 'sort' : 0, - \ 'deffile' : expand('<sfile>:p:h:h') . '/ctags/latex.cnf' - \ } -< -The "deffile" field is of course only needed if the ctags definition actually -is in that file and not in ~/.ctags. - -Sort has been disabled for LaTeX so that the sections appear in their correct -order. They unfortunately can't be shown nested with their correct scopes -since as already mentioned the regular expression approach doesn't support -that. - -Tagbar should now be able to show the sections and other tags from LaTeX -files. - -============================================================================== -7. Troubleshooting & Known issues *tagbar-issues* - -As a general rule, if the tag information displayed by Tagbar is wrong (for -example, a method doesn't show up or is in the wrong place) you should first -try running ctags manually to see whether ctags reports the wrong information -or whether that information is correct and Tagbar does something wrong. To run -ctags manually execute the following command in a terminal: -> - ctags -f - --format=2 --excmd=pattern --extra= --fields=nksaSmt myfile -< -If you set the |g:tagbar_ctags_bin| variable you probably have to use the same -value here instead of simply "ctags". - -If Tagbar doesn't seem to work at all, but you don't get any error messages, -you can use Tagbar's debug mode to try to find the source of the problem (see -|tagbar-commands| on how to invoke it). In that case you should especially pay -attention to the reported file type and the ctags command line in the log -file. - - - - jsctags has to be newer than 2011-01-06 since it needs the "-f" option to - work. Also, the output of jsctags seems to be a bit unreliable at the - moment (especially regarding line numbers), so if you notice some strange - behaviour with it please run it manually in a terminal to check whether - the bug is in jsctags or Tagbar. - - - Nested pseudo-tags cannot be properly parsed since only the direct parent - scope of a tag gets assigned a type, the type of the grandparents is not - reported by ctags (assuming the grandparents don't have direct, real - children). - - For example, if we have a C++ file with the following content: -> - foo::Bar::init() - { - // ... - } - foo::Baz::method() - { - // ... - } -< - In this case the type of "foo" is not known. Is it a namespace? A class? - For this reason the methods are displayed in Tagbar like this: -> - foo::Bar* : class - init() - foo::Baz* : class - method() -< - - Scope-defining tags at the top level that have the same name but a - different kind/scope type can lead to an incorrect display. For example, - the following Python code will incorrectly insert a pseudo-tag "Inner2" - into the "test" class: -> - class test: - class Inner: - def foo(self): - pass - - def test(): - class Inner2: - def bar(self): - pass -< - I haven't found a clean way around this yet, but it shouldn't be much of a - problem in practice anyway. Tags with the same name at any other level are - no problem, though. - -============================================================================== -8. History *tagbar-history* - -2.3 (2011-12-24) - - Add a convenience function that allows more flexible ways to - automatically open Tagbar. - - Replace option tagbar_usearrows with tagbar_iconchars to allow custom - characters to be specified. This helps with fonts that don't display the - default characters properly. - - Remove the need to provide the complete jsctags configuration if jsctags - is not found in $PATH, now only the concrete path has to be specified. - - Add debugging functionality. - -2.2 (2011-11-26) - - Small incompatible change: TagbarOpen now doesn't jump to the Tagbar - window anymore if it is already open. Use "TagbarOpen j" instead or see - its documentation for more options. - - Tags inside of scopes now have a header displaying their "kind". - - The Tagbar contents are now immediately updated on save for files - smaller than a configurable size. - - Tagbar can now be configured to jump to a tag with only a single-click - instead of a double-click. - - Most of the script has been moved to the |autoload| directory, so Vim - startup should be faster (thanks to Kien N). - - Jumping to tags should work most of the time even if the file has been - modified and not saved. - - If Ctags has been installed into the default location using Homebrew or - MacPorts it should now be found automatically. - - Several bugfixes. - -2.1 (2011-05-29) - - Make Tagbar work in (hopefully) all cases under Windows - - Handle cases where 'encoding' is different from system encoding, for - example on a Chinese Windows with 'encoding' set to "utf-8" (see manual - for details in case it doesn't work out-of-the-box) - - Fixed a bug with the handling of subtypes like "python.django" - - If a session got saved with Tagbar open it now gets restored properly - - Locally reset foldmethod/foldexpr in case foldexpr got set to something - expensive globally - - Tagbar now tries hard to go to the correct window when jumping to a tag - - Explain some possible issues with the current jsctags version in the - manual - - Explicitly check for some possible configuration problems to be able to - give better feedback - - A few other small fixes - -2.0.1 (2011-04-26) - - Fix sorting bug when 'ignorecase' is set - -2.0 (2011-04-26) - - Folding now works correctly. Folds will be preserved when leaving the - Tagbar window and when switching between files. Also tag types can be - configured to be folded by default, which is useful for things like - includes and imports. - - DoctorJS/jsctags and other compatible programs are now supported. - - All of the highlight groups can now be overridden. - - Added keybinding to quickly jump to next/previous top-level tag. - - Added Taglist's "p" keybinding for jumping to a tag without leaving the - Tagbar window. - - Several bugfixes and other small improvements. - -1.5 (2011-03-06) - - Type definitions can now include a path to a file with the ctags - definition. This is especially useful for ftplugins that can now ship - with a complete ctags and Tagbar configuration without requiring user - intervention. Thanks to Jan Christoph Ebersbach for the suggestion. - - Added autofocus setting by Taybin Rutkin. This will put the cursor in - the Tagbar window when it is opened. - - The "scopes" field is no longer needed in type definitions, the - information is already there in "scope2kind". Existing definitions will - be ignored. - - Some fixes and improvements related to redrawing and window switching. - -1.2 (2011-02-28) - - Fix typo in Ruby definition - -1.1 (2011-02-26) - - Don't lose syntax highlighting when ':syntax enable' is called - - Allow expanding the Vim window when Tagbar is opened - -1.0 (2011-02-23) - - Initial release - -============================================================================== -9. Todo *tagbar-todo* - - - Allow filtering the Tagbar content by some criteria like tag name, - visibility, kind ... - - Integrate Tagbar with the FSwitch plugin to provide header file - information in C/C++. - - Allow jumping to a tag in the preview window, a split window or a new tab. - -============================================================================== -10. Credits *tagbar-credits* - -Tagbar was written by Jan Larres and is released under the Vim licence, see -|license|. It was heavily inspired by the Taglist plugin by Yegappan -Lakshmanan and uses a small amount of code from it. - -Original taglist copyright notice: -Permission is hereby granted to use and distribute this code, with or without -modifications, provided that this copyright notice is copied with it. Like -anything else that's free, taglist.vim is provided *as is* and comes with no -warranty of any kind, either expressed or implied. In no event will the -copyright holder be liable for any damamges resulting from the use of this -software. - -The folding technique was inspired by NERDTree by Martin Grenfell. - -Thanks to the following people for code contributions, feature suggestions etc: -Jan Christoph Ebersbach -Leandro Freitas -Seth Milliken -Kien N -pielgrzym -Taybin Rutkin - -============================================================================== - vim: tw=78 ts=8 sw=8 sts=8 noet ft=help diff --git a/vim/doc/taglist.txt b/vim/doc/taglist.txt deleted file mode 100644 index 6a62b39..0000000 --- a/vim/doc/taglist.txt +++ /dev/null @@ -1,1501 +0,0 @@ -*taglist.txt* Plugin for browsing source code - -Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com) -For Vim version 6.0 and above -Last change: 2007 May 24 - -1. Overview |taglist-intro| -2. Taglist on the internet |taglist-internet| -3. Requirements |taglist-requirements| -4. Installation |taglist-install| -5. Usage |taglist-using| -6. Options |taglist-options| -7. Commands |taglist-commands| -8. Global functions |taglist-functions| -9. Extending |taglist-extend| -10. FAQ |taglist-faq| -11. License |taglist-license| -12. Todo |taglist-todo| - -============================================================================== - *taglist-intro* -1. Overview~ - -The "Tag List" plugin is a source code browser plugin for Vim. This plugin -allows you to efficiently browse through source code files for different -programming languages. The "Tag List" plugin provides the following features: - - * Displays the tags (functions, classes, structures, variables, etc.) - defined in a file in a vertically or horizontally split Vim window. - * In GUI Vim, optionally displays the tags in the Tags drop-down menu and - in the popup menu. - * Automatically updates the taglist window as you switch between - files/buffers. As you open new files, the tags defined in the new files - are added to the existing file list and the tags defined in all the - files are displayed grouped by the filename. - * When a tag name is selected from the taglist window, positions the - cursor at the definition of the tag in the source file. - * Automatically highlights the current tag name. - * Groups the tags by their type and displays them in a foldable tree. - * Can display the prototype and scope of a tag. - * Can optionally display the tag prototype instead of the tag name in the - taglist window. - * The tag list can be sorted either by name or by chronological order. - * Supports the following language files: Assembly, ASP, Awk, Beta, C, - C++, C#, Cobol, Eiffel, Erlang, Fortran, HTML, Java, Javascript, Lisp, - Lua, Make, Pascal, Perl, PHP, Python, Rexx, Ruby, Scheme, Shell, Slang, - SML, Sql, TCL, Verilog, Vim and Yacc. - * Can be easily extended to support new languages. Support for - existing languages can be modified easily. - * Provides functions to display the current tag name in the Vim status - line or the window title bar. - * The list of tags and files in the taglist can be saved and - restored across Vim sessions. - * Provides commands to get the name and prototype of the current tag. - * Runs in both console/terminal and GUI versions of Vim. - * Works with the winmanager plugin. Using the winmanager plugin, you - can use Vim plugins like the file explorer, buffer explorer and the - taglist plugin at the same time like an IDE. - * Can be used in both Unix and MS-Windows systems. - -============================================================================== - *taglist-internet* -2. Taglist on the internet~ - -The home page of the taglist plugin is at: -> - http://vim-taglist.sourceforge.net/ -< -You can subscribe to the taglist mailing list to post your questions or -suggestions for improvement or to send bug reports. Visit the following page -for subscribing to the mailing list: -> - http://groups.yahoo.com/group/taglist -< -============================================================================== - *taglist-requirements* -3. Requirements~ - -The taglist plugin requires the following: - - * Vim version 6.0 and above - * Exuberant ctags 5.0 and above - -The taglist plugin will work on all the platforms where the exuberant ctags -utility and Vim are supported (this includes MS-Windows and Unix based -systems). - -The taglist plugin relies on the exuberant ctags utility to dynamically -generate the tag listing. The exuberant ctags utility must be installed in -your system to use this plugin. The exuberant ctags utility is shipped with -most of the Linux distributions. You can download the exuberant ctags utility -from -> - http://ctags.sourceforge.net -< -The taglist plugin doesn't use or create a tags file and there is no need to -create a tags file to use this plugin. The taglist plugin will not work with -the GNU ctags or the Unix ctags utility. - -This plugin relies on the Vim "filetype" detection mechanism to determine the -type of the current file. You have to turn on the Vim filetype detection by -adding the following line to your .vimrc file: -> - filetype on -< -The taglist plugin will not work if you run Vim in the restricted mode (using -the -Z command-line argument). - -The taglist plugin uses the Vim system() function to invoke the exuberant -ctags utility. If Vim is compiled without the system() function then you -cannot use the taglist plugin. Some of the Linux distributions (Suse) compile -Vim without the system() function for security reasons. - -============================================================================== - *taglist-install* -4. Installation~ - -1. Download the taglist.zip file and unzip the files to the $HOME/.vim or the - $HOME/vimfiles or the $VIM/vimfiles directory. After this step, you should - have the following two files (the directory structure should be preserved): - - plugin/taglist.vim - main taglist plugin file - doc/taglist.txt - documentation (help) file - - Refer to the |add-plugin|and |'runtimepath'| Vim help pages for more - details about installing Vim plugins. -2. Change to the $HOME/.vim/doc or $HOME/vimfiles/doc or $VIM/vimfiles/doc - directory, start Vim and run the ":helptags ." command to process the - taglist help file. Without this step, you cannot jump to the taglist help - topics. -3. If the exuberant ctags utility is not present in one of the directories in - the PATH environment variable, then set the 'Tlist_Ctags_Cmd' variable to - point to the location of the exuberant ctags utility (not to the directory) - in the .vimrc file. -4. If you are running a terminal/console version of Vim and the terminal - doesn't support changing the window width then set the - 'Tlist_Inc_Winwidth' variable to 0 in the .vimrc file. -5. Restart Vim. -6. You can now use the ":TlistToggle" command to open/close the taglist - window. You can use the ":help taglist" command to get more information - about using the taglist plugin. - -To uninstall the taglist plugin, remove the plugin/taglist.vim and -doc/taglist.txt files from the $HOME/.vim or $HOME/vimfiles directory. - -============================================================================== - *taglist-using* -5. Usage~ - -The taglist plugin can be used in several different ways. - -1. You can keep the taglist window open during the entire editing session. On - opening the taglist window, the tags defined in all the files in the Vim - buffer list will be displayed in the taglist window. As you edit files, the - tags defined in them will be added to the taglist window. You can select a - tag from the taglist window and jump to it. The current tag will be - highlighted in the taglist window. You can close the taglist window when - you no longer need the window. -2. You can configure the taglist plugin to process the tags defined in all the - edited files always. In this configuration, even if the taglist window is - closed and the taglist menu is not displayed, the taglist plugin will - processes the tags defined in newly edited files. You can then open the - taglist window only when you need to select a tag and then automatically - close the taglist window after selecting the tag. -3. You can configure the taglist plugin to display only the tags defined in - the current file in the taglist window. By default, the taglist plugin - displays the tags defined in all the files in the Vim buffer list. As you - switch between files, the taglist window will be refreshed to display only - the tags defined in the current file. -4. In GUI Vim, you can use the Tags pull-down and popup menu created by the - taglist plugin to display the tags defined in the current file and select a - tag to jump to it. You can use the menu without opening the taglist window. - By default, the Tags menu is disabled. -5. You can configure the taglist plugin to display the name of the current tag - in the Vim window status line or in the Vim window title bar. For this to - work without the taglist window or menu, you need to configure the taglist - plugin to process the tags defined in a file always. -6. You can save the tags defined in multiple files to a taglist session file - and load it when needed. You can also configure the taglist plugin to not - update the taglist window when editing new files. You can then manually add - files to the taglist window. - -Opening the taglist window~ -You can open the taglist window using the ":TlistOpen" or the ":TlistToggle" -commands. The ":TlistOpen" command opens the taglist window and jumps to it. -The ":TlistToggle" command opens or closes (toggle) the taglist window and the -cursor remains in the current window. If the 'Tlist_GainFocus_On_ToggleOpen' -variable is set to 1, then the ":TlistToggle" command opens the taglist window -and moves the cursor to the taglist window. - -You can map a key to invoke these commands. For example, the following command -creates a normal mode mapping for the <F8> key to toggle the taglist window. -> - nnoremap <silent> <F8> :TlistToggle<CR> -< -Add the above mapping to your ~/.vimrc or $HOME/_vimrc file. - -To automatically open the taglist window on Vim startup, set the -'Tlist_Auto_Open' variable to 1. - -You can also open the taglist window on startup using the following command -line: -> - $ vim +TlistOpen -< -Closing the taglist window~ -You can close the taglist window from the taglist window by pressing 'q' or -using the Vim ":q" command. You can also use any of the Vim window commands to -close the taglist window. Invoking the ":TlistToggle" command when the taglist -window is opened, closes the taglist window. You can also use the -":TlistClose" command to close the taglist window. - -To automatically close the taglist window when a tag or file is selected, you -can set the 'Tlist_Close_On_Select' variable to 1. To exit Vim when only the -taglist window is present, set the 'Tlist_Exit_OnlyWindow' variable to 1. - -Jumping to a tag or a file~ -You can select a tag in the taglist window either by pressing the <Enter> key -or by double clicking the tag name using the mouse. To jump to a tag on a -single mouse click set the 'Tlist_Use_SingleClick' variable to 1. - -If the selected file is already opened in a window, then the cursor is moved -to that window. If the file is not currently opened in a window then the file -is opened in the window used by the taglist plugin to show the previously -selected file. If there are no usable windows, then the file is opened in a -new window. The file is not opened in special windows like the quickfix -window, preview window and windows containing buffer with the 'buftype' option -set. - -To jump to the tag in a new window, press the 'o' key. To open the file in the -previous window (Ctrl-W_p) use the 'P' key. You can press the 'p' key to jump -to the tag but still keep the cursor in the taglist window (preview). - -To open the selected file in a tab, use the 't' key. If the file is already -present in a tab then the cursor is moved to that tab otherwise the file is -opened in a new tab. To jump to a tag in a new tab press Ctrl-t. The taglist -window is automatically opened in the newly created tab. - -Instead of jumping to a tag, you can open a file by pressing the <Enter> key -or by double clicking the file name using the mouse. - -In the taglist window, you can use the [[ or <Backspace> key to jump to the -beginning of the previous file. You can use the ]] or <Tab> key to jump to the -beginning of the next file. When you reach the first or last file, the search -wraps around and the jumps to the next/previous file. - -Highlighting the current tag~ -The taglist plugin automatically highlights the name of the current tag in the -taglist window. The Vim |CursorHold| autocmd event is used for this. If the -current tag name is not visible in the taglist window, then the taglist window -contents are scrolled to make that tag name visible. You can also use the -":TlistHighlightTag" command to force the highlighting of the current tag. - -The tag name is highlighted if no activity is performed for |'updatetime'| -milliseconds. The default value for this Vim option is 4 seconds. To avoid -unexpected problems, you should not set the |'updatetime'| option to a very -low value. - -To disable the automatic highlighting of the current tag name in the taglist -window, set the 'Tlist_Auto_Highlight_Tag' variable to zero. - -When entering a Vim buffer/window, the taglist plugin automatically highlights -the current tag in that buffer/window. If you like to disable the automatic -highlighting of the current tag when entering a buffer, set the -'Tlist_Highlight_Tag_On_BufEnter' variable to zero. - -Adding files to the taglist~ -When the taglist window is opened, all the files in the Vim buffer list are -processed and the supported files are added to the taglist. When you edit a -file in Vim, the taglist plugin automatically processes this file and adds it -to the taglist. If you close the taglist window, the tag information in the -taglist is retained. - -To process files even when the taglist window is not open, set the -'Tlist_Process_File_Always' variable to 1. - -You can manually add multiple files to the taglist without opening them using -the ":TlistAddFiles" and the ":TlistAddFilesRecursive" commands. - -For example, to add all the C files in the /my/project/dir directory to the -taglist, you can use the following command: -> - :TlistAddFiles /my/project/dir/*.c -< -Note that when adding several files with a large number of tags or a large -number of files, it will take several seconds to several minutes for the -taglist plugin to process all the files. You should not interrupt the taglist -plugin by pressing <CTRL-C>. - -You can recursively add multiple files from a directory tree using the -":TlistAddFilesRecursive" command: -> - :TlistAddFilesRecursive /my/project/dir *.c -< -This command takes two arguments. The first argument specifies the directory -from which to recursively add the files. The second optional argument -specifies the wildcard matching pattern for selecting the files to add. The -default pattern is * and all the files are added. - -Displaying tags for only one file~ -The taglist window displays the tags for all the files in the Vim buffer list -and all the manually added files. To display the tags for only the current -active buffer, set the 'Tlist_Show_One_File' variable to 1. - -Removing files from the taglist~ -You can remove a file from the taglist window, by pressing the 'd' key when the -cursor is on one of the tags listed for the file in the taglist window. The -removed file will no longer be displayed in the taglist window in the current -Vim session. To again display the tags for the file, open the file in a Vim -window and then use the ":TlistUpdate" command or use ":TlistAddFiles" command -to add the file to the taglist. - -When a buffer is removed from the Vim buffer list using the ":bdelete" or the -":bwipeout" command, the taglist is updated to remove the stored information -for this buffer. - -Updating the tags displayed for a file~ -The taglist plugin keeps track of the modification time of a file. When the -modification time changes (the file is modified), the taglist plugin -automatically updates the tags listed for that file. The modification time of -a file is checked when you enter a window containing that file or when you -load that file. - -You can also update or refresh the tags displayed for a file by pressing the -"u" key in the taglist window. If an existing file is modified, after the file -is saved, the taglist plugin automatically updates the tags displayed for the -file. - -You can also use the ":TlistUpdate" command to update the tags for the current -buffer after you made some changes to it. You should save the modified buffer -before you update the taglist window. Otherwise the listed tags will not -include the new tags created in the buffer. - -If you have deleted the tags displayed for a file in the taglist window using -the 'd' key, you can again display the tags for that file using the -":TlistUpdate" command. - -Controlling the taglist updates~ -To disable the automatic processing of new files or modified files, you can -set the 'Tlist_Auto_Update' variable to zero. When this variable is set to -zero, the taglist is updated only when you use the ":TlistUpdate" command or -the ":TlistAddFiles" or the ":TlistAddFilesRecursive" commands. You can use -this option to control which files are added to the taglist. - -You can use the ":TlistLock" command to lock the taglist contents. After this -command is executed, new files are not automatically added to the taglist. -When the taglist is locked, you can use the ":TlistUpdate" command to add the -current file or the ":TlistAddFiles" or ":TlistAddFilesRecursive" commands to -add new files to the taglist. To unlock the taglist, use the ":TlistUnlock" -command. - -Displaying the tag prototype~ -To display the prototype of the tag under the cursor in the taglist window, -press the space bar. If you place the cursor on a tag name in the taglist -window, then the tag prototype is displayed at the Vim status line after -|'updatetime'| milliseconds. The default value for the |'updatetime'| Vim -option is 4 seconds. - -You can get the name and prototype of a tag without opening the taglist window -and the taglist menu using the ":TlistShowTag" and the ":TlistShowPrototype" -commands. These commands will work only if the current file is already present -in the taglist. To use these commands without opening the taglist window, set -the 'Tlist_Process_File_Always' variable to 1. - -You can use the ":TlistShowTag" command to display the name of the tag at or -before the specified line number in the specified file. If the file name and -line number are not supplied, then this command will display the name of the -current tag. For example, -> - :TlistShowTag - :TlistShowTag myfile.java 100 -< -You can use the ":TlistShowPrototype" command to display the prototype of the -tag at or before the specified line number in the specified file. If the file -name and the line number are not supplied, then this command will display the -prototype of the current tag. For example, -> - :TlistShowPrototype - :TlistShowPrototype myfile.c 50 -< -In the taglist window, when the mouse is moved over a tag name, the tag -prototype is displayed in a balloon. This works only in GUI versions where -balloon evaluation is supported. - -Taglist window contents~ -The taglist window contains the tags defined in various files in the taglist -grouped by the filename and by the tag type (variable, function, class, etc.). -For tags with scope information (like class members, structures inside -structures, etc.), the scope information is displayed in square brackets "[]" -after the tag name. - -The contents of the taglist buffer/window are managed by the taglist plugin. -The |'filetype'| for the taglist buffer is set to 'taglist'. The Vim -|'modifiable'| option is turned off for the taglist buffer. You should not -manually edit the taglist buffer, by setting the |'modifiable'| flag. If you -manually edit the taglist buffer contents, then the taglist plugin will be out -of sync with the taglist buffer contents and the plugin will no longer work -correctly. To redisplay the taglist buffer contents again, close the taglist -window and reopen it. - -Opening and closing the tag and file tree~ -In the taglist window, the tag names are displayed as a foldable tree using -the Vim folding support. You can collapse the tree using the '-' key or using -the Vim |zc| fold command. You can open the tree using the '+' key or using -the Vim |zo| fold command. You can open all the folds using the '*' key or -using the Vim |zR| fold command. You can also use the mouse to open/close the -folds. You can close all the folds using the '=' key. You should not manually -create or delete the folds in the taglist window. - -To automatically close the fold for the inactive files/buffers and open only -the fold for the current buffer in the taglist window, set the -'Tlist_File_Fold_Auto_Close' variable to 1. - -Sorting the tags for a file~ -The tags displayed in the taglist window can be sorted either by their name or -by their chronological order. The default sorting method is by the order in -which the tags appear in a file. You can change the default sort method by -setting the 'Tlist_Sort_Type' variable to either "name" or "order". You can -sort the tags by their name by pressing the "s" key in the taglist window. You -can again sort the tags by their chronological order using the "s" key. Each -file in the taglist window can be sorted using different order. - -Zooming in and out of the taglist window~ -You can press the 'x' key in the taglist window to maximize the taglist -window width/height. The window will be maximized to the maximum possible -width/height without closing the other existing windows. You can again press -'x' to restore the taglist window to the default width/height. - - *taglist-session* -Taglist Session~ -A taglist session refers to the group of files and their tags stored in the -taglist in a Vim session. - -You can save and restore a taglist session (and all the displayed tags) using -the ":TlistSessionSave" and ":TlistSessionLoad" commands. - -To save the information about the tags and files in the taglist to a file, use -the ":TlistSessionSave" command and specify the filename: -> - :TlistSessionSave <file name> -< -To load a saved taglist session, use the ":TlistSessionLoad" command: > - - :TlistSessionLoad <file name> -< -When you load a taglist session file, the tags stored in the file will be -added to the tags already stored in the taglist. - -The taglist session feature can be used to save the tags for large files or a -group of frequently used files (like a project). By using the taglist session -file, you can minimize the amount to time it takes to load/refresh the taglist -for multiple files. - -You can create more than one taglist session file for multiple groups of -files. - -Displaying the tag name in the Vim status line or the window title bar~ -You can use the Tlist_Get_Tagname_By_Line() function provided by the taglist -plugin to display the current tag name in the Vim status line or the window -title bar. Similarly, you can use the Tlist_Get_Tag_Prototype_By_Line() -function to display the current tag prototype in the Vim status line or the -window title bar. - -For example, the following command can be used to display the current tag name -in the status line: -> - :set statusline=%<%f%=%([%{Tlist_Get_Tagname_By_Line()}]%) -< -The following command can be used to display the current tag name in the -window title bar: -> - :set title titlestring=%<%f\ %([%{Tlist_Get_Tagname_By_Line()}]%) -< -Note that the current tag name can be displayed only after the file is -processed by the taglist plugin. For this, you have to either set the -'Tlist_Process_File_Always' variable to 1 or open the taglist window or use -the taglist menu. For more information about configuring the Vim status line, -refer to the documentation for the Vim |'statusline'| option. - -Changing the taglist window highlighting~ -The following Vim highlight groups are defined and used to highlight the -various entities in the taglist window: - - TagListTagName - Used for tag names - TagListTagScope - Used for tag scope - TagListTitle - Used for tag titles - TagListComment - Used for comments - TagListFileName - Used for filenames - -By default, these highlight groups are linked to the standard Vim highlight -groups. If you want to change the colors used for these highlight groups, -prefix the highlight group name with 'My' and define it in your .vimrc or -.gvimrc file: MyTagListTagName, MyTagListTagScope, MyTagListTitle, -MyTagListComment and MyTagListFileName. For example, to change the colors -used for tag names, you can use the following command: -> - :highlight MyTagListTagName guifg=blue ctermfg=blue -< -Controlling the taglist window~ -To use a horizontally split taglist window, instead of a vertically split -window, set the 'Tlist_Use_Horiz_Window' variable to 1. - -To use a vertically split taglist window on the rightmost side of the Vim -window, set the 'Tlist_Use_Right_Window' variable to 1. - -You can specify the width of the vertically split taglist window, by setting -the 'Tlist_WinWidth' variable. You can specify the height of the horizontally -split taglist window, by setting the 'Tlist_WinHeight' variable. - -When opening a vertically split taglist window, the Vim window width is -increased to accommodate the new taglist window. When the taglist window is -closed, the Vim window is reduced. To disable this, set the -'Tlist_Inc_Winwidth' variable to zero. - -To reduce the number of empty lines in the taglist window, set the -'Tlist_Compact_Format' variable to 1. - -To not display the Vim fold column in the taglist window, set the -'Tlist_Enable_Fold_Column' variable to zero. - -To display the tag prototypes instead of the tag names in the taglist window, -set the 'Tlist_Display_Prototype' variable to 1. - -To not display the scope of the tags next to the tag names, set the -'Tlist_Display_Tag_Scope' variable to zero. - - *taglist-keys* -Taglist window key list~ -The following table lists the description of the keys that can be used -in the taglist window. - - Key Description~ - - <CR> Jump to the location where the tag under cursor is - defined. - o Jump to the location where the tag under cursor is - defined in a new window. - P Jump to the tag in the previous (Ctrl-W_p) window. - p Display the tag definition in the file window and - keep the cursor in the taglist window itself. - t Jump to the tag in a new tab. If the file is already - opened in a tab, move to that tab. - Ctrl-t Jump to the tag in a new tab. - <Space> Display the prototype of the tag under the cursor. - For file names, display the full path to the file, - file type and the number of tags. For tag types, display the - tag type and the number of tags. - u Update the tags listed in the taglist window - s Change the sort order of the tags (by name or by order) - d Remove the tags for the file under the cursor - x Zoom-in or Zoom-out the taglist window - + Open a fold - - Close a fold - * Open all folds - = Close all folds - [[ Jump to the beginning of the previous file - <Backspace> Jump to the beginning of the previous file - ]] Jump to the beginning of the next file - <Tab> Jump to the beginning of the next file - q Close the taglist window - <F1> Display help - -The above keys will work in both the normal mode and the insert mode. - - *taglist-menu* -Taglist menu~ -When using GUI Vim, the taglist plugin can display the tags defined in the -current file in the drop-down menu and the popup menu. By default, this -feature is turned off. To turn on this feature, set the 'Tlist_Show_Menu' -variable to 1. - -You can jump to a tag by selecting the tag name from the menu. You can use the -taglist menu independent of the taglist window i.e. you don't need to open the -taglist window to get the taglist menu. - -When you switch between files/buffers, the taglist menu is automatically -updated to display the tags defined in the current file/buffer. - -The tags are grouped by their type (variables, functions, classes, methods, -etc.) and displayed as a separate sub-menu for each type. If all the tags -defined in a file are of the same type (e.g. functions), then the sub-menu is -not used. - -If the number of items in a tag type submenu exceeds the value specified by -the 'Tlist_Max_Submenu_Items' variable, then the submenu will be split into -multiple submenus. The default setting for 'Tlist_Max_Submenu_Items' is 25. -The first and last tag names in the submenu are used to form the submenu name. -The menu items are prefixed by alpha-numeric characters for easy selection by -keyboard. - -If the popup menu support is enabled (the |'mousemodel'| option contains -"popup"), then the tags menu is added to the popup menu. You can access -the popup menu by right clicking on the GUI window. - -You can regenerate the tags menu by selecting the 'Tags->Refresh menu' entry. -You can sort the tags listed in the menu either by name or by order by -selecting the 'Tags->Sort menu by->Name/Order' menu entry. - -You can tear-off the Tags menu and keep it on the side of the Vim window -for quickly locating the tags. - -Using the taglist plugin with the winmanager plugin~ -You can use the taglist plugin with the winmanager plugin. This will allow you -to use the file explorer, buffer explorer and the taglist plugin at the same -time in different windows. To use the taglist plugin with the winmanager -plugin, set 'TagList' in the 'winManagerWindowLayout' variable. For example, -to use the file explorer plugin and the taglist plugin at the same time, use -the following setting: > - - let winManagerWindowLayout = 'FileExplorer|TagList' -< -Getting help~ -If you have installed the taglist help file (this file), then you can use the -Vim ":help taglist-<keyword>" command to get help on the various taglist -topics. - -You can press the <F1> key in the taglist window to display the help -information about using the taglist window. If you again press the <F1> key, -the help information is removed from the taglist window. - - *taglist-debug* -Debugging the taglist plugin~ -You can use the ":TlistDebug" command to enable logging of the debug messages -from the taglist plugin. To display the logged debug messages, you can use the -":TlistMessages" command. To disable the logging of the debug messages, use -the ":TlistUndebug" command. - -You can specify a file name to the ":TlistDebug" command to log the debug -messages to a file. Otherwise, the debug messages are stored in a script-local -variable. In the later case, to minimize memory usage, only the last 3000 -characters from the debug messages are stored. - -============================================================================== - *taglist-options* -6. Options~ - -A number of Vim variables control the behavior of the taglist plugin. These -variables are initialized to a default value. By changing these variables you -can change the behavior of the taglist plugin. You need to change these -settings only if you want to change the behavior of the taglist plugin. You -should use the |:let| command in your .vimrc file to change the setting of any -of these variables. - -The configurable taglist variables are listed below. For a detailed -description of these variables refer to the text below this table. - -|'Tlist_Auto_Highlight_Tag'| Automatically highlight the current tag in the - taglist. -|'Tlist_Auto_Open'| Open the taglist window when Vim starts. -|'Tlist_Auto_Update'| Automatically update the taglist to include - newly edited files. -|'Tlist_Close_On_Select'| Close the taglist window when a file or tag is - selected. -|'Tlist_Compact_Format'| Remove extra information and blank lines from - the taglist window. -|'Tlist_Ctags_Cmd'| Specifies the path to the ctags utility. -|'Tlist_Display_Prototype'| Show prototypes and not tags in the taglist - window. -|'Tlist_Display_Tag_Scope'| Show tag scope next to the tag name. -|'Tlist_Enable_Fold_Column'| Show the fold indicator column in the taglist - window. -|'Tlist_Exit_OnlyWindow'| Close Vim if the taglist is the only window. -|'Tlist_File_Fold_Auto_Close'| Close tag folds for inactive buffers. -|'Tlist_GainFocus_On_ToggleOpen'| - Jump to taglist window on open. -|'Tlist_Highlight_Tag_On_BufEnter'| - On entering a buffer, automatically highlight - the current tag. -|'Tlist_Inc_Winwidth'| Increase the Vim window width to accommodate - the taglist window. -|'Tlist_Max_Submenu_Items'| Maximum number of items in a tags sub-menu. -|'Tlist_Max_Tag_Length'| Maximum tag length used in a tag menu entry. -|'Tlist_Process_File_Always'| Process files even when the taglist window is - closed. -|'Tlist_Show_Menu'| Display the tags menu. -|'Tlist_Show_One_File'| Show tags for the current buffer only. -|'Tlist_Sort_Type'| Sort method used for arranging the tags. -|'Tlist_Use_Horiz_Window'| Use a horizontally split window for the - taglist window. -|'Tlist_Use_Right_Window'| Place the taglist window on the right side. -|'Tlist_Use_SingleClick'| Single click on a tag jumps to it. -|'Tlist_WinHeight'| Horizontally split taglist window height. -|'Tlist_WinWidth'| Vertically split taglist window width. - - *'Tlist_Auto_Highlight_Tag'* -Tlist_Auto_Highlight_Tag~ -The taglist plugin will automatically highlight the current tag in the taglist -window. If you want to disable this, then you can set the -'Tlist_Auto_Highlight_Tag' variable to zero. Note that even though the current -tag highlighting is disabled, the tags for a new file will still be added to -the taglist window. -> - let Tlist_Auto_Highlight_Tag = 0 -< -With the above variable set to 1, you can use the ":TlistHighlightTag" command -to highlight the current tag. - - *'Tlist_Auto_Open'* -Tlist_Auto_Open~ -To automatically open the taglist window, when you start Vim, you can set the -'Tlist_Auto_Open' variable to 1. By default, this variable is set to zero and -the taglist window will not be opened automatically on Vim startup. -> - let Tlist_Auto_Open = 1 -< -The taglist window is opened only when a supported type of file is opened on -Vim startup. For example, if you open text files, then the taglist window will -not be opened. - - *'Tlist_Auto_Update'* -Tlist_Auto_Update~ -When a new file is edited, the tags defined in the file are automatically -processed and added to the taglist. To stop adding new files to the taglist, -set the 'Tlist_Auto_Update' variable to zero. By default, this variable is set -to 1. -> - let Tlist_Auto_Update = 0 -< -With the above variable set to 1, you can use the ":TlistUpdate" command to -add the tags defined in the current file to the taglist. - - *'Tlist_Close_On_Select'* -Tlist_Close_On_Select~ -If you want to close the taglist window when a file or tag is selected, then -set the 'Tlist_Close_On_Select' variable to 1. By default, this variable is -set zero and when you select a tag or file from the taglist window, the window -is not closed. -> - let Tlist_Close_On_Select = 1 -< - *'Tlist_Compact_Format'* -Tlist_Compact_Format~ -By default, empty lines are used to separate different tag types displayed for -a file and the tags displayed for different files in the taglist window. If -you want to display as many tags as possible in the taglist window, you can -set the 'Tlist_Compact_Format' variable to 1 to get a compact display. -> - let Tlist_Compact_Format = 1 -< - *'Tlist_Ctags_Cmd'* -Tlist_Ctags_Cmd~ -The 'Tlist_Ctags_Cmd' variable specifies the location (path) of the exuberant -ctags utility. If exuberant ctags is present in any one of the directories in -the PATH environment variable, then there is no need to set this variable. - -The exuberant ctags tool can be installed under different names. When the -taglist plugin starts up, if the 'Tlist_Ctags_Cmd' variable is not set, it -checks for the names exuberant-ctags, exctags, ctags, ctags.exe and tags in -the PATH environment variable. If any one of the named executable is found, -then the Tlist_Ctags_Cmd variable is set to that name. - -If exuberant ctags is not present in one of the directories specified in the -PATH environment variable, then set this variable to point to the location of -the ctags utility in your system. Note that this variable should point to the -fully qualified exuberant ctags location and NOT to the directory in which -exuberant ctags is installed. If the exuberant ctags tool is not found in -either PATH or in the specified location, then the taglist plugin will not be -loaded. Examples: -> - let Tlist_Ctags_Cmd = 'd:\tools\ctags.exe' - let Tlist_Ctags_Cmd = '/usr/local/bin/ctags' -< - *'Tlist_Display_Prototype'* -Tlist_Display_Prototype~ -By default, only the tag name will be displayed in the taglist window. If you -like to see tag prototypes instead of names, set the 'Tlist_Display_Prototype' -variable to 1. By default, this variable is set to zero and only tag names -will be displayed. -> - let Tlist_Display_Prototype = 1 -< - *'Tlist_Display_Tag_Scope'* -Tlist_Display_Tag_Scope~ -By default, the scope of a tag (like a C++ class) will be displayed in -square brackets next to the tag name. If you don't want the tag scopes -to be displayed, then set the 'Tlist_Display_Tag_Scope' to zero. By default, -this variable is set to 1 and the tag scopes will be displayed. -> - let Tlist_Display_Tag_Scope = 0 -< - *'Tlist_Enable_Fold_Column'* -Tlist_Enable_Fold_Column~ -By default, the Vim fold column is enabled and displayed in the taglist -window. If you wish to disable this (for example, when you are working with a -narrow Vim window or terminal), you can set the 'Tlist_Enable_Fold_Column' -variable to zero. -> - let Tlist_Enable_Fold_Column = 1 -< - *'Tlist_Exit_OnlyWindow'* -Tlist_Exit_OnlyWindow~ -If you want to exit Vim if only the taglist window is currently opened, then -set the 'Tlist_Exit_OnlyWindow' variable to 1. By default, this variable is -set to zero and the Vim instance will not be closed if only the taglist window -is present. -> - let Tlist_Exit_OnlyWindow = 1 -< - *'Tlist_File_Fold_Auto_Close'* -Tlist_File_Fold_Auto_Close~ -By default, the tags tree displayed in the taglist window for all the files is -opened. You can close/fold the tags tree for the files manually. To -automatically close the tags tree for inactive files, you can set the -'Tlist_File_Fold_Auto_Close' variable to 1. When this variable is set to 1, -the tags tree for the current buffer is automatically opened and for all the -other buffers is closed. -> - let Tlist_File_Fold_Auto_Close = 1 -< - *'Tlist_GainFocus_On_ToggleOpen'* -Tlist_GainFocus_On_ToggleOpen~ -When the taglist window is opened using the ':TlistToggle' command, this -option controls whether the cursor is moved to the taglist window or remains -in the current window. By default, this option is set to 0 and the cursor -remains in the current window. When this variable is set to 1, the cursor -moves to the taglist window after opening the taglist window. -> - let Tlist_GainFocus_On_ToggleOpen = 1 -< - *'Tlist_Highlight_Tag_On_BufEnter'* -Tlist_Highlight_Tag_On_BufEnter~ -When you enter a Vim buffer/window, the current tag in that buffer/window is -automatically highlighted in the taglist window. If the current tag name is -not visible in the taglist window, then the taglist window contents are -scrolled to make that tag name visible. If you like to disable the automatic -highlighting of the current tag when entering a buffer, you can set the -'Tlist_Highlight_Tag_On_BufEnter' variable to zero. The default setting for -this variable is 1. -> - let Tlist_Highlight_Tag_On_BufEnter = 0 -< - *'Tlist_Inc_Winwidth'* -Tlist_Inc_Winwidth~ -By default, when the width of the window is less than 100 and a new taglist -window is opened vertically, then the window width is increased by the value -set in the 'Tlist_WinWidth' variable to accommodate the new window. The value -of this variable is used only if you are using a vertically split taglist -window. - -If your terminal doesn't support changing the window width from Vim (older -version of xterm running in a Unix system) or if you see any weird problems in -the screen due to the change in the window width or if you prefer not to -adjust the window width then set the 'Tlist_Inc_Winwidth' variable to zero. -CAUTION: If you are using the MS-Windows version of Vim in a MS-DOS command -window then you must set this variable to zero, otherwise the system may hang -due to a Vim limitation (explained in :help win32-problems) -> - let Tlist_Inc_Winwidth = 0 -< - *'Tlist_Max_Submenu_Items'* -Tlist_Max_Submenu_Items~ -If a file contains too many tags of a particular type (function, variable, -class, etc.), greater than that specified by the 'Tlist_Max_Submenu_Items' -variable, then the menu for that tag type will be split into multiple -sub-menus. The default setting for the 'Tlist_Max_Submenu_Items' variable is -25. This can be changed by setting the 'Tlist_Max_Submenu_Items' variable: -> - let Tlist_Max_Submenu_Items = 20 -< -The name of the submenu is formed using the names of the first and the last -tag entries in that submenu. - - *'Tlist_Max_Tag_Length'* -Tlist_Max_Tag_Length~ -Only the first 'Tlist_Max_Tag_Length' characters from the tag names will be -used to form the tag type submenu name. The default value for this variable is -10. Change the 'Tlist_Max_Tag_Length' setting if you want to include more or -less characters: -> - let Tlist_Max_Tag_Length = 10 -< - *'Tlist_Process_File_Always'* -Tlist_Process_File_Always~ -By default, the taglist plugin will generate and process the tags defined in -the newly opened files only when the taglist window is opened or when the -taglist menu is enabled. When the taglist window is closed, the taglist plugin -will stop processing the tags for newly opened files. - -You can set the 'Tlist_Process_File_Always' variable to 1 to generate the list -of tags for new files even when the taglist window is closed and the taglist -menu is disabled. -> - let Tlist_Process_File_Always = 1 -< -To use the ":TlistShowTag" and the ":TlistShowPrototype" commands without the -taglist window and the taglist menu, you should set this variable to 1. - - *'Tlist_Show_Menu'* -Tlist_Show_Menu~ -When using GUI Vim, you can display the tags defined in the current file in a -menu named "Tags". By default, this feature is turned off. To turn on this -feature, set the 'Tlist_Show_Menu' variable to 1: -> - let Tlist_Show_Menu = 1 -< - *'Tlist_Show_One_File'* -Tlist_Show_One_File~ -By default, the taglist plugin will display the tags defined in all the loaded -buffers in the taglist window. If you prefer to display the tags defined only -in the current buffer, then you can set the 'Tlist_Show_One_File' to 1. When -this variable is set to 1, as you switch between buffers, the taglist window -will be refreshed to display the tags for the current buffer and the tags for -the previous buffer will be removed. -> - let Tlist_Show_One_File = 1 -< - *'Tlist_Sort_Type'* -Tlist_Sort_Type~ -The 'Tlist_Sort_Type' variable specifies the sort order for the tags in the -taglist window. The tags can be sorted either alphabetically by their name or -by the order of their appearance in the file (chronological order). By -default, the tag names will be listed by the order in which they are defined -in the file. You can change the sort type (from name to order or from order to -name) by pressing the "s" key in the taglist window. You can also change the -default sort order by setting 'Tlist_Sort_Type' to "name" or "order": -> - let Tlist_Sort_Type = "name" -< - *'Tlist_Use_Horiz_Window'* -Tlist_Use_Horiz_Window~ -Be default, the tag names are displayed in a vertically split window. If you -prefer a horizontally split window, then set the 'Tlist_Use_Horiz_Window' -variable to 1. If you are running MS-Windows version of Vim in a MS-DOS -command window, then you should use a horizontally split window instead of a -vertically split window. Also, if you are using an older version of xterm in a -Unix system that doesn't support changing the xterm window width, you should -use a horizontally split window. -> - let Tlist_Use_Horiz_Window = 1 -< - *'Tlist_Use_Right_Window'* -Tlist_Use_Right_Window~ -By default, the vertically split taglist window will appear on the left hand -side. If you prefer to open the window on the right hand side, you can set the -'Tlist_Use_Right_Window' variable to 1: -> - let Tlist_Use_Right_Window = 1 -< - *'Tlist_Use_SingleClick'* -Tlist_Use_SingleClick~ -By default, when you double click on the tag name using the left mouse -button, the cursor will be positioned at the definition of the tag. You -can set the 'Tlist_Use_SingleClick' variable to 1 to jump to a tag when -you single click on the tag name using the mouse. By default this variable -is set to zero. -> - let Tlist_Use_SingleClick = 1 -< -Due to a bug in Vim, if you set 'Tlist_Use_SingleClick' to 1 and try to resize -the taglist window using the mouse, then Vim will crash. This problem is fixed -in Vim 6.3 and above. In the meantime, instead of resizing the taglist window -using the mouse, you can use normal Vim window resizing commands to resize the -taglist window. - - *'Tlist_WinHeight'* -Tlist_WinHeight~ -The default height of the horizontally split taglist window is 10. This can be -changed by modifying the 'Tlist_WinHeight' variable: -> - let Tlist_WinHeight = 20 -< -The |'winfixheight'| option is set for the taglist window, to maintain the -height of the taglist window, when new Vim windows are opened and existing -windows are closed. - - *'Tlist_WinWidth'* -Tlist_WinWidth~ -The default width of the vertically split taglist window is 30. This can be -changed by modifying the 'Tlist_WinWidth' variable: -> - let Tlist_WinWidth = 20 -< -Note that the value of the |'winwidth'| option setting determines the minimum -width of the current window. If you set the 'Tlist_WinWidth' variable to a -value less than that of the |'winwidth'| option setting, then Vim will use the -value of the |'winwidth'| option. - -When new Vim windows are opened and existing windows are closed, the taglist -plugin will try to maintain the width of the taglist window to the size -specified by the 'Tlist_WinWidth' variable. - -============================================================================== - *taglist-commands* -7. Commands~ - -The taglist plugin provides the following ex-mode commands: - -|:TlistAddFiles| Add multiple files to the taglist. -|:TlistAddFilesRecursive| - Add files recursively to the taglist. -|:TlistClose| Close the taglist window. -|:TlistDebug| Start logging of taglist debug messages. -|:TlistLock| Stop adding new files to the taglist. -|:TlistMessages| Display the logged taglist plugin debug messages. -|:TlistOpen| Open and jump to the taglist window. -|:TlistSessionSave| Save the information about files and tags in the - taglist to a session file. -|:TlistSessionLoad| Load the information about files and tags stored - in a session file to taglist. -|:TlistShowPrototype| Display the prototype of the tag at or before the - specified line number. -|:TlistShowTag| Display the name of the tag defined at or before the - specified line number. -|:TlistHighlightTag| Highlight the current tag in the taglist window. -|:TlistToggle| Open or close (toggle) the taglist window. -|:TlistUndebug| Stop logging of taglist debug messages. -|:TlistUnlock| Start adding new files to the taglist. -|:TlistUpdate| Update the tags for the current buffer. - - *:TlistAddFiles* -:TlistAddFiles {file(s)} [file(s) ...] - Add one or more specified files to the taglist. You can - specify multiple filenames using wildcards. To specify a - file name with space character, you should escape the space - character with a backslash. - Examples: -> - :TlistAddFiles *.c *.cpp - :TlistAddFiles file1.html file2.html -< - If you specify a large number of files, then it will take some - time for the taglist plugin to process all of them. The - specified files will not be edited in a Vim window and will - not be added to the Vim buffer list. - - *:TlistAddFilesRecursive* -:TlistAddFilesRecursive {directory} [ {pattern} ] - Add files matching {pattern} recursively from the specified - {directory} to the taglist. If {pattern} is not specified, - then '*' is assumed. To specify the current directory, use "." - for {directory}. To specify a directory name with space - character, you should escape the space character with a - backslash. - Examples: -> - :TlistAddFilesRecursive myproject *.java - :TlistAddFilesRecursive smallproject -< - If large number of files are present in the specified - directory tree, then it will take some time for the taglist - plugin to process all of them. - - *:TlistClose* -:TlistClose Close the taglist window. This command can be used from any - one of the Vim windows. - - *:TlistDebug* -:TlistDebug [filename] - Start logging of debug messages from the taglist plugin. - If {filename} is specified, then the debug messages are stored - in the specified file. Otherwise, the debug messages are - stored in a script local variable. If the file {filename} is - already present, then it is overwritten. - - *:TlistLock* -:TlistLock - Lock the taglist and don't process new files. After this - command is executed, newly edited files will not be added to - the taglist. - - *:TlistMessages* -:TlistMessages - Display the logged debug messages from the taglist plugin - in a window. This command works only when logging to a - script-local variable. - - *:TlistOpen* -:TlistOpen Open and jump to the taglist window. Creates the taglist - window, if the window is not opened currently. After executing - this command, the cursor is moved to the taglist window. When - the taglist window is opened for the first time, all the files - in the buffer list are processed and the tags defined in them - are displayed in the taglist window. - - *:TlistSessionSave* -:TlistSessionSave {filename} - Saves the information about files and tags in the taglist to - the specified file. This command can be used to save and - restore the taglist contents across Vim sessions. - - *:TlistSessionLoad* -:TlistSessionLoad {filename} - Load the information about files and tags stored in the - specified session file to the taglist. - - *:TlistShowPrototype* -:TlistShowPrototype [filename] [linenumber] - Display the prototype of the tag at or before the specified - line number. If the file name and the line number are not - specified, then the current file name and line number are - used. A tag spans multiple lines starting from the line where - it is defined to the line before the next tag. This command - displays the prototype for the tag for any line number in this - range. - - *:TlistShowTag* -:TlistShowTag [filename] [linenumber] - Display the name of the tag defined at or before the specified - line number. If the file name and the line number are not - specified, then the current file name and line number are - used. A tag spans multiple lines starting from the line where - it is defined to the line before the next tag. This command - displays the tag name for any line number in this range. - - *:TlistHighlightTag* -:TlistHighlightTag - Highlight the current tag in the taglist window. By default, - the taglist plugin periodically updates the taglist window to - highlight the current tag. This command can be used to force - the taglist plugin to highlight the current tag. - - *:TlistToggle* -:TlistToggle Open or close (toggle) the taglist window. Opens the taglist - window, if the window is not opened currently. Closes the - taglist window, if the taglist window is already opened. When - the taglist window is opened for the first time, all the files - in the buffer list are processed and the tags are displayed in - the taglist window. After executing this command, the cursor - is not moved from the current window to the taglist window. - - *:TlistUndebug* -:TlistUndebug - Stop logging of debug messages from the taglist plugin. - - *:TlistUnlock* -:TlistUnlock - Unlock the taglist and start processing newly edited files. - - *:TlistUpdate* -:TlistUpdate Update the tags information for the current buffer. This - command can be used to re-process the current file/buffer and - get the tags information. As the taglist plugin uses the file - saved in the disk (instead of the file displayed in a Vim - buffer), you should save a modified buffer before you update - the taglist. Otherwise the listed tags will not include the - new tags created in the buffer. You can use this command even - when the taglist window is not opened. - -============================================================================== - *taglist-functions* -8. Global functions~ - -The taglist plugin provides several global functions that can be used from -other Vim plugins to interact with the taglist plugin. These functions are -described below. - -|Tlist_Update_File_Tags()| Update the tags for the specified file -|Tlist_Get_Tag_Prototype_By_Line()| Return the prototype of the tag at or - before the specified line number in the - specified file. -|Tlist_Get_Tagname_By_Line()| Return the name of the tag at or - before the specified line number in - the specified file. -|Tlist_Set_App()| Set the name of the application - controlling the taglist window. - - *Tlist_Update_File_Tags()* -Tlist_Update_File_Tags({filename}, {filetype}) - Update the tags for the file {filename}. The second argument - specifies the Vim filetype for the file. If the taglist plugin - has not processed the file previously, then the exuberant - ctags tool is invoked to generate the tags for the file. - - *Tlist_Get_Tag_Prototype_By_Line()* -Tlist_Get_Tag_Prototype_By_Line([{filename}, {linenumber}]) - Return the prototype of the tag at or before the specified - line number in the specified file. If the filename and line - number are not specified, then the current buffer name and the - current line number are used. - - *Tlist_Get_Tagname_By_Line()* -Tlist_Get_Tagname_By_Line([{filename}, {linenumber}]) - Return the name of the tag at or before the specified line - number in the specified file. If the filename and line number - are not specified, then the current buffer name and the - current line number are used. - - *Tlist_Set_App()* -Tlist_Set_App({appname}) - Set the name of the plugin that controls the taglist plugin - window and buffer. This can be used to integrate the taglist - plugin with other Vim plugins. - - For example, the winmanager plugin and the Cream package use - this function and specify the appname as "winmanager" and - "cream" respectively. - - By default, the taglist plugin is a stand-alone plugin and - controls the taglist window and buffer. If the taglist window - is controlled by an external plugin, then the appname should - be set appropriately. - -============================================================================== - *taglist-extend* -9. Extending~ - -The taglist plugin supports all the languages supported by the exuberant ctags -tool, which includes the following languages: Assembly, ASP, Awk, Beta, C, -C++, C#, Cobol, Eiffel, Erlang, Fortran, HTML, Java, Javascript, Lisp, Lua, -Make, Pascal, Perl, PHP, Python, Rexx, Ruby, Scheme, Shell, Slang, SML, Sql, -TCL, Verilog, Vim and Yacc. - -You can extend the taglist plugin to add support for new languages and also -modify the support for the above listed languages. - -You should NOT make modifications to the taglist plugin script file to add -support for new languages. You will lose these changes when you upgrade to the -next version of the taglist plugin. Instead you should follow the below -described instructions to extend the taglist plugin. - -You can extend the taglist plugin by setting variables in the .vimrc or _vimrc -file. The name of these variables depends on the language name and is -described below. - -Modifying support for an existing language~ -To modify the support for an already supported language, you have to set the -tlist_xxx_settings variable in the ~/.vimrc or $HOME/_vimrc file. Replace xxx -with the Vim filetype name for the language file. For example, to modify the -support for the perl language files, you have to set the tlist_perl_settings -variable. To modify the support for java files, you have to set the -tlist_java_settings variable. - -To determine the filetype name used by Vim for a file, use the following -command in the buffer containing the file: - - :set filetype - -The above command will display the Vim filetype for the current buffer. - -The format of the value set in the tlist_xxx_settings variable is - - <language_name>;flag1:name1;flag2:name2;flag3:name3 - -The different fields in the value are separated by the ';' character. - -The first field 'language_name' is the name used by exuberant ctags to refer -to this language file. This name can be different from the file type name used -by Vim. For example, for C++, the language name used by ctags is 'c++' but the -filetype name used by Vim is 'cpp'. To get the list of language names -supported by exuberant ctags, use the following command: - - $ ctags --list-maps=all - -The remaining fields follow the format "flag:name". The sub-field 'flag' is -the language specific flag used by exuberant ctags to generate the -corresponding tags. For example, for the C language, to list only the -functions, the 'f' flag is used. To get the list of flags supported by -exuberant ctags for the various languages use the following command: - - $ ctags --list-kinds=all - -The sub-field 'name' specifies the title text to use for displaying the tags -of a particular type. For example, 'name' can be set to 'functions'. This -field can be set to any text string name. - -For example, to list only the classes and functions defined in a C++ language -file, add the following line to your .vimrc file: - - let tlist_cpp_settings = 'c++;c:class;f:function' - -In the above setting, 'cpp' is the Vim filetype name and 'c++' is the name -used by the exuberant ctags tool. 'c' and 'f' are the flags passed to -exuberant ctags to list C++ classes and functions and 'class' is the title -used for the class tags and 'function' is the title used for the function tags -in the taglist window. - -For example, to display only functions defined in a C file and to use "My -Functions" as the title for the function tags, use - - let tlist_c_settings = 'c;f:My Functions' - -When you set the tlist_xxx_settings variable, you will override the default -setting used by the taglist plugin for the 'xxx' language. You cannot add to -the default options used by the taglist plugin for a particular file type. To -add to the options used by the taglist plugin for a language, copy the option -values from the taglist plugin file to your .vimrc file and modify it. - -Adding support for a new language~ -If you want to add support for a new language to the taglist plugin, you need -to first extend the exuberant ctags tool. For more information about extending -exuberant ctags, visit the following page: - - http://ctags.sourceforge.net/EXTENDING.html - -To add support for a new language, set the tlist_xxx_settings variable in the -~/.vimrc file appropriately as described above. Replace 'xxx' in the variable -name with the Vim filetype name for the new language. - -For example, to extend the taglist plugin to support the latex language, you -can use the following line (assuming, you have already extended exuberant -ctags to support the latex language): - - let tlist_tex_settings='latex;b:bibitem;c:command;l:label' - -With the above line, when you edit files of filetype "tex" in Vim, the taglist -plugin will invoke the exuberant ctags tool passing the "latex" filetype and -the flags b, c and l to generate the tags. The text heading 'bibitem', -'command' and 'label' will be used in the taglist window for the tags which -are generated for the flags b, c and l respectively. - -============================================================================== - *taglist-faq* -10. Frequently Asked Questions~ - -Q. The taglist plugin doesn't work. The taglist window is empty and the tags - defined in a file are not displayed. -A. Are you using Vim version 6.0 and above? The taglist plugin relies on the - features supported by Vim version 6.0 and above. You can use the following - command to get the Vim version: -> - $ vim --version -< - Are you using exuberant ctags version 5.0 and above? The taglist plugin - relies on the features supported by exuberant ctags and will not work with - GNU ctags or the Unix ctags utility. You can use the following command to - determine whether the ctags installed in your system is exuberant ctags: -> - $ ctags --version -< - Is exuberant ctags present in one of the directories in your PATH? If not, - you need to set the Tlist_Ctags_Cmd variable to point to the location of - exuberant ctags. Use the following Vim command to verify that this is setup - correctly: -> - :echo system(Tlist_Ctags_Cmd . ' --version') -< - The above command should display the version information for exuberant - ctags. - - Did you turn on the Vim filetype detection? The taglist plugin relies on - the filetype detected by Vim and passes the filetype to the exuberant ctags - utility to parse the tags. Check the output of the following Vim command: -> - :filetype -< - The output of the above command should contain "filetype detection:ON". - To turn on the filetype detection, add the following line to the .vimrc or - _vimrc file: -> - filetype on -< - Is your version of Vim compiled with the support for the system() function? - The following Vim command should display 1: -> - :echo exists('*system') -< - In some Linux distributions (particularly Suse Linux), the default Vim - installation is built without the support for the system() function. The - taglist plugin uses the system() function to invoke the exuberant ctags - utility. You need to rebuild Vim after enabling the support for the - system() function. If you use the default build options, the system() - function will be supported. - - Do you have the |'shellslash'| option set? You can try disabling the - |'shellslash'| option. When the taglist plugin invokes the exuberant ctags - utility with the path to the file, if the incorrect slashes are used, then - you will see errors. - - Check the shell related Vim options values using the following command: -> - :set shell? shellcmdflag? shellpipe? - :set shellquote? shellredir? shellxquote? -< - If these options are set in your .vimrc or _vimrc file, try removing those - lines. - - Are you using a Unix shell in a MS-Windows environment? For example, - the Unix shell from the MKS-toolkit. Do you have the SHELL environment - set to point to this shell? You can try resetting the SHELL environment - variable. - - If you are using a Unix shell on MS-Windows, you should try to use - exuberant ctags that is compiled for Unix-like environments so that - exuberant ctags will understand path names with forward slash characters. - - Is your filetype supported by the exuberant ctags utility? The file types - supported by the exuberant ctags utility are listed in the ctags help. If a - file type is not supported, you have to extend exuberant ctags. You can use - the following command to list the filetypes supported by exuberant ctags: -> - ctags --list-languages -< - Run the following command from the shell prompt and check whether the tags - defined in your file are listed in the output from exuberant ctags: -> - ctags -f - --format=2 --excmd=pattern --fields=nks <filename> -< - If you see your tags in the output from the above command, then the - exuberant ctags utility is properly parsing your file. - - Do you have the .ctags or _ctags or the ctags.cnf file in your home - directory for specifying default options or for extending exuberant ctags? - If you do have this file, check the options in this file and make sure - these options are not interfering with the operation of the taglist plugin. - - If you are using MS-Windows, check the value of the TEMP and TMP - environment variables. If these environment variables are set to a path - with space characters in the name, then try using the DOS 8.3 short name - for the path or set them to a path without the space characters in the - name. For example, if the temporary directory name is "C:\Documents and - Settings\xyz\Local Settings\Temp", then try setting the TEMP variable to - the following: -> - set TEMP=C:\DOCUMEN~1\xyz\LOCALS~1\Temp -< - If exuberant ctags is installed in a directory with space characters in the - name, then try adding the directory to the PATH environment variable or try - setting the 'Tlist_Ctags_Cmd' variable to the shortest path name to ctags - or try copying the exuberant ctags to a path without space characters in - the name. For example, if exuberant ctags is installed in the directory - "C:\Program Files\Ctags", then try setting the 'Tlist_Ctags_Cmd' variable - as below: -> - let Tlist_Ctags_Cmd='C:\Progra~1\Ctags\ctags.exe' -< - If you are using a cygwin compiled version of exuberant ctags on MS-Windows, - make sure that either you have the cygwin compiled sort utility installed - and available in your PATH or compile exuberant ctags with internal sort - support. Otherwise, when exuberant ctags sorts the tags output by invoking - the sort utility, it may end up invoking the MS-Windows version of - sort.exe, thereby resulting in failure. - -Q. When I try to open the taglist window, I am seeing the following error - message. How do I fix this problem? - - Taglist: Failed to generate tags for /my/path/to/file - ctags: illegal option -- -^@usage: ctags [-BFadtuwvx] [-f tagsfile] file ... - -A. The taglist plugin will work only with the exuberant ctags tool. You - cannot use the GNU ctags or the Unix ctags program with the taglist plugin. - You will see an error message similar to the one shown above, if you try - use a non-exuberant ctags program with Vim. To fix this problem, either add - the exuberant ctags tool location to the PATH environment variable or set - the 'Tlist_Ctags_Cmd' variable. - -Q. A file has more than one tag with the same name. When I select a tag name - from the taglist window, the cursor is positioned at the incorrect tag - location. -A. The taglist plugin uses the search pattern generated by the exuberant ctags - utility to position the cursor at the location of a tag definition. If a - file has more than one tag with the same name and same prototype, then the - search pattern will be the same. In this case, when searching for the tag - pattern, the cursor may be positioned at the incorrect location. - -Q. I have made some modifications to my file and introduced new - functions/classes/variables. I have not yet saved my file. The taglist - plugin is not displaying the new tags when I update the taglist window. -A. The exuberant ctags utility will process only files that are present in the - disk. To list the tags defined in a file, you have to save the file and - then update the taglist window. - -Q. I have created a ctags file using the exuberant ctags utility for my source - tree. How do I configure the taglist plugin to use this tags file? -A. The taglist plugin doesn't use a tags file stored in disk. For every opened - file, the taglist plugin invokes the exuberant ctags utility to get the - list of tags dynamically. The Vim system() function is used to invoke - exuberant ctags and get the ctags output. This function internally uses a - temporary file to store the output. This file is deleted after the output - from the command is read. So you will never see the file that contains the - output of exuberant ctags. - -Q. When I set the |'updatetime'| option to a low value (less than 1000) and if - I keep pressing a key with the taglist window open, the current buffer - contents are changed. Why is this? -A. The taglist plugin uses the |CursorHold| autocmd to highlight the current - tag. The CursorHold autocmd triggers for every |'updatetime'| milliseconds. - If the |'updatetime'| option is set to a low value, then the CursorHold - autocmd will be triggered frequently. As the taglist plugin changes - the focus to the taglist window to highlight the current tag, this could - interfere with the key movement resulting in changing the contents of - the current buffer. The workaround for this problem is to not set the - |'updatetime'| option to a low value. - -============================================================================== - *taglist-license* -11. License~ -Permission is hereby granted to use and distribute the taglist plugin, with or -without modifications, provided that this copyright notice is copied with it. -Like anything else that's free, taglist.vim is provided *as is* and comes with -no warranty of any kind, either expressed or implied. In no event will the -copyright holder be liable for any damamges resulting from the use of this -software. - -============================================================================== - *taglist-todo* -12. Todo~ - -1. Group tags according to the scope and display them. For example, - group all the tags belonging to a C++/Java class -2. Support for displaying tags in a modified (not-yet-saved) file. -3. Automatically open the taglist window only for selected filetypes. - For other filetypes, close the taglist window. -4. When using the shell from the MKS toolkit, the taglist plugin - doesn't work. -5. The taglist plugin doesn't work with files edited remotely using the - netrw plugin. The exuberant ctags utility cannot process files over - scp/rcp/ftp, etc. - -============================================================================== - -vim:tw=78:ts=8:noet:ft=help: diff --git a/vim/doc/tags b/vim/doc/tags index 7c855b7..6b4874e 100644 --- a/vim/doc/tags +++ b/vim/doc/tags @@ -1,85 +1,3 @@ -'NERDAllowAnyVisualDelims' NERD_commenter.txt /*'NERDAllowAnyVisualDelims'* -'NERDBlockComIgnoreEmpty' NERD_commenter.txt /*'NERDBlockComIgnoreEmpty'* -'NERDChristmasTree' NERD_tree.txt /*'NERDChristmasTree'* -'NERDCommentWholeLinesInVMode' NERD_commenter.txt /*'NERDCommentWholeLinesInVMode'* -'NERDCompactSexyComs' NERD_commenter.txt /*'NERDCompactSexyComs'* -'NERDCreateDefaultMappings' NERD_commenter.txt /*'NERDCreateDefaultMappings'* -'NERDDefaultNesting' NERD_commenter.txt /*'NERDDefaultNesting'* -'NERDLPlace' NERD_commenter.txt /*'NERDLPlace'* -'NERDMenuMode' NERD_commenter.txt /*'NERDMenuMode'* -'NERDRPlace' NERD_commenter.txt /*'NERDRPlace'* -'NERDRemoveAltComs' NERD_commenter.txt /*'NERDRemoveAltComs'* -'NERDRemoveExtraSpaces' NERD_commenter.txt /*'NERDRemoveExtraSpaces'* -'NERDSpaceDelims' NERD_commenter.txt /*'NERDSpaceDelims'* -'NERDTreeAutoCenter' NERD_tree.txt /*'NERDTreeAutoCenter'* -'NERDTreeAutoCenterThreshold' NERD_tree.txt /*'NERDTreeAutoCenterThreshold'* -'NERDTreeBookmarksFile' NERD_tree.txt /*'NERDTreeBookmarksFile'* -'NERDTreeCaseSensitiveSort' NERD_tree.txt /*'NERDTreeCaseSensitiveSort'* -'NERDTreeChDirMode' NERD_tree.txt /*'NERDTreeChDirMode'* -'NERDTreeHighlightCursorline' NERD_tree.txt /*'NERDTreeHighlightCursorline'* -'NERDTreeHijackNetrw' NERD_tree.txt /*'NERDTreeHijackNetrw'* -'NERDTreeIgnore' NERD_tree.txt /*'NERDTreeIgnore'* -'NERDTreeMouseMode' NERD_tree.txt /*'NERDTreeMouseMode'* -'NERDTreeQuitOnOpen' NERD_tree.txt /*'NERDTreeQuitOnOpen'* -'NERDTreeShowBookmarks' NERD_tree.txt /*'NERDTreeShowBookmarks'* -'NERDTreeShowFiles' NERD_tree.txt /*'NERDTreeShowFiles'* -'NERDTreeShowHidden' NERD_tree.txt /*'NERDTreeShowHidden'* -'NERDTreeShowLineNumbers' NERD_tree.txt /*'NERDTreeShowLineNumbers'* -'NERDTreeSortOrder' NERD_tree.txt /*'NERDTreeSortOrder'* -'NERDTreeStatusline' NERD_tree.txt /*'NERDTreeStatusline'* -'NERDTreeWinPos' NERD_tree.txt /*'NERDTreeWinPos'* -'NERDTreeWinSize' NERD_tree.txt /*'NERDTreeWinSize'* -'NERDUsePlaceHolders' NERD_commenter.txt /*'NERDUsePlaceHolders'* -'Tlist_Auto_Highlight_Tag' taglist.txt /*'Tlist_Auto_Highlight_Tag'* -'Tlist_Auto_Open' taglist.txt /*'Tlist_Auto_Open'* -'Tlist_Auto_Update' taglist.txt /*'Tlist_Auto_Update'* -'Tlist_Close_On_Select' taglist.txt /*'Tlist_Close_On_Select'* -'Tlist_Compact_Format' taglist.txt /*'Tlist_Compact_Format'* -'Tlist_Ctags_Cmd' taglist.txt /*'Tlist_Ctags_Cmd'* -'Tlist_Display_Prototype' taglist.txt /*'Tlist_Display_Prototype'* -'Tlist_Display_Tag_Scope' taglist.txt /*'Tlist_Display_Tag_Scope'* -'Tlist_Enable_Fold_Column' taglist.txt /*'Tlist_Enable_Fold_Column'* -'Tlist_Exit_OnlyWindow' taglist.txt /*'Tlist_Exit_OnlyWindow'* -'Tlist_File_Fold_Auto_Close' taglist.txt /*'Tlist_File_Fold_Auto_Close'* -'Tlist_GainFocus_On_ToggleOpen' taglist.txt /*'Tlist_GainFocus_On_ToggleOpen'* -'Tlist_Highlight_Tag_On_BufEnter' taglist.txt /*'Tlist_Highlight_Tag_On_BufEnter'* -'Tlist_Inc_Winwidth' taglist.txt /*'Tlist_Inc_Winwidth'* -'Tlist_Max_Submenu_Items' taglist.txt /*'Tlist_Max_Submenu_Items'* -'Tlist_Max_Tag_Length' taglist.txt /*'Tlist_Max_Tag_Length'* -'Tlist_Process_File_Always' taglist.txt /*'Tlist_Process_File_Always'* -'Tlist_Show_Menu' taglist.txt /*'Tlist_Show_Menu'* -'Tlist_Show_One_File' taglist.txt /*'Tlist_Show_One_File'* -'Tlist_Sort_Type' taglist.txt /*'Tlist_Sort_Type'* -'Tlist_Use_Horiz_Window' taglist.txt /*'Tlist_Use_Horiz_Window'* -'Tlist_Use_Right_Window' taglist.txt /*'Tlist_Use_Right_Window'* -'Tlist_Use_SingleClick' taglist.txt /*'Tlist_Use_SingleClick'* -'Tlist_WinHeight' taglist.txt /*'Tlist_WinHeight'* -'Tlist_WinWidth' taglist.txt /*'Tlist_WinWidth'* -'b:delimitMate_autoclose' delimitMate.txt /*'b:delimitMate_autoclose'* -'b:delimitMate_balance_matchpairs' delimitMate.txt /*'b:delimitMate_balance_matchpairs'* -'b:delimitMate_expand_cr' delimitMate.txt /*'b:delimitMate_expand_cr'* -'b:delimitMate_expand_space' delimitMate.txt /*'b:delimitMate_expand_space'* -'b:delimitMate_matchpairs' delimitMate.txt /*'b:delimitMate_matchpairs'* -'b:delimitMate_nesting_quotes' delimitMate.txt /*'b:delimitMate_nesting_quotes'* -'b:delimitMate_quotes' delimitMate.txt /*'b:delimitMate_quotes'* -'b:delimitMate_smart_matchpairs' delimitMate.txt /*'b:delimitMate_smart_matchpairs'* -'b:delimitMate_smart_quotes' delimitMate.txt /*'b:delimitMate_smart_quotes'* -'b:loaded_delimitMate' delimitMate.txt /*'b:loaded_delimitMate'* -'delimitMate_apostrophes' delimitMate.txt /*'delimitMate_apostrophes'* -'delimitMate_autoclose' delimitMate.txt /*'delimitMate_autoclose'* -'delimitMate_balance_matchpairs' delimitMate.txt /*'delimitMate_balance_matchpairs'* -'delimitMate_excluded_ft' delimitMate.txt /*'delimitMate_excluded_ft'* -'delimitMate_excluded_regions' delimitMate.txt /*'delimitMate_excluded_regions'* -'delimitMate_expand_cr' delimitMate.txt /*'delimitMate_expand_cr'* -'delimitMate_expand_space' delimitMate.txt /*'delimitMate_expand_space'* -'delimitMate_matchpairs' delimitMate.txt /*'delimitMate_matchpairs'* -'delimitMate_nesting_quotes' delimitMate.txt /*'delimitMate_nesting_quotes'* -'delimitMate_quotes' delimitMate.txt /*'delimitMate_quotes'* -'delimitMate_smart_matchpairs' delimitMate.txt /*'delimitMate_smart_matchpairs'* -'delimitMate_smart_quotes' delimitMate.txt /*'delimitMate_smart_quotes'* -'loaded_delimitMate' delimitMate.txt /*'loaded_delimitMate'* -'loaded_nerd_comments' NERD_commenter.txt /*'loaded_nerd_comments'* -'loaded_nerd_tree' NERD_tree.txt /*'loaded_nerd_tree'* 'showmarks_enable' showmarks.txt /*'showmarks_enable'* 'showmarks_hlline_lower' showmarks.txt /*'showmarks_hlline_lower'* 'showmarks_hlline_other' showmarks.txt /*'showmarks_hlline_other'* @@ -89,7 +7,6 @@ 'showmarks_include' showmarks.txt /*'showmarks_include'* 'showmarks_textother' showmarks.txt /*'showmarks_textother'* 'showmarks_textupper' showmarks.txt /*'showmarks_textupper'* -'snippets' snipMate.txt /*'snippets'* 'solarized_bold' solarized.txt /*'solarized_bold'* 'solarized_contrast' solarized.txt /*'solarized_contrast'* 'solarized_degrade' solarized.txt /*'solarized_degrade'* @@ -100,306 +17,15 @@ 'solarized_termtrans' solarized.txt /*'solarized_termtrans'* 'solarized_underline' solarized.txt /*'solarized_underline'* 'solarized_visibility' solarized.txt /*'solarized_visibility'* -'syntastic_auto_jump' syntastic.txt /*'syntastic_auto_jump'* -'syntastic_auto_loc_list' syntastic.txt /*'syntastic_auto_loc_list'* -'syntastic_check_on_open' syntastic.txt /*'syntastic_check_on_open'* -'syntastic_echo_current_error' syntastic.txt /*'syntastic_echo_current_error'* -'syntastic_enable_balloons' syntastic.txt /*'syntastic_enable_balloons'* -'syntastic_enable_highlighting' syntastic.txt /*'syntastic_enable_highlighting'* -'syntastic_enable_signs' syntastic.txt /*'syntastic_enable_signs'* -'syntastic_loc_list_height' syntastic.txt /*'syntastic_loc_list_height'* -'syntastic_mode_map' syntastic.txt /*'syntastic_mode_map'* -'syntastic_quiet_warnings' syntastic.txt /*'syntastic_quiet_warnings'* -'syntastic_stl_format' syntastic.txt /*'syntastic_stl_format'* -.snippet snipMate.txt /*.snippet* -.snippets snipMate.txt /*.snippets* -:Ack ack.txt /*:Ack* -:AckAdd ack.txt /*:AckAdd* -:AckFile ack.txt /*:AckFile* -:AckFromSearch ack.txt /*:AckFromSearch* :CoffeeCompile coffee-script.txt /*:CoffeeCompile* :CoffeeMake coffee-script.txt /*:CoffeeMake* :CoffeeMake! coffee-script.txt /*:CoffeeMake!* :CoffeeRun coffee-script.txt /*:CoffeeRun* -:CommandT command-t.txt /*:CommandT* -:CommandTBuffer command-t.txt /*:CommandTBuffer* -:CommandTFlush command-t.txt /*:CommandTFlush* -:CommandTJumps command-t.txt /*:CommandTJumps* -:DelimitMateReload delimitMate.txt /*:DelimitMateReload* -:DelimitMateSwitch delimitMate.txt /*:DelimitMateSwitch* -:DelimitMateTest delimitMate.txt /*:DelimitMateTest* -:Errors syntastic.txt /*:Errors* -:Gist gist-vim.txt /*:Gist* -:LAck ack.txt /*:LAck* -:LAckAdd ack.txt /*:LAckAdd* -:LuaInspect luainspect.txt /*:LuaInspect* -:LuaInspectToggle luainspect.txt /*:LuaInspectToggle* -:NERDTree NERD_tree.txt /*:NERDTree* -:NERDTreeClose NERD_tree.txt /*:NERDTreeClose* -:NERDTreeFind NERD_tree.txt /*:NERDTreeFind* -:NERDTreeFromBookmark NERD_tree.txt /*:NERDTreeFromBookmark* -:NERDTreeMirror NERD_tree.txt /*:NERDTreeMirror* -:NERDTreeToggle NERD_tree.txt /*:NERDTreeToggle* -:SyntasticCheck syntastic.txt /*:SyntasticCheck* -:SyntasticErrors syntastic.txt /*:SyntasticErrors* -:SyntasticToggleMode syntastic.txt /*:SyntasticToggleMode* -:TlistAddFiles taglist.txt /*:TlistAddFiles* -:TlistAddFilesRecursive taglist.txt /*:TlistAddFilesRecursive* -:TlistClose taglist.txt /*:TlistClose* -:TlistDebug taglist.txt /*:TlistDebug* -:TlistHighlightTag taglist.txt /*:TlistHighlightTag* -:TlistLock taglist.txt /*:TlistLock* -:TlistMessages taglist.txt /*:TlistMessages* -:TlistOpen taglist.txt /*:TlistOpen* -:TlistSessionLoad taglist.txt /*:TlistSessionLoad* -:TlistSessionSave taglist.txt /*:TlistSessionSave* -:TlistShowPrototype taglist.txt /*:TlistShowPrototype* -:TlistShowTag taglist.txt /*:TlistShowTag* -:TlistToggle taglist.txt /*:TlistToggle* -:TlistUndebug taglist.txt /*:TlistUndebug* -:TlistUnlock taglist.txt /*:TlistUnlock* -:TlistUpdate taglist.txt /*:TlistUpdate* -Align-copyright Align.txt /*Align-copyright* -ConqueTerm conque_term.txt /*ConqueTerm* -ExtractSnips() snipMate.txt /*ExtractSnips()* -ExtractSnipsFile() snipMate.txt /*ExtractSnipsFile()* -Filename() snipMate.txt /*Filename()* -Gist.vim gist-vim.txt /*Gist.vim* -NERDComAbout NERD_commenter.txt /*NERDComAbout* -NERDComAlignedComment NERD_commenter.txt /*NERDComAlignedComment* -NERDComAltDelim NERD_commenter.txt /*NERDComAltDelim* -NERDComAppendComment NERD_commenter.txt /*NERDComAppendComment* -NERDComChangelog NERD_commenter.txt /*NERDComChangelog* -NERDComComment NERD_commenter.txt /*NERDComComment* -NERDComCredits NERD_commenter.txt /*NERDComCredits* -NERDComDefaultDelims NERD_commenter.txt /*NERDComDefaultDelims* -NERDComEOLComment NERD_commenter.txt /*NERDComEOLComment* -NERDComFunctionality NERD_commenter.txt /*NERDComFunctionality* -NERDComFunctionalityDetails NERD_commenter.txt /*NERDComFunctionalityDetails* -NERDComFunctionalitySummary NERD_commenter.txt /*NERDComFunctionalitySummary* -NERDComHeuristics NERD_commenter.txt /*NERDComHeuristics* -NERDComInsertComment NERD_commenter.txt /*NERDComInsertComment* -NERDComInstallation NERD_commenter.txt /*NERDComInstallation* -NERDComInvertComment NERD_commenter.txt /*NERDComInvertComment* -NERDComIssues NERD_commenter.txt /*NERDComIssues* -NERDComLicense NERD_commenter.txt /*NERDComLicense* -NERDComMappings NERD_commenter.txt /*NERDComMappings* -NERDComMinimalComment NERD_commenter.txt /*NERDComMinimalComment* -NERDComNERDComment NERD_commenter.txt /*NERDComNERDComment* -NERDComNestedComment NERD_commenter.txt /*NERDComNestedComment* -NERDComNesting NERD_commenter.txt /*NERDComNesting* -NERDComOptions NERD_commenter.txt /*NERDComOptions* -NERDComOptionsDetails NERD_commenter.txt /*NERDComOptionsDetails* -NERDComOptionsSummary NERD_commenter.txt /*NERDComOptionsSummary* -NERDComSexyComment NERD_commenter.txt /*NERDComSexyComment* -NERDComSexyComments NERD_commenter.txt /*NERDComSexyComments* -NERDComToggleComment NERD_commenter.txt /*NERDComToggleComment* -NERDComUncommentLine NERD_commenter.txt /*NERDComUncommentLine* -NERDComYankComment NERD_commenter.txt /*NERDComYankComment* -NERDCommenter NERD_commenter.txt /*NERDCommenter* -NERDCommenterContents NERD_commenter.txt /*NERDCommenterContents* -NERDTree NERD_tree.txt /*NERDTree* -NERDTree-? NERD_tree.txt /*NERDTree-?* -NERDTree-A NERD_tree.txt /*NERDTree-A* -NERDTree-B NERD_tree.txt /*NERDTree-B* -NERDTree-C NERD_tree.txt /*NERDTree-C* -NERDTree-C-J NERD_tree.txt /*NERDTree-C-J* -NERDTree-C-K NERD_tree.txt /*NERDTree-C-K* -NERDTree-D NERD_tree.txt /*NERDTree-D* -NERDTree-F NERD_tree.txt /*NERDTree-F* -NERDTree-I NERD_tree.txt /*NERDTree-I* -NERDTree-J NERD_tree.txt /*NERDTree-J* -NERDTree-K NERD_tree.txt /*NERDTree-K* -NERDTree-O NERD_tree.txt /*NERDTree-O* -NERDTree-P NERD_tree.txt /*NERDTree-P* -NERDTree-R NERD_tree.txt /*NERDTree-R* -NERDTree-T NERD_tree.txt /*NERDTree-T* -NERDTree-U NERD_tree.txt /*NERDTree-U* -NERDTree-X NERD_tree.txt /*NERDTree-X* -NERDTree-cd NERD_tree.txt /*NERDTree-cd* -NERDTree-contents NERD_tree.txt /*NERDTree-contents* -NERDTree-e NERD_tree.txt /*NERDTree-e* -NERDTree-f NERD_tree.txt /*NERDTree-f* -NERDTree-gi NERD_tree.txt /*NERDTree-gi* -NERDTree-go NERD_tree.txt /*NERDTree-go* -NERDTree-gs NERD_tree.txt /*NERDTree-gs* -NERDTree-i NERD_tree.txt /*NERDTree-i* -NERDTree-m NERD_tree.txt /*NERDTree-m* -NERDTree-o NERD_tree.txt /*NERDTree-o* -NERDTree-p NERD_tree.txt /*NERDTree-p* -NERDTree-q NERD_tree.txt /*NERDTree-q* -NERDTree-r NERD_tree.txt /*NERDTree-r* -NERDTree-s NERD_tree.txt /*NERDTree-s* -NERDTree-t NERD_tree.txt /*NERDTree-t* -NERDTree-u NERD_tree.txt /*NERDTree-u* -NERDTree-x NERD_tree.txt /*NERDTree-x* -NERDTreeAPI NERD_tree.txt /*NERDTreeAPI* -NERDTreeAbout NERD_tree.txt /*NERDTreeAbout* -NERDTreeAddKeyMap() NERD_tree.txt /*NERDTreeAddKeyMap()* -NERDTreeAddMenuItem() NERD_tree.txt /*NERDTreeAddMenuItem()* -NERDTreeAddMenuSeparator() NERD_tree.txt /*NERDTreeAddMenuSeparator()* -NERDTreeAddSubmenu() NERD_tree.txt /*NERDTreeAddSubmenu()* -NERDTreeBookmarkCommands NERD_tree.txt /*NERDTreeBookmarkCommands* -NERDTreeBookmarkTable NERD_tree.txt /*NERDTreeBookmarkTable* -NERDTreeBookmarks NERD_tree.txt /*NERDTreeBookmarks* -NERDTreeChangelog NERD_tree.txt /*NERDTreeChangelog* -NERDTreeCredits NERD_tree.txt /*NERDTreeCredits* -NERDTreeFunctionality NERD_tree.txt /*NERDTreeFunctionality* -NERDTreeGlobalCommands NERD_tree.txt /*NERDTreeGlobalCommands* -NERDTreeInvalidBookmarks NERD_tree.txt /*NERDTreeInvalidBookmarks* -NERDTreeKeymapAPI NERD_tree.txt /*NERDTreeKeymapAPI* -NERDTreeLicense NERD_tree.txt /*NERDTreeLicense* -NERDTreeMappings NERD_tree.txt /*NERDTreeMappings* -NERDTreeMenu NERD_tree.txt /*NERDTreeMenu* -NERDTreeMenuAPI NERD_tree.txt /*NERDTreeMenuAPI* -NERDTreeOptionDetails NERD_tree.txt /*NERDTreeOptionDetails* -NERDTreeOptionSummary NERD_tree.txt /*NERDTreeOptionSummary* -NERDTreeOptions NERD_tree.txt /*NERDTreeOptions* -NERDTreeRender() NERD_tree.txt /*NERDTreeRender()* -NERD_commenter.txt NERD_commenter.txt /*NERD_commenter.txt* -NERD_tree.txt NERD_tree.txt /*NERD_tree.txt* -ReloadAllSnippets() snipMate.txt /*ReloadAllSnippets()* -ReloadSnippets() snipMate.txt /*ReloadSnippets()* -ResetAllSnippets() snipMate.txt /*ResetAllSnippets()* -ResetSnippets() snipMate.txt /*ResetSnippets()* ShowMarksClearAll showmarks.txt /*ShowMarksClearAll* ShowMarksClearMark showmarks.txt /*ShowMarksClearMark* ShowMarksOn showmarks.txt /*ShowMarksOn* ShowMarksPlaceMark showmarks.txt /*ShowMarksPlaceMark* ShowMarksToggle showmarks.txt /*ShowMarksToggle* -SyntasticMake() syntastic.txt /*SyntasticMake()* -Tlist_Get_Tag_Prototype_By_Line() taglist.txt /*Tlist_Get_Tag_Prototype_By_Line()* -Tlist_Get_Tagname_By_Line() taglist.txt /*Tlist_Get_Tagname_By_Line()* -Tlist_Set_App() taglist.txt /*Tlist_Set_App()* -Tlist_Update_File_Tags() taglist.txt /*Tlist_Update_File_Tags()* -ZoomWin.txt ZoomWin.txt /*ZoomWin.txt* -[<Space> unimpaired.txt /*[<Space>* -[A unimpaired.txt /*[A* -[B unimpaired.txt /*[B* -[L unimpaired.txt /*[L* -[Q unimpaired.txt /*[Q* -[T unimpaired.txt /*[T* -[a unimpaired.txt /*[a* -[b unimpaired.txt /*[b* -[e unimpaired.txt /*[e* -[l unimpaired.txt /*[l* -[o unimpaired.txt /*[o* -[q unimpaired.txt /*[q* -[t unimpaired.txt /*[t* -[u unimpaired.txt /*[u* -[uu unimpaired.txt /*[uu* -[x unimpaired.txt /*[x* -[xx unimpaired.txt /*[xx* -[y unimpaired.txt /*[y* -[yy unimpaired.txt /*[yy* -]<Space> unimpaired.txt /*]<Space>* -]A unimpaired.txt /*]A* -]B unimpaired.txt /*]B* -]L unimpaired.txt /*]L* -]Q unimpaired.txt /*]Q* -]T unimpaired.txt /*]T* -]a unimpaired.txt /*]a* -]b unimpaired.txt /*]b* -]e unimpaired.txt /*]e* -]l unimpaired.txt /*]l* -]o unimpaired.txt /*]o* -]q unimpaired.txt /*]q* -]t unimpaired.txt /*]t* -]u unimpaired.txt /*]u* -]uu unimpaired.txt /*]uu* -]x unimpaired.txt /*]x* -]xx unimpaired.txt /*]xx* -]y unimpaired.txt /*]y* -]yy unimpaired.txt /*]yy* -aI indent-object.txt /*aI* -ack ack.txt /*ack* -ack-author ack.txt /*ack-author* -ack.txt ack.txt /*ack.txt* -ai indent-object.txt /*ai* -align Align.txt /*align* -align-align Align.txt /*align-align* -align-codepoint Align.txt /*align-codepoint* -align-command Align.txt /*align-command* -align-commands Align.txt /*align-commands* -align-concept Align.txt /*align-concept* -align-concepts Align.txt /*align-concepts* -align-contents Align.txt /*align-contents* -align-control Align.txt /*align-control* -align-history Align.txt /*align-history* -align-manual Align.txt /*align-manual* -align-maps Align.txt /*align-maps* -align-multibyte Align.txt /*align-multibyte* -align-option Align.txt /*align-option* -align-options Align.txt /*align-options* -align-strlen Align.txt /*align-strlen* -align-usage Align.txt /*align-usage* -align-userguide Align.txt /*align-userguide* -align-utf Align.txt /*align-utf* -align-utf8 Align.txt /*align-utf8* -align.txt Align.txt /*align.txt* -alignctrl Align.txt /*alignctrl* -alignctrl- Align.txt /*alignctrl-* -alignctrl-+ Align.txt /*alignctrl-+* -alignctrl-- Align.txt /*alignctrl--* -alignctrl-: Align.txt /*alignctrl-:* -alignctrl-< Align.txt /*alignctrl-<* -alignctrl-= Align.txt /*alignctrl-=* -alignctrl-> Align.txt /*alignctrl->* -alignctrl-C Align.txt /*alignctrl-C* -alignctrl-I Align.txt /*alignctrl-I* -alignctrl-P Align.txt /*alignctrl-P* -alignctrl-W Align.txt /*alignctrl-W* -alignctrl-c Align.txt /*alignctrl-c* -alignctrl-g Align.txt /*alignctrl-g* -alignctrl-l Align.txt /*alignctrl-l* -alignctrl-m Align.txt /*alignctrl-m* -alignctrl-no-option Align.txt /*alignctrl-no-option* -alignctrl-p Align.txt /*alignctrl-p* -alignctrl-r Align.txt /*alignctrl-r* -alignctrl-separators Align.txt /*alignctrl-separators* -alignctrl-settings Align.txt /*alignctrl-settings* -alignctrl-v Align.txt /*alignctrl-v* -alignctrl-w Align.txt /*alignctrl-w* -alignman Align.txt /*alignman* -alignmanual Align.txt /*alignmanual* -alignmap-Htd Align.txt /*alignmap-Htd* -alignmap-T= Align.txt /*alignmap-T=* -alignmap-Tsp Align.txt /*alignmap-Tsp* -alignmap-a( Align.txt /*alignmap-a(* -alignmap-a, Align.txt /*alignmap-a,* -alignmap-a< Align.txt /*alignmap-a<* -alignmap-a= Align.txt /*alignmap-a=* -alignmap-a? Align.txt /*alignmap-a?* -alignmap-abox Align.txt /*alignmap-abox* -alignmap-acom Align.txt /*alignmap-acom* -alignmap-adcom Align.txt /*alignmap-adcom* -alignmap-adec Align.txt /*alignmap-adec* -alignmap-adef Align.txt /*alignmap-adef* -alignmap-afnc Align.txt /*alignmap-afnc* -alignmap-anum Align.txt /*alignmap-anum* -alignmap-aocom Align.txt /*alignmap-aocom* -alignmap-ascom Align.txt /*alignmap-ascom* -alignmap-history Align.txt /*alignmap-history* -alignmap-m= Align.txt /*alignmap-m=* -alignmap-t# Align.txt /*alignmap-t#* -alignmap-t, Align.txt /*alignmap-t,* -alignmap-t: Align.txt /*alignmap-t:* -alignmap-t; Align.txt /*alignmap-t;* -alignmap-t< Align.txt /*alignmap-t<* -alignmap-t= Align.txt /*alignmap-t=* -alignmap-t? Align.txt /*alignmap-t?* -alignmap-tab Align.txt /*alignmap-tab* -alignmap-tml Align.txt /*alignmap-tml* -alignmap-ts, Align.txt /*alignmap-ts,* -alignmap-ts: Align.txt /*alignmap-ts:* -alignmap-ts< Align.txt /*alignmap-ts<* -alignmap-ts= Align.txt /*alignmap-ts=* -alignmap-tsp Align.txt /*alignmap-tsp* -alignmap-tsq Align.txt /*alignmap-tsq* -alignmap-tt Align.txt /*alignmap-tt* -alignmap-t~ Align.txt /*alignmap-t~* -alignmaps Align.txt /*alignmaps* -alignusage Align.txt /*alignusage* before solarized.txt /*before* coffee-script coffee-script.txt /*coffee-script* coffee-script-author coffee-script.txt /*coffee-script-author* @@ -409,331 +35,9 @@ coffee-script-introduction coffee-script.txt /*coffee-script-introduction* coffee-script-license coffee-script.txt /*coffee-script-license* coffee-script-settings coffee-script.txt /*coffee-script-settings* coffee-script.txt coffee-script.txt /*coffee-script.txt* -command-t command-t.txt /*command-t* -command-t-authors command-t.txt /*command-t-authors* -command-t-commands command-t.txt /*command-t-commands* -command-t-contents command-t.txt /*command-t-contents* -command-t-donations command-t.txt /*command-t-donations* -command-t-history command-t.txt /*command-t-history* -command-t-installation command-t.txt /*command-t-installation* -command-t-intro command-t.txt /*command-t-intro* -command-t-license command-t.txt /*command-t-license* -command-t-mappings command-t.txt /*command-t-mappings* -command-t-options command-t.txt /*command-t-options* -command-t-pathogen command-t.txt /*command-t-pathogen* -command-t-requirements command-t.txt /*command-t-requirements* -command-t-trouble-shooting command-t.txt /*command-t-trouble-shooting* -command-t-usage command-t.txt /*command-t-usage* -command-t-website command-t.txt /*command-t-website* -command-t-wildignore command-t.txt /*command-t-wildignore* -command-t.txt command-t.txt /*command-t.txt* -config/rails.vim rails.txt /*config\/rails.vim* -conque_term-bugs conque_term.txt /*conque_term-bugs* -conque_term-changelog conque_term.txt /*conque_term-changelog* -conque_term-contribute conque_term.txt /*conque_term-contribute* -conque_term-requirements conque_term.txt /*conque_term-requirements* -conque_term-settings conque_term.txt /*conque_term-settings* -conque_term-todo conque_term.txt /*conque_term-todo* -conque_term-usage conque_term.txt /*conque_term-usage* -cs surround.txt /*cs* -delimitMate delimitMate.txt /*delimitMate* -delimitMate#JumpAny() delimitMate.txt /*delimitMate#JumpAny()* -delimitMate#ShouldJump() delimitMate.txt /*delimitMate#ShouldJump()* -delimitMate#WithinEmptyPair() delimitMate.txt /*delimitMate#WithinEmptyPair()* -delimitMate-contents delimitMate.txt /*delimitMate-contents* -delimitMate.txt delimitMate.txt /*delimitMate.txt* -delimitMateAutoClose delimitMate.txt /*delimitMateAutoClose* -delimitMateBackspace delimitMate.txt /*delimitMateBackspace* -delimitMateBalance delimitMate.txt /*delimitMateBalance* -delimitMateCommands delimitMate.txt /*delimitMateCommands* -delimitMateCredits delimitMate.txt /*delimitMateCredits* -delimitMateExpansion delimitMate.txt /*delimitMateExpansion* -delimitMateFileType delimitMate.txt /*delimitMateFileType* -delimitMateFunctionality delimitMate.txt /*delimitMateFunctionality* -delimitMateFunctions delimitMate.txt /*delimitMateFunctions* -delimitMateHistory delimitMate.txt /*delimitMateHistory* -delimitMateIntro delimitMate.txt /*delimitMateIntro* -delimitMateMaintainer delimitMate.txt /*delimitMateMaintainer* -delimitMateMappings delimitMate.txt /*delimitMateMappings* -delimitMateOptionDetails delimitMate.txt /*delimitMateOptionDetails* -delimitMateOptionSummary delimitMate.txt /*delimitMateOptionSummary* -delimitMateOptions delimitMate.txt /*delimitMateOptions* -delimitMateSmartMatchpairs delimitMate.txt /*delimitMateSmartMatchpairs* -delimitMateSmartQuotes delimitMate.txt /*delimitMateSmartQuotes* -delimitMateSyntax delimitMate.txt /*delimitMateSyntax* -delimitMateTodo delimitMate.txt /*delimitMateTodo* -ds surround.txt /*ds* ft-coffee-script-syntax coffee-script.txt /*ft-coffee-script-syntax* ft-gitcommit-plugin ft-gitcommit-plugin.txt /*ft-gitcommit-plugin* -fugitive fugitive.txt /*fugitive* -fugitive#statusline() fugitive.txt /*fugitive#statusline()* -fugitive-:Gblame fugitive.txt /*fugitive-:Gblame* -fugitive-:Gbrowse fugitive.txt /*fugitive-:Gbrowse* -fugitive-:Gcd fugitive.txt /*fugitive-:Gcd* -fugitive-:Gcommit fugitive.txt /*fugitive-:Gcommit* -fugitive-:Gdiff fugitive.txt /*fugitive-:Gdiff* -fugitive-:Ge fugitive.txt /*fugitive-:Ge* -fugitive-:Gedit fugitive.txt /*fugitive-:Gedit* -fugitive-:Ggrep fugitive.txt /*fugitive-:Ggrep* -fugitive-:Git fugitive.txt /*fugitive-:Git* -fugitive-:Git! fugitive.txt /*fugitive-:Git!* -fugitive-:Glcd fugitive.txt /*fugitive-:Glcd* -fugitive-:Glog fugitive.txt /*fugitive-:Glog* -fugitive-:Gmove fugitive.txt /*fugitive-:Gmove* -fugitive-:Gpedit fugitive.txt /*fugitive-:Gpedit* -fugitive-:Gpedit! fugitive.txt /*fugitive-:Gpedit!* -fugitive-:Gread fugitive.txt /*fugitive-:Gread* -fugitive-:Gread! fugitive.txt /*fugitive-:Gread!* -fugitive-:Gremove fugitive.txt /*fugitive-:Gremove* -fugitive-:Gsdiff fugitive.txt /*fugitive-:Gsdiff* -fugitive-:Gsplit fugitive.txt /*fugitive-:Gsplit* -fugitive-:Gsplit! fugitive.txt /*fugitive-:Gsplit!* -fugitive-:Gstatus fugitive.txt /*fugitive-:Gstatus* -fugitive-:Gtabedit fugitive.txt /*fugitive-:Gtabedit* -fugitive-:Gtabedit! fugitive.txt /*fugitive-:Gtabedit!* -fugitive-:Gvdiff fugitive.txt /*fugitive-:Gvdiff* -fugitive-:Gvsplit fugitive.txt /*fugitive-:Gvsplit* -fugitive-:Gvsplit! fugitive.txt /*fugitive-:Gvsplit!* -fugitive-:Gwq fugitive.txt /*fugitive-:Gwq* -fugitive-:Gwrite fugitive.txt /*fugitive-:Gwrite* -fugitive-<CR> fugitive.txt /*fugitive-<CR>* -fugitive-C fugitive.txt /*fugitive-C* -fugitive-O fugitive.txt /*fugitive-O* -fugitive-P fugitive.txt /*fugitive-P* -fugitive-a fugitive.txt /*fugitive-a* -fugitive-about fugitive.txt /*fugitive-about* -fugitive-commands fugitive.txt /*fugitive-commands* -fugitive-mappings fugitive.txt /*fugitive-mappings* -fugitive-o fugitive.txt /*fugitive-o* -fugitive-revision fugitive.txt /*fugitive-revision* -fugitive-statusline fugitive.txt /*fugitive-statusline* -fugitive-~ fugitive.txt /*fugitive-~* -fugitive.txt fugitive.txt /*fugitive.txt* -g:CommandTAcceptSelectionMap command-t.txt /*g:CommandTAcceptSelectionMap* -g:CommandTAcceptSelectionSplitMap command-t.txt /*g:CommandTAcceptSelectionSplitMap* -g:CommandTAcceptSelectionTabMap command-t.txt /*g:CommandTAcceptSelectionTabMap* -g:CommandTAcceptSelectionVSplitMap command-t.txt /*g:CommandTAcceptSelectionVSplitMap* -g:CommandTAlwaysShowDotFiles command-t.txt /*g:CommandTAlwaysShowDotFiles* -g:CommandTBackspaceMap command-t.txt /*g:CommandTBackspaceMap* -g:CommandTCancelMap command-t.txt /*g:CommandTCancelMap* -g:CommandTClearMap command-t.txt /*g:CommandTClearMap* -g:CommandTCursorEndMap command-t.txt /*g:CommandTCursorEndMap* -g:CommandTCursorLeftMap command-t.txt /*g:CommandTCursorLeftMap* -g:CommandTCursorRightMap command-t.txt /*g:CommandTCursorRightMap* -g:CommandTCursorStartMap command-t.txt /*g:CommandTCursorStartMap* -g:CommandTDeleteMap command-t.txt /*g:CommandTDeleteMap* -g:CommandTMatchWindowAtTop command-t.txt /*g:CommandTMatchWindowAtTop* -g:CommandTMatchWindowReverse command-t.txt /*g:CommandTMatchWindowReverse* -g:CommandTMaxCachedDirectories command-t.txt /*g:CommandTMaxCachedDirectories* -g:CommandTMaxDepth command-t.txt /*g:CommandTMaxDepth* -g:CommandTMaxFiles command-t.txt /*g:CommandTMaxFiles* -g:CommandTMaxHeight command-t.txt /*g:CommandTMaxHeight* -g:CommandTNeverShowDotFiles command-t.txt /*g:CommandTNeverShowDotFiles* -g:CommandTScanDotDirectories command-t.txt /*g:CommandTScanDotDirectories* -g:CommandTSelectNextMap command-t.txt /*g:CommandTSelectNextMap* -g:CommandTSelectPrevMap command-t.txt /*g:CommandTSelectPrevMap* -g:CommandTToggleFocusMap command-t.txt /*g:CommandTToggleFocusMap* -g:SuperTabCompletionContexts supertab.txt /*g:SuperTabCompletionContexts* -g:SuperTabContextDefaultCompletionType supertab.txt /*g:SuperTabContextDefaultCompletionType* -g:SuperTabCrMapping supertab.txt /*g:SuperTabCrMapping* -g:SuperTabDefaultCompletionType supertab.txt /*g:SuperTabDefaultCompletionType* -g:SuperTabLongestEnhanced supertab.txt /*g:SuperTabLongestEnhanced* -g:SuperTabLongestHighlight supertab.txt /*g:SuperTabLongestHighlight* -g:SuperTabMappingBackward supertab.txt /*g:SuperTabMappingBackward* -g:SuperTabMappingForward supertab.txt /*g:SuperTabMappingForward* -g:SuperTabMappingTabLiteral supertab.txt /*g:SuperTabMappingTabLiteral* -g:SuperTabNoCompleteAfter supertab.txt /*g:SuperTabNoCompleteAfter* -g:SuperTabNoCompleteBefore supertab.txt /*g:SuperTabNoCompleteBefore* -g:SuperTabRetainCompletionDuration supertab.txt /*g:SuperTabRetainCompletionDuration* g:coffee_make_options coffee-script.txt /*g:coffee_make_options* -g:loaded_luainspect luainspect.txt /*g:loaded_luainspect* -g:loaded_rails rails.txt /*g:loaded_rails* -g:lua_inspect_events luainspect.txt /*g:lua_inspect_events* -g:lua_inspect_internal luainspect.txt /*g:lua_inspect_internal* -g:lua_inspect_warnings luainspect.txt /*g:lua_inspect_warnings* -g:rails_abbreviations rails.txt /*g:rails_abbreviations* -g:rails_ctags_arguments rails.txt /*g:rails_ctags_arguments* -g:rails_default_file rails.txt /*g:rails_default_file* -g:rails_gnu_screen rails.txt /*g:rails_gnu_screen* -g:rails_history_size rails.txt /*g:rails_history_size* -g:rails_mappings rails.txt /*g:rails_mappings* -g:rails_menu rails.txt /*g:rails_menu* -g:rails_modelines rails.txt /*g:rails_modelines* -g:rails_syntax rails.txt /*g:rails_syntax* -g:rails_tabstop rails.txt /*g:rails_tabstop* -g:rails_url rails.txt /*g:rails_url* -g:snippets_dir snipMate.txt /*g:snippets_dir* -g:snips_author snipMate.txt /*g:snips_author* -g:tagbar_autoclose tagbar.txt /*g:tagbar_autoclose* -g:tagbar_autofocus tagbar.txt /*g:tagbar_autofocus* -g:tagbar_autoshowtag tagbar.txt /*g:tagbar_autoshowtag* -g:tagbar_compact tagbar.txt /*g:tagbar_compact* -g:tagbar_ctags_bin tagbar.txt /*g:tagbar_ctags_bin* -g:tagbar_expand tagbar.txt /*g:tagbar_expand* -g:tagbar_foldlevel tagbar.txt /*g:tagbar_foldlevel* -g:tagbar_iconchars tagbar.txt /*g:tagbar_iconchars* -g:tagbar_left tagbar.txt /*g:tagbar_left* -g:tagbar_singleclick tagbar.txt /*g:tagbar_singleclick* -g:tagbar_sort tagbar.txt /*g:tagbar_sort* -g:tagbar_systemenc tagbar.txt /*g:tagbar_systemenc* -g:tagbar_updateonsave_maxlines tagbar.txt /*g:tagbar_updateonsave_maxlines* -g:tagbar_width tagbar.txt /*g:tagbar_width* -gist-vim-install gist-vim.txt /*gist-vim-install* -gist-vim-license gist-vim.txt /*gist-vim-license* -gist-vim-requirements gist-vim.txt /*gist-vim-requirements* -gist-vim-tips gist-vim.txt /*gist-vim-tips* -gist-vim-usage gist-vim.txt /*gist-vim-usage* -iI indent-object.txt /*iI* -i_CTRL-G_S surround.txt /*i_CTRL-G_S* -i_CTRL-G_s surround.txt /*i_CTRL-G_s* -i_CTRL-R_<Tab> snipMate.txt /*i_CTRL-R_<Tab>* -idntobj-about indent-object.txt /*idntobj-about* -idntobj-blanklines indent-object.txt /*idntobj-blanklines* -idntobj-introduction indent-object.txt /*idntobj-introduction* -idntobj-objects indent-object.txt /*idntobj-objects* -ii indent-object.txt /*ii* -indent-object.txt indent-object.txt /*indent-object.txt* -list-snippets snipMate.txt /*list-snippets* -luainspect-contact luainspect.txt /*luainspect-contact* -luainspect-installation luainspect.txt /*luainspect-installation* -luainspect-license luainspect.txt /*luainspect-license* -luainspect-references luainspect.txt /*luainspect-references* -luainspect-usage luainspect.txt /*luainspect-usage* -luainspect.txt luainspect.txt /*luainspect.txt* -macros/rails.vim rails.txt /*macros\/rails.vim* -multi_snip snipMate.txt /*multi_snip* -rails rails.txt /*rails* -rails-'cfu' rails.txt /*rails-'cfu'* -rails-'completefunc' rails.txt /*rails-'completefunc'* -rails-'et' rails.txt /*rails-'et'* -rails-'expandtab' rails.txt /*rails-'expandtab'* -rails-'filetype' rails.txt /*rails-'filetype'* -rails-'ft' rails.txt /*rails-'ft'* -rails-'includeexpr' rails.txt /*rails-'includeexpr'* -rails-'inex' rails.txt /*rails-'inex'* -rails-'pa' rails.txt /*rails-'pa'* -rails-'path' rails.txt /*rails-'path'* -rails-'shiftwidth' rails.txt /*rails-'shiftwidth'* -rails-'softtabstop' rails.txt /*rails-'softtabstop'* -rails-'sts' rails.txt /*rails-'sts'* -rails-'sua' rails.txt /*rails-'sua'* -rails-'suffixesadd' rails.txt /*rails-'suffixesadd'* -rails-'sw' rails.txt /*rails-'sw'* -rails-:A rails.txt /*rails-:A* -rails-:AD rails.txt /*rails-:AD* -rails-:AE rails.txt /*rails-:AE* -rails-:AS rails.txt /*rails-:AS* -rails-:AT rails.txt /*rails-:AT* -rails-:AV rails.txt /*rails-:AV* -rails-:OpenURL rails.txt /*rails-:OpenURL* -rails-:R rails.txt /*rails-:R* -rails-:RD rails.txt /*rails-:RD* -rails-:RE rails.txt /*rails-:RE* -rails-:RS rails.txt /*rails-:RS* -rails-:RT rails.txt /*rails-:RT* -rails-:RV rails.txt /*rails-:RV* -rails-:Rabbrev rails.txt /*rails-:Rabbrev* -rails-:Rabbrev! rails.txt /*rails-:Rabbrev!* -rails-:Rails rails.txt /*rails-:Rails* -rails-:Rake rails.txt /*rails-:Rake* -rails-:Rake! rails.txt /*rails-:Rake!* -rails-:Rcd rails.txt /*rails-:Rcd* -rails-:Rcommand rails.txt /*rails-:Rcommand* -rails-:Rconsole rails.txt /*rails-:Rconsole* -rails-:Rcontroller rails.txt /*rails-:Rcontroller* -rails-:Rdbext rails.txt /*rails-:Rdbext* -rails-:Rdestroy rails.txt /*rails-:Rdestroy* -rails-:Rdoc rails.txt /*rails-:Rdoc* -rails-:Rdoc! rails.txt /*rails-:Rdoc!* -rails-:Redit rails.txt /*rails-:Redit* -rails-:Renvironment rails.txt /*rails-:Renvironment* -rails-:Rextract rails.txt /*rails-:Rextract* -rails-:Rfind rails.txt /*rails-:Rfind* -rails-:Rfixtures rails.txt /*rails-:Rfixtures* -rails-:Rfunctionaltest rails.txt /*rails-:Rfunctionaltest* -rails-:Rgenerate rails.txt /*rails-:Rgenerate* -rails-:Rhelper rails.txt /*rails-:Rhelper* -rails-:Rinitializer rails.txt /*rails-:Rinitializer* -rails-:Rintegrationtest rails.txt /*rails-:Rintegrationtest* -rails-:Rinvert rails.txt /*rails-:Rinvert* -rails-:Rjavascript rails.txt /*rails-:Rjavascript* -rails-:Rlayout rails.txt /*rails-:Rlayout* -rails-:Rlcd rails.txt /*rails-:Rlcd* -rails-:Rlib rails.txt /*rails-:Rlib* -rails-:Rlocale rails.txt /*rails-:Rlocale* -rails-:Rlog rails.txt /*rails-:Rlog* -rails-:Rmailer rails.txt /*rails-:Rmailer* -rails-:Rmetal rails.txt /*rails-:Rmetal* -rails-:Rmigration rails.txt /*rails-:Rmigration* -rails-:Rmodel rails.txt /*rails-:Rmodel* -rails-:Rnavcommand rails.txt /*rails-:Rnavcommand* -rails-:Robserver rails.txt /*rails-:Robserver* -rails-:Rp rails.txt /*rails-:Rp* -rails-:Rpartial rails.txt /*rails-:Rpartial* -rails-:Rplugin rails.txt /*rails-:Rplugin* -rails-:Rpp rails.txt /*rails-:Rpp* -rails-:Rpreview rails.txt /*rails-:Rpreview* -rails-:Rpreview! rails.txt /*rails-:Rpreview!* -rails-:Rrefresh rails.txt /*rails-:Rrefresh* -rails-:Rrefresh! rails.txt /*rails-:Rrefresh!* -rails-:Rrunner rails.txt /*rails-:Rrunner* -rails-:Rscript rails.txt /*rails-:Rscript* -rails-:Rserver rails.txt /*rails-:Rserver* -rails-:Rserver! rails.txt /*rails-:Rserver!* -rails-:Rset rails.txt /*rails-:Rset* -rails-:Rspec rails.txt /*rails-:Rspec* -rails-:Rstylesheet rails.txt /*rails-:Rstylesheet* -rails-:Rtags rails.txt /*rails-:Rtags* -rails-:Rtask rails.txt /*rails-:Rtask* -rails-:Rtree rails.txt /*rails-:Rtree* -rails-:Runittest rails.txt /*rails-:Runittest* -rails-:Rview rails.txt /*rails-:Rview* -rails-:Ry rails.txt /*rails-:Ry* -rails-:autocmd rails.txt /*rails-:autocmd* -rails-abbreviations rails.txt /*rails-abbreviations* -rails-abolish rails.txt /*rails-abolish* -rails-about rails.txt /*rails-about* -rails-alternate rails.txt /*rails-alternate* -rails-alternate-related rails.txt /*rails-alternate-related* -rails-autocommands rails.txt /*rails-autocommands* -rails-commands rails.txt /*rails-commands* -rails-configuration rails.txt /*rails-configuration* -rails-cream rails.txt /*rails-cream* -rails-custom-navigation rails.txt /*rails-custom-navigation* -rails-dbext rails.txt /*rails-dbext* -rails-gf rails.txt /*rails-gf* -rails-global-settings rails.txt /*rails-global-settings* -rails-integration rails.txt /*rails-integration* -rails-introduction rails.txt /*rails-introduction* -rails-license rails.txt /*rails-license* -rails-menu rails.txt /*rails-menu* -rails-migrations rails.txt /*rails-migrations* -rails-modelines rails.txt /*rails-modelines* -rails-navigation rails.txt /*rails-navigation* -rails-options rails.txt /*rails-options* -rails-partials rails.txt /*rails-partials* -rails-plugin-author rails.txt /*rails-plugin-author* -rails-rails-integration rails.txt /*rails-rails-integration* -rails-rake rails.txt /*rails-rake* -rails-rake-defaults rails.txt /*rails-rake-defaults* -rails-refactoring rails.txt /*rails-refactoring* -rails-related rails.txt /*rails-related* -rails-rspec rails.txt /*rails-rspec* -rails-screen rails.txt /*rails-screen* -rails-scripts rails.txt /*rails-scripts* -rails-snippets rails.txt /*rails-snippets* -rails-surround rails.txt /*rails-surround* -rails-syntax rails.txt /*rails-syntax* -rails-syntax-assertions rails.txt /*rails-syntax-assertions* -rails-syntax-classes rails.txt /*rails-syntax-classes* -rails-syntax-keywords rails.txt /*rails-syntax-keywords* -rails-syntax-strings rails.txt /*rails-syntax-strings* -rails-syntax-yaml rails.txt /*rails-syntax-yaml* -rails-tabs rails.txt /*rails-tabs* -rails-template-types rails.txt /*rails-template-types* -rails-type-navigation rails.txt /*rails-type-navigation* -rails-vim-integration rails.txt /*rails-vim-integration* -rails.txt rails.txt /*rails.txt* showmarks showmarks.txt /*showmarks* showmarks-changelog showmarks.txt /*showmarks-changelog* showmarks-commands showmarks.txt /*showmarks-commands* @@ -742,28 +46,6 @@ showmarks-contents showmarks.txt /*showmarks-contents* showmarks-highlighting showmarks.txt /*showmarks-highlighting* showmarks-mappings showmarks.txt /*showmarks-mappings* showmarks.txt showmarks.txt /*showmarks.txt* -snipMate snipMate.txt /*snipMate* -snipMate-$# snipMate.txt /*snipMate-$#* -snipMate-${#:} snipMate.txt /*snipMate-${#:}* -snipMate-${#} snipMate.txt /*snipMate-${#}* -snipMate-author snipMate.txt /*snipMate-author* -snipMate-commands snipMate.txt /*snipMate-commands* -snipMate-contact snipMate.txt /*snipMate-contact* -snipMate-description snipMate.txt /*snipMate-description* -snipMate-disadvantages snipMate.txt /*snipMate-disadvantages* -snipMate-expandtab snipMate.txt /*snipMate-expandtab* -snipMate-features snipMate.txt /*snipMate-features* -snipMate-filename snipMate.txt /*snipMate-filename* -snipMate-indenting snipMate.txt /*snipMate-indenting* -snipMate-license snipMate.txt /*snipMate-license* -snipMate-placeholders snipMate.txt /*snipMate-placeholders* -snipMate-remap snipMate.txt /*snipMate-remap* -snipMate-settings snipMate.txt /*snipMate-settings* -snipMate-usage snipMate.txt /*snipMate-usage* -snipMate.txt snipMate.txt /*snipMate.txt* -snippet snipMate.txt /*snippet* -snippet-syntax snipMate.txt /*snippet-syntax* -snippets snipMate.txt /*snippets* solarized solarized.txt /*solarized* solarized-colors solarized.txt /*solarized-colors* solarized-colorscheme solarized.txt /*solarized-colorscheme* @@ -774,84 +56,6 @@ solarized-options solarized.txt /*solarized-options* solarized-term solarized.txt /*solarized-term* solarized-togglebg solarized.txt /*solarized-togglebg* solarized.vim solarized.txt /*solarized.vim* -supertab supertab.txt /*supertab* -supertab-completioncontexts supertab.txt /*supertab-completioncontexts* -supertab-contextdefault supertab.txt /*supertab-contextdefault* -supertab-contextdiscover supertab.txt /*supertab-contextdiscover* -supertab-contextexample supertab.txt /*supertab-contextexample* -supertab-contexttext supertab.txt /*supertab-contexttext* -supertab-crmapping supertab.txt /*supertab-crmapping* -supertab-defaultcompletion supertab.txt /*supertab-defaultcompletion* -supertab-duration supertab.txt /*supertab-duration* -supertab-forwardbackward supertab.txt /*supertab-forwardbackward* -supertab-intro supertab.txt /*supertab-intro* -supertab-longestenhanced supertab.txt /*supertab-longestenhanced* -supertab-longesthighlight supertab.txt /*supertab-longesthighlight* -supertab-mappingtabliteral supertab.txt /*supertab-mappingtabliteral* -supertab-options supertab.txt /*supertab-options* -supertab-preventcomplete supertab.txt /*supertab-preventcomplete* -supertab-usage supertab.txt /*supertab-usage* -supertab.txt supertab.txt /*supertab.txt* -surround surround.txt /*surround* -surround-author surround.txt /*surround-author* -surround-customizing surround.txt /*surround-customizing* -surround-issues surround.txt /*surround-issues* -surround-mappings surround.txt /*surround-mappings* -surround-replacements surround.txt /*surround-replacements* -surround-targets surround.txt /*surround-targets* -surround.txt surround.txt /*surround.txt* -syntastic syntastic.txt /*syntastic* -syntastic-about syntastic.txt /*syntastic-about* -syntastic-changelog syntastic.txt /*syntastic-changelog* -syntastic-commands syntastic.txt /*syntastic-commands* -syntastic-contents syntastic.txt /*syntastic-contents* -syntastic-credits syntastic.txt /*syntastic-credits* -syntastic-error-signs syntastic.txt /*syntastic-error-signs* -syntastic-error-window syntastic.txt /*syntastic-error-window* -syntastic-functionality syntastic.txt /*syntastic-functionality* -syntastic-intro syntastic.txt /*syntastic-intro* -syntastic-license syntastic.txt /*syntastic-license* -syntastic-options syntastic.txt /*syntastic-options* -syntastic-statusline-flag syntastic.txt /*syntastic-statusline-flag* -syntastic-syntax-checkers syntastic.txt /*syntastic-syntax-checkers* -syntastic.txt syntastic.txt /*syntastic.txt* -tagbar tagbar.txt /*tagbar* -tagbar-autoopen tagbar.txt /*tagbar-autoopen* -tagbar-commands tagbar.txt /*tagbar-commands* -tagbar-configuration tagbar.txt /*tagbar-configuration* -tagbar-contents tagbar.txt /*tagbar-contents* -tagbar-credits tagbar.txt /*tagbar-credits* -tagbar-extend tagbar.txt /*tagbar-extend* -tagbar-features tagbar.txt /*tagbar-features* -tagbar-highlight tagbar.txt /*tagbar-highlight* -tagbar-history tagbar.txt /*tagbar-history* -tagbar-installation tagbar.txt /*tagbar-installation* -tagbar-intro tagbar.txt /*tagbar-intro* -tagbar-issues tagbar.txt /*tagbar-issues* -tagbar-keys tagbar.txt /*tagbar-keys* -tagbar-other tagbar.txt /*tagbar-other* -tagbar-pseudotags tagbar.txt /*tagbar-pseudotags* -tagbar-requirements tagbar.txt /*tagbar-requirements* -tagbar-todo tagbar.txt /*tagbar-todo* -tagbar-usage tagbar.txt /*tagbar-usage* -tagbar.txt tagbar.txt /*tagbar.txt* -taglist-commands taglist.txt /*taglist-commands* -taglist-debug taglist.txt /*taglist-debug* -taglist-extend taglist.txt /*taglist-extend* -taglist-faq taglist.txt /*taglist-faq* -taglist-functions taglist.txt /*taglist-functions* -taglist-install taglist.txt /*taglist-install* -taglist-internet taglist.txt /*taglist-internet* -taglist-intro taglist.txt /*taglist-intro* -taglist-keys taglist.txt /*taglist-keys* -taglist-license taglist.txt /*taglist-license* -taglist-menu taglist.txt /*taglist-menu* -taglist-options taglist.txt /*taglist-options* -taglist-requirements taglist.txt /*taglist-requirements* -taglist-session taglist.txt /*taglist-session* -taglist-todo taglist.txt /*taglist-todo* -taglist-using taglist.txt /*taglist-using* -taglist.txt taglist.txt /*taglist.txt* textile-changelog textile.txt /*textile-changelog* textile-commands textile.txt /*textile-commands* textile-config textile.txt /*textile-config* @@ -861,32 +65,6 @@ textile.txt textile.txt /*textile.txt* toggle-background solarized.txt /*toggle-background* toggle-bg solarized.txt /*toggle-bg* togglebg solarized.txt /*togglebg* -unimpaired unimpaired.txt /*unimpaired* -unimpaired-encoding unimpaired.txt /*unimpaired-encoding* -unimpaired-lines unimpaired.txt /*unimpaired-lines* -unimpaired-next unimpaired.txt /*unimpaired-next* -unimpaired-todo unimpaired.txt /*unimpaired-todo* -unimpaired.txt unimpaired.txt /*unimpaired.txt* urxvt solarized.txt /*urxvt* -vS surround.txt /*vS* -v_[e unimpaired.txt /*v_[e* -v_[u unimpaired.txt /*v_[u* -v_[x unimpaired.txt /*v_[x* -v_[y unimpaired.txt /*v_[y* -v_]e unimpaired.txt /*v_]e* -v_]u unimpaired.txt /*v_]u* -v_]x unimpaired.txt /*v_]x* -v_]y unimpaired.txt /*v_]y* -vgS surround.txt /*vgS* vim-colors-solarized solarized.txt /*vim-colors-solarized* -vs surround.txt /*vs* without solarized.txt /*without* -yS surround.txt /*yS* -ySS surround.txt /*ySS* -ys surround.txt /*ys* -yss surround.txt /*yss* -zoomwin ZoomWin.txt /*zoomwin* -zoomwin-copyright ZoomWin.txt /*zoomwin-copyright* -zoomwin-history ZoomWin.txt /*zoomwin-history* -zoomwin-setup ZoomWin.txt /*zoomwin-setup* -zoomwin-usage ZoomWin.txt /*zoomwin-usage* diff --git a/vim/doc/unimpaired.txt b/vim/doc/unimpaired.txt deleted file mode 100644 index 82d61a9..0000000 --- a/vim/doc/unimpaired.txt +++ /dev/null @@ -1,103 +0,0 @@ -*unimpaired.txt* Pairs of handy bracket mappings - -Author: Tim Pope <http://tpo.pe/> -License: Same terms as Vim itself (see |license|) - -This plugin is only available if 'compatible' is not set. - -INTRODUCTION *unimpaired* - -This plugin provides several pairs of bracket maps. - -NEXT AND PREVIOUS *unimpaired-next* - -The following maps all correspond to normal mode commands. If a count is -given, it becomes an argument to the command. A mnemonic for the "a" commands -is "args" and for the "q" commands is "quickfix". - -*[a* |:previous| -*]a* |:next| -*[A* |:first| -*]A* |:last| -*[b* |:bprevious| -*]b* |:bnext| -*[B* |:bfirst| -*]B* |:blast| -*[l* |:lprevious| -*]l* |:lnext| -*[L* |:lfirst| -*]L* |:llast| -*[q* |:cprevious| -*]q* |:cnext| -*[Q* |:cfirst| -*]Q* |:clast| -*[t* |:tprevious| -*]t* |:tnext| -*[T* |:tfirst| -*]T* |:tlast| - - *[o* -[o Go to the file preceding the current one - alphabetically in the current file's directory. - - *]o* -]o Go to the file succeeding the current one - alphabetically in the current file's directory. - -LINE OPERATIONS *unimpaired-lines* - - *[<Space>* -[<Space> Add [count] blank lines above the cursor. - - *]<Space>* -]<Space> Add [count] blank lines below the cursor. - - *[e* *v_[e* -[e Exchange the current line with [count] lines above it. - - *]e* *v_]e* -]e Exchange the current line with [count] lines below it. - -ENCODING AND DECODING *unimpaired-encoding* - -Each of these operations has a map that takes a motion, a map that -targets [count] lines, and a visual mode map. The linewise variant integrates -with repeat.vim. - -Mnenomic: encoding always comes before decoding; "[" always comes before "]". - - *[x* *[xx* *v_[x* -[x{motion} XML encode. -[xx <foo bar="baz"> => <foo bar="baz"> -{Visual}[x - - *]x* *]xx* *v_]x* -]x{motion} XML decode. HTML entities are handled as well. -]xx -{Visual}]x - - *[u* *[uu* *v_[u* -[u{motion} URL encode. -[uu foo bar => foo%20bar -{Visual}[u - - *]u* *]uu* *v_]u* -]u{motion} URL decode. -]uu -{Visual}]u - - *[y* *[yy* *v_[y* -[y{motion} C String encode. Backslash escape control -[yy characters, quotation marks, and backslashes. -{Visual}[y - - *]y* *]yy* *v_]y* -]y{motion} C String decode. -]yy -{Visual}]y - -TODO *unimpaired-todo* - -Avoid munging null characters when encoding and decoding. - - vim:tw=78:et:ft=help:norl: diff --git a/vim/ftplugin/html_snip_helper.vim b/vim/ftplugin/html_snip_helper.vim deleted file mode 100644 index 2e54570..0000000 --- a/vim/ftplugin/html_snip_helper.vim +++ /dev/null @@ -1,10 +0,0 @@ -" Helper function for (x)html snippets -if exists('s:did_snip_helper') || &cp || !exists('loaded_snips') - finish -endif -let s:did_snip_helper = 1 - -" Automatically closes tag if in xhtml -fun! Close() - return stridx(&ft, 'xhtml') == -1 ? '' : ' /' -endf diff --git a/vim/plugin/31-create-scala.vim b/vim/plugin/31-create-scala.vim deleted file mode 100644 index e4ecb44..0000000 --- a/vim/plugin/31-create-scala.vim +++ /dev/null @@ -1,55 +0,0 @@ -" Vim plugin that generates new Scala source file when you type -" vim nonexistent.scala. -" Scripts tries to detect package name from the directory path, e. g. -" .../src/main/scala/com/mycompany/myapp/app.scala gets header -" package com.mycompany.myapp -" -" Author : Stepan Koltsov <yozh@mx1.ru> - -function! MakeScalaFile() - if exists("b:template_used") && b:template_used - return - endif - - let b:template_used = 1 - - let filename = expand("<afile>:p") - let x = substitute(filename, "\.scala$", "", "") - - let p = substitute(x, "/[^/]*$", "", "") - let p = substitute(p, "/", ".", "g") - let p = substitute(p, ".*\.src$", "@", "") " unnamed package - let p = substitute(p, ".*\.src\.", "!", "") - let p = substitute(p, "^!main\.scala\.", "!", "") " - let p = substitute(p, "^!.*\.ru\.", "!ru.", "") - let p = substitute(p, "^!.*\.org\.", "!org.", "") - let p = substitute(p, "^!.*\.com\.", "!com.", "") - - " ! marks that we found package name. - if match(p, "^!") == 0 - let p = substitute(p, "^!", "", "") - else - " Don't know package name. - let p = "@" - endif - - let class = substitute(x, ".*/", "", "") - - if p != "@" - call append("0", "package " . p) - endif - - "norm G - "call append(".", "class " . class . " {") - - "norm G - "call append(".", "} /// end of " . class) - - call append(".", "// vim: set ts=4 sw=4 et:") - call append(".", "") - -endfunction - -au BufNewFile *.scala call MakeScalaFile() - -" vim: set ts=4 sw=4 et: diff --git a/vim/plugin/fugitive.vim b/vim/plugin/fugitive.vim deleted file mode 100644 index 17d52fc..0000000 --- a/vim/plugin/fugitive.vim +++ /dev/null @@ -1,2220 +0,0 @@ -" fugitive.vim - A Git wrapper so awesome, it should be illegal -" Maintainer: Tim Pope <http://tpo.pe/> -" Version: 1.2 -" GetLatestVimScripts: 2975 1 :AutoInstall: fugitive.vim - -if exists('g:loaded_fugitive') || &cp - finish -endif -let g:loaded_fugitive = 1 - -if !exists('g:fugitive_git_executable') - let g:fugitive_git_executable = 'git' -endif - -" Utility {{{1 - -function! s:function(name) abort - return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) -endfunction - -function! s:sub(str,pat,rep) abort - return substitute(a:str,'\v\C'.a:pat,a:rep,'') -endfunction - -function! s:gsub(str,pat,rep) abort - return substitute(a:str,'\v\C'.a:pat,a:rep,'g') -endfunction - -function! s:shellesc(arg) abort - if a:arg =~ '^[A-Za-z0-9_/.-]\+$' - return a:arg - elseif &shell =~# 'cmd' && a:arg !~# '"' - return '"'.a:arg.'"' - else - return shellescape(a:arg) - endif -endfunction - -function! s:fnameescape(file) abort - if exists('*fnameescape') - return fnameescape(a:file) - else - return escape(a:file," \t\n*?[{`$\\%#'\"|!<") - endif -endfunction - -function! s:throw(string) abort - let v:errmsg = 'fugitive: '.a:string - throw v:errmsg -endfunction - -function! s:warn(str) - echohl WarningMsg - echomsg a:str - echohl None - let v:warningmsg = a:str -endfunction - -function! s:shellslash(path) - if exists('+shellslash') && !&shellslash - return s:gsub(a:path,'\\','/') - else - return a:path - endif -endfunction - -function! s:recall() - let rev = s:buffer().rev() - if rev ==# ':' - return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*') - endif - return rev -endfunction - -function! s:add_methods(namespace, method_names) abort - for name in a:method_names - let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name) - endfor -endfunction - -let s:commands = [] -function! s:command(definition) abort - let s:commands += [a:definition] -endfunction - -function! s:define_commands() - for command in s:commands - exe 'command! -buffer '.command - endfor -endfunction - -function! s:compatibility_check() - if exists('b:git_dir') && exists('*GitBranchInfoCheckGitDir') && !exists('g:fugitive_did_compatibility_warning') - let g:fugitive_did_compatibility_warning = 1 - call s:warn("See http://github.com/tpope/vim-fugitive/issues#issue/1 for why you should remove git-branch-info.vim") - endif -endfunction - -augroup fugitive_utility - autocmd! - autocmd User Fugitive call s:define_commands() - autocmd VimEnter * call s:compatibility_check() -augroup END - -let s:abstract_prototype = {} - -" }}}1 -" Initialization {{{1 - -function! s:ExtractGitDir(path) abort - let path = s:shellslash(a:path) - if path =~? '^fugitive://.*//' - return matchstr(path,'fugitive://\zs.\{-\}\ze//') - endif - let fn = fnamemodify(path,':s?[\/]$??') - let ofn = "" - let nfn = fn - while fn != ofn - if filereadable(fn . '/.git/HEAD') - return s:sub(simplify(fnamemodify(fn . '/.git',':p')),'\W$','') - elseif fn =~ '\.git$' && filereadable(fn . '/HEAD') - return s:sub(simplify(fnamemodify(fn,':p')),'\W$','') - endif - let ofn = fn - let fn = fnamemodify(ofn,':h') - endwhile - return '' -endfunction - -function! s:Detect(path) - if exists('b:git_dir') && b:git_dir ==# '' - unlet b:git_dir - endif - if !exists('b:git_dir') - let dir = s:ExtractGitDir(a:path) - if dir != '' - let b:git_dir = dir - endif - endif - if exists('b:git_dir') - silent doautocmd User Fugitive - cnoremap <expr> <buffer> <C-R><C-G> <SID>recall() - let buffer = fugitive#buffer() - if expand('%:p') =~# '//' - call buffer.setvar('&path',s:sub(buffer.getvar('&path'),'^\.%(,|$)','')) - endif - if stridx(buffer.getvar('&tags'),escape(b:git_dir.'/tags',', ')) == -1 - call buffer.setvar('&tags',escape(b:git_dir.'/tags',', ').','.buffer.getvar('&tags')) - if &filetype != '' - call buffer.setvar('&tags',escape(b:git_dir.'/'.&filetype.'.tags',', ').','.buffer.getvar('&tags')) - endif - endif - endif -endfunction - -augroup fugitive - autocmd! - autocmd BufNewFile,BufReadPost * call s:Detect(expand('<amatch>:p')) - autocmd FileType netrw call s:Detect(expand('<afile>:p')) - autocmd VimEnter * if expand('<amatch>')==''|call s:Detect(getcwd())|endif - autocmd BufWinLeave * execute getwinvar(+winnr(), 'fugitive_leave') -augroup END - -" }}}1 -" Repository {{{1 - -let s:repo_prototype = {} -let s:repos = {} - -function! s:repo(...) abort - let dir = a:0 ? a:1 : (exists('b:git_dir') && b:git_dir !=# '' ? b:git_dir : s:ExtractGitDir(expand('%:p'))) - if dir !=# '' - if has_key(s:repos,dir) - let repo = get(s:repos,dir) - else - let repo = {'git_dir': dir} - let s:repos[dir] = repo - endif - return extend(extend(repo,s:repo_prototype,'keep'),s:abstract_prototype,'keep') - endif - call s:throw('not a git repository: '.expand('%:p')) -endfunction - -function! s:repo_dir(...) dict abort - return join([self.git_dir]+a:000,'/') -endfunction - -function! s:repo_tree(...) dict abort - if !self.bare() - let dir = fnamemodify(self.git_dir,':h') - return join([dir]+a:000,'/') - endif - call s:throw('no work tree') -endfunction - -function! s:repo_bare() dict abort - return self.dir() !~# '/\.git$' -endfunction - -function! s:repo_translate(spec) dict abort - if a:spec ==# '.' || a:spec ==# '/.' - return self.bare() ? self.dir() : self.tree() - elseif a:spec =~# '^/' - return fnamemodify(self.dir(),':h').a:spec - elseif a:spec =~# '^:[0-3]:' - return 'fugitive://'.self.dir().'//'.a:spec[1].'/'.a:spec[3:-1] - elseif a:spec ==# ':' - if $GIT_INDEX_FILE =~# '/[^/]*index[^/]*\.lock$' && fnamemodify($GIT_INDEX_FILE,':p')[0:strlen(s:repo().dir())] ==# s:repo().dir('') && filereadable($GIT_INDEX_FILE) - return fnamemodify($GIT_INDEX_FILE,':p') - else - return self.dir('index') - endif - elseif a:spec =~# '^:/' - let ref = self.rev_parse(matchstr(a:spec,'.[^:]*')) - return 'fugitive://'.self.dir().'//'.ref - elseif a:spec =~# '^:' - return 'fugitive://'.self.dir().'//0/'.a:spec[1:-1] - elseif a:spec =~# 'HEAD\|^refs/' && a:spec !~ ':' && filereadable(self.dir(a:spec)) - return self.dir(a:spec) - elseif filereadable(s:repo().dir('refs/'.a:spec)) - return self.dir('refs/'.a:spec) - elseif filereadable(s:repo().dir('refs/tags/'.a:spec)) - return self.dir('refs/tags/'.a:spec) - elseif filereadable(s:repo().dir('refs/heads/'.a:spec)) - return self.dir('refs/heads/'.a:spec) - elseif filereadable(s:repo().dir('refs/remotes/'.a:spec)) - return self.dir('refs/remotes/'.a:spec) - elseif filereadable(s:repo().dir('refs/remotes/'.a:spec.'/HEAD')) - return self.dir('refs/remotes/'.a:spec,'/HEAD') - else - try - let ref = self.rev_parse(matchstr(a:spec,'[^:]*')) - let path = s:sub(matchstr(a:spec,':.*'),'^:','/') - return 'fugitive://'.self.dir().'//'.ref.path - catch /^fugitive:/ - return self.tree(a:spec) - endtry - endif -endfunction - -call s:add_methods('repo',['dir','tree','bare','translate']) - -function! s:repo_git_command(...) dict abort - let git = g:fugitive_git_executable . ' --git-dir='.s:shellesc(self.git_dir) - return git.join(map(copy(a:000),'" ".s:shellesc(v:val)'),'') -endfunction - -function! s:repo_git_chomp(...) dict abort - return s:sub(system(call(self.git_command,a:000,self)),'\n$','') -endfunction - -function! s:repo_git_chomp_in_tree(...) dict abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - return call(s:repo().git_chomp, a:000, s:repo()) - finally - execute cd.'`=dir`' - endtry -endfunction - -function! s:repo_rev_parse(rev) dict abort - let hash = self.git_chomp('rev-parse','--verify',a:rev) - if hash =~ '\<\x\{40\}$' - return matchstr(hash,'\<\x\{40\}$') - endif - call s:throw('rev-parse '.a:rev.': '.hash) -endfunction - -call s:add_methods('repo',['git_command','git_chomp','git_chomp_in_tree','rev_parse']) - -function! s:repo_dirglob(base) dict abort - let base = s:sub(a:base,'^/','') - let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*/')),"\n") - call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]') - return matches -endfunction - -function! s:repo_superglob(base) dict abort - if a:base =~# '^/' || a:base !~# ':' - let results = [] - if a:base !~# '^/' - let heads = ["HEAD","ORIG_HEAD","FETCH_HEAD","MERGE_HEAD"] - let heads += sort(split(s:repo().git_chomp("rev-parse","--symbolic","--branches","--tags","--remotes"),"\n")) - call filter(heads,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - let results += heads - endif - if !self.bare() - let base = s:sub(a:base,'^/','') - let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*')),"\n") - call map(matches,'s:shellslash(v:val)') - call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val') - call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]') - let results += matches - endif - return results - - elseif a:base =~# '^:' - let entries = split(self.git_chomp('ls-files','--stage'),"\n") - call map(entries,'s:sub(v:val,".*(\\d)\\t(.*)",":\\1:\\2")') - if a:base !~# '^:[0-3]\%(:\|$\)' - call filter(entries,'v:val[1] == "0"') - call map(entries,'v:val[2:-1]') - endif - call filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - return entries - - else - let tree = matchstr(a:base,'.*[:/]') - let entries = split(self.git_chomp('ls-tree',tree),"\n") - call map(entries,'s:sub(v:val,"^04.*\\zs$","/")') - call map(entries,'tree.s:sub(v:val,".*\t","")') - return filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base') - endif -endfunction - -call s:add_methods('repo',['dirglob','superglob']) - -function! s:repo_config(conf) dict abort - return matchstr(system(s:repo().git_command('config').' '.a:conf),"[^\r\n]*") -endfun - -function! s:repo_user() dict abort - let username = s:repo().config('user.name') - let useremail = s:repo().config('user.email') - return username.' <'.useremail.'>' -endfun - -function! s:repo_aliases() dict abort - if !has_key(self,'_aliases') - let self._aliases = {} - for line in split(self.git_chomp('config','--get-regexp','^alias[.]'),"\n") - let self._aliases[matchstr(line,'\.\zs\S\+')] = matchstr(line,' \zs.*') - endfor - endif - return self._aliases -endfunction - -call s:add_methods('repo',['config', 'user', 'aliases']) - -function! s:repo_keywordprg() dict abort - let args = ' --git-dir='.escape(self.dir(),"\\\"' ").' show' - if has('gui_running') && !has('win32') - return g:fugitive_git_executable . ' --no-pager' . args - else - return g:fugitive_git_executable . args - endif -endfunction - -call s:add_methods('repo',['keywordprg']) - -" }}}1 -" Buffer {{{1 - -let s:buffer_prototype = {} - -function! s:buffer(...) abort - let buffer = {'#': bufnr(a:0 ? a:1 : '%')} - call extend(extend(buffer,s:buffer_prototype,'keep'),s:abstract_prototype,'keep') - if buffer.getvar('git_dir') !=# '' - return buffer - endif - call s:throw('not a git repository: '.expand('%:p')) -endfunction - -function! fugitive#buffer(...) abort - return s:buffer(a:0 ? a:1 : '%') -endfunction - -function! s:buffer_getvar(var) dict abort - return getbufvar(self['#'],a:var) -endfunction - -function! s:buffer_setvar(var,value) dict abort - return setbufvar(self['#'],a:var,a:value) -endfunction - -function! s:buffer_getline(lnum) dict abort - return getbufline(self['#'],a:lnum)[0] -endfunction - -function! s:buffer_repo() dict abort - return s:repo(self.getvar('git_dir')) -endfunction - -function! s:buffer_type(...) dict abort - if self.getvar('fugitive_type') != '' - let type = self.getvar('fugitive_type') - elseif fnamemodify(self.spec(),':p') =~# '.\git/refs/\|\.git/\w*HEAD$' - let type = 'head' - elseif self.getline(1) =~ '^tree \x\{40\}$' && self.getline(2) == '' - let type = 'tree' - elseif self.getline(1) =~ '^\d\{6\} \w\{4\} \x\{40\}\>\t' - let type = 'tree' - elseif self.getline(1) =~ '^\d\{6\} \x\{40\}\> \d\t' - let type = 'index' - elseif isdirectory(self.spec()) - let type = 'directory' - elseif self.spec() == '' - let type = 'null' - else - let type = 'file' - endif - if a:0 - return !empty(filter(copy(a:000),'v:val ==# type')) - else - return type - endif -endfunction - -if has('win32') - - function! s:buffer_spec() dict abort - let bufname = bufname(self['#']) - let retval = '' - for i in split(bufname,'[^:]\zs\\') - let retval = fnamemodify((retval==''?'':retval.'\').i,':.') - endfor - return s:shellslash(fnamemodify(retval,':p')) - endfunction - -else - - function! s:buffer_spec() dict abort - let bufname = bufname(self['#']) - return s:shellslash(bufname == '' ? '' : fnamemodify(bufname,':p')) - endfunction - -endif - -function! s:buffer_name() dict abort - return self.spec() -endfunction - -function! s:buffer_commit() dict abort - return matchstr(self.spec(),'^fugitive://.\{-\}//\zs\w*') -endfunction - -function! s:buffer_path(...) dict abort - let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*') - if rev != '' - let rev = s:sub(rev,'\w*','') - else - let rev = self.spec()[strlen(self.repo().tree()) : -1] - endif - return s:sub(s:sub(rev,'.\zs/$',''),'^/',a:0 ? a:1 : '') -endfunction - -function! s:buffer_rev() dict abort - let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*') - if rev =~ '^\x/' - return ':'.rev[0].':'.rev[2:-1] - elseif rev =~ '.' - return s:sub(rev,'/',':') - elseif self.spec() =~ '\.git/index$' - return ':' - elseif self.spec() =~ '\.git/refs/\|\.git/.*HEAD$' - return self.spec()[strlen(self.repo().dir())+1 : -1] - else - return self.path() - endif -endfunction - -function! s:buffer_sha1() dict abort - if self.spec() =~ '^fugitive://' || self.spec() =~ '\.git/refs/\|\.git/.*HEAD$' - return self.repo().rev_parse(self.rev()) - else - return '' - endif -endfunction - -function! s:buffer_expand(rev) dict abort - if a:rev =~# '^:[0-3]$' - let file = a:rev.self.path(':') - elseif a:rev =~# '^[-:]/$' - let file = '/'.self.path() - elseif a:rev =~# '^-' - let file = 'HEAD^{}'.a:rev[1:-1].self.path(':') - elseif a:rev =~# '^@{' - let file = 'HEAD'.a:rev.self.path(':') - elseif a:rev =~# '^[~^]' - let commit = s:sub(self.commit(),'^\d=$','HEAD') - let file = commit.a:rev.self.path(':') - else - let file = a:rev - endif - return s:sub(s:sub(file,'\%$',self.path()),'\.\@<=/$','') -endfunction - -function! s:buffer_containing_commit() dict abort - if self.commit() =~# '^\d$' - return ':' - elseif self.commit() =~# '.' - return self.commit() - else - return 'HEAD' - endif -endfunction - -call s:add_methods('buffer',['getvar','setvar','getline','repo','type','spec','name','commit','path','rev','sha1','expand','containing_commit']) - -" }}}1 -" Git {{{1 - -call s:command("-bang -nargs=? -complete=customlist,s:GitComplete Git :execute s:Git(<bang>0,<q-args>)") - -function! s:ExecuteInTree(cmd) abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - execute a:cmd - finally - execute cd.'`=dir`' - endtry -endfunction - -function! s:Git(bang,cmd) abort - if a:bang - return s:Edit('edit',1,a:cmd) - endif - let git = s:repo().git_command() - if has('gui_running') && !has('win32') - let git .= ' --no-pager' - endif - let cmd = matchstr(a:cmd,'\v\C.{-}%($|\\@<!%(\\\\)*\|)@=') - call s:ExecuteInTree('!'.git.' '.cmd) - call fugitive#reload_status() - return matchstr(a:cmd,'\v\C\\@<!%(\\\\)*\|\zs.*') -endfunction - -function! s:GitComplete(A,L,P) abort - if !exists('s:exec_path') - let s:exec_path = s:sub(system(g:fugitive_git_executable.' --exec-path'),'\n$','') - endif - let cmds = map(split(glob(s:exec_path.'/git-*'),"\n"),'s:sub(v:val[strlen(s:exec_path)+5 : -1],"\\.exe$","")') - if a:L =~ ' [[:alnum:]-]\+ ' - return s:repo().superglob(a:A) - elseif a:A == '' - return sort(cmds+keys(s:repo().aliases())) - else - return filter(sort(cmds+keys(s:repo().aliases())),'v:val[0:strlen(a:A)-1] ==# a:A') - endif -endfunction - -" }}}1 -" Gcd, Glcd {{{1 - -function! s:DirComplete(A,L,P) abort - let matches = s:repo().dirglob(a:A) - return matches -endfunction - -call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Gcd :cd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`") -call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Glcd :lcd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`") - -" }}}1 -" Gstatus {{{1 - -call s:command("-bar Gstatus :execute s:Status()") - -function! s:Status() abort - try - Gpedit : - wincmd P - nnoremap <buffer> <silent> q :<C-U>bdelete<CR> - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return '' -endfunction - -function! fugitive#reload_status() abort - let mytab = tabpagenr() - for tab in [mytab] + range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - if getbufvar(tabpagebuflist(tab)[winnr-1],'fugitive_type') ==# 'index' - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - if !&modified - call s:BufReadIndex() - endif - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - endif - endfor - endfor -endfunction - -function! s:StageReloadSeek(target,lnum1,lnum2) - let jump = a:target - let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.*') - if f !=# '' | let jump = f | endif - let f = matchstr(getline(a:lnum2+1),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.*') - if f !=# '' | let jump = f | endif - silent! edit! - 1 - redraw - call search('^#\t\%([[:alpha:] ]\+: *\)\=\V'.jump.'\%( (new commits)\)\=\$','W') -endfunction - -function! s:StageDiff(diff) abort - let section = getline(search('^# .*:$','bcnW')) - let line = getline('.') - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - if filename ==# '' && section ==# '# Changes to be committed:' - return 'Git diff --cached' - elseif filename ==# '' - return 'Git diff' - elseif line =~# '^#\trenamed:' && filename =~# ' -> ' - let [old, new] = split(filename,' -> ') - execute 'Gedit '.s:fnameescape(':0:'.new) - return a:diff.' HEAD:'.s:fnameescape(old) - elseif section ==# '# Changes to be committed:' - execute 'Gedit '.s:fnameescape(':0:'.filename) - return a:diff.' -' - else - execute 'Gedit '.s:fnameescape('/'.filename) - return a:diff - endif -endfunction - -function! s:StageDiffEdit() abort - let section = getline(search('^# .*:$','bcnW')) - let line = getline('.') - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - let arg = (filename ==# '' ? '.' : filename) - if section ==# '# Changes to be committed:' - return 'Git! diff --cached '.s:shellesc(arg) - elseif section ==# '# Untracked files:' - let repo = s:repo() - call repo.git_chomp_in_tree('add','--intent-to-add',arg) - if arg ==# '.' - silent! edit! - 1 - if !search('^# Change\%(d but not updated\|s not staged for commit\):$','W') - call search('^# Change','W') - endif - else - call s:StageReloadSeek(arg,line('.'),line('.')) - endif - return '' - else - return 'Git! diff '.s:shellesc(arg) - endif -endfunction - -function! s:StageToggle(lnum1,lnum2) abort - try - let output = '' - for lnum in range(a:lnum1,a:lnum2) - let line = getline(lnum) - let repo = s:repo() - if line ==# '# Changes to be committed:' - call repo.git_chomp_in_tree('reset','-q') - silent! edit! - 1 - if !search('^# Untracked files:$','W') - call search('^# Change','W') - endif - return '' - elseif line =~# '^# Change\%(d but not updated\|s not staged for commit\):$' - call repo.git_chomp_in_tree('add','-u') - silent! edit! - 1 - if !search('^# Untracked files:$','W') - call search('^# Change','W') - endif - return '' - elseif line ==# '# Untracked files:' - call repo.git_chomp_in_tree('add','.') - silent! edit! - 1 - call search('^# Change','W') - return '' - endif - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (\a\+ [[:alpha:], ]\+)\)\=$') - if filename ==# '' - continue - endif - if !exists('first_filename') - let first_filename = filename - endif - execute lnum - let section = getline(search('^# .*:$','bnW')) - if line =~# '^#\trenamed:' && filename =~ ' -> ' - let cmd = ['mv','--'] + reverse(split(filename,' -> ')) - let filename = cmd[-1] - elseif section =~? ' to be ' - let cmd = ['reset','-q','--',filename] - elseif line =~# '^#\tdeleted:' - let cmd = ['rm','--',filename] - else - let cmd = ['add','--',filename] - endif - let output .= call(repo.git_chomp_in_tree,cmd,s:repo())."\n" - endfor - if exists('first_filename') - call s:StageReloadSeek(first_filename,a:lnum1,a:lnum2) - endif - echo s:sub(s:gsub(output,'\n+','\n'),'\n$','') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return 'checktime' -endfunction - -function! s:StagePatch(lnum1,lnum2) abort - let add = [] - let reset = [] - - for lnum in range(a:lnum1,a:lnum2) - let line = getline(lnum) - if line ==# '# Changes to be committed:' - return 'Git reset --patch' - elseif line =~# '^# Change\%(d but not updated\|s not staged for commit\):$' - return 'Git add --patch' - endif - let filename = matchstr(line,'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( (new commits)\)\=$') - if filename ==# '' - continue - endif - if !exists('first_filename') - let first_filename = filename - endif - execute lnum - let section = getline(search('^# .*:$','bnW')) - if line =~# '^#\trenamed:' && filename =~ ' -> ' - let reset += [split(filename,' -> ')[1]] - elseif section =~? ' to be ' - let reset += [filename] - elseif line !~# '^#\tdeleted:' - let add += [filename] - endif - endfor - try - if !empty(add) - execute "Git add --patch -- ".join(map(add,'s:shellesc(v:val)')) - endif - if !empty(reset) - execute "Git reset --patch -- ".join(map(add,'s:shellesc(v:val)')) - endif - if exists('first_filename') - silent! edit! - 1 - redraw - call search('^#\t\%([[:alpha:] ]\+: *\)\=\V'.first_filename.'\%( (new commits)\)\=\$','W') - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - return 'checktime' -endfunction - -" }}}1 -" Gcommit {{{1 - -call s:command("-nargs=? -complete=customlist,s:CommitComplete Gcommit :execute s:Commit(<q-args>)") - -function! s:Commit(args) abort - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - let msgfile = s:repo().dir('COMMIT_EDITMSG') - let outfile = tempname() - let errorfile = tempname() - try - execute cd.'`=s:repo().tree()`' - if &shell =~# 'cmd' - let command = '' - let old_editor = $GIT_EDITOR - let $GIT_EDITOR = 'false' - else - let command = 'env GIT_EDITOR=false ' - endif - let command .= s:repo().git_command('commit').' '.a:args - if &shell =~# 'csh' - silent execute '!('.command.' > '.outfile.') >& '.errorfile - elseif a:args =~# '\%(^\| \)--interactive\>' - execute '!'.command.' 2> '.errorfile - else - silent execute '!'.command.' > '.outfile.' 2> '.errorfile - endif - if !has('gui_running') - redraw! - endif - if !v:shell_error - if filereadable(outfile) - for line in readfile(outfile) - echo line - endfor - endif - return '' - else - let errors = readfile(errorfile) - let error = get(errors,-2,get(errors,-1,'!')) - if error =~# '\<false''\=\.$' - let args = a:args - let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-[se]|--edit|--interactive)%($| )','') - let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-F|--file|-m|--message)%(\s+|\=)%(''[^'']*''|"%(\\.|[^"])*"|\\.|\S)*','') - let args = s:gsub(args,'%(^| )@<=[%#]%(:\w)*','\=expand(submatch(0))') - let args = '-F '.s:shellesc(msgfile).' '.args - if args !~# '\%(^\| \)--cleanup\>' - let args = '--cleanup=strip '.args - endif - if bufname('%') == '' && line('$') == 1 && getline(1) == '' && !&mod - keepalt edit `=msgfile` - elseif s:buffer().type() ==# 'index' - keepalt edit `=msgfile` - execute (search('^#','n')+1).'wincmd+' - setlocal nopreviewwindow - else - keepalt split `=msgfile` - endif - let b:fugitive_commit_arguments = args - setlocal bufhidden=delete filetype=gitcommit - return '1' - elseif error ==# '!' - return s:Status() - else - call s:throw(error) - endif - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - finally - if exists('old_editor') - let $GIT_EDITOR = old_editor - endif - call delete(outfile) - call delete(errorfile) - execute cd.'`=dir`' - call fugitive#reload_status() - endtry -endfunction - -function! s:CommitComplete(A,L,P) abort - if a:A =~ '^-' || type(a:A) == type(0) " a:A is 0 on :Gcommit -<Tab> - let args = ['-C', '-F', '-a', '-c', '-e', '-i', '-m', '-n', '-o', '-q', '-s', '-t', '-u', '-v', '--all', '--allow-empty', '--amend', '--author=', '--cleanup=', '--dry-run', '--edit', '--file=', '--include', '--interactive', '--message=', '--no-verify', '--only', '--quiet', '--reedit-message=', '--reuse-message=', '--signoff', '--template=', '--untracked-files', '--verbose'] - return filter(args,'v:val[0 : strlen(a:A)-1] ==# a:A') - else - return s:repo().superglob(a:A) - endif -endfunction - -function! s:FinishCommit() - let args = getbufvar(+expand('<abuf>'),'fugitive_commit_arguments') - if !empty(args) - call setbufvar(+expand('<abuf>'),'fugitive_commit_arguments','') - return s:Commit(args) - endif - return '' -endfunction - -augroup fugitive_commit - autocmd! - autocmd VimLeavePre,BufDelete *.git/COMMIT_EDITMSG execute s:sub(s:FinishCommit(), '^echoerr (.*)', 'echohl ErrorMsg|echo \1|echohl NONE') -augroup END - -" }}}1 -" Ggrep, Glog {{{1 - -if !exists('g:fugitive_summary_format') - let g:fugitive_summary_format = '%s' -endif - -call s:command("-bang -nargs=? -complete=customlist,s:EditComplete Ggrep :execute s:Grep(<bang>0,<q-args>)") -call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Glog :execute s:Log('grep<bang>',<f-args>)") - -function! s:Grep(bang,arg) abort - let grepprg = &grepprg - let grepformat = &grepformat - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - let &grepprg = s:repo().git_command('--no-pager', 'grep', '-n') - let &grepformat = '%f:%l:%m' - exe 'grep! '.escape(matchstr(a:arg,'\v\C.{-}%($|[''" ]\@=\|)@='),'|') - let list = getqflist() - for entry in list - if bufname(entry.bufnr) =~ ':' - let entry.filename = s:repo().translate(bufname(entry.bufnr)) - unlet! entry.bufnr - elseif a:arg =~# '\%(^\| \)--cached\>' - let entry.filename = s:repo().translate(':0:'.bufname(entry.bufnr)) - unlet! entry.bufnr - endif - endfor - call setqflist(list,'r') - if !a:bang && !empty(list) - return 'cfirst'.matchstr(a:arg,'\v\C[''" ]\zs\|.*') - else - return matchstr(a:arg,'\v\C[''" ]\|\zs.*') - endif - finally - let &grepprg = grepprg - let &grepformat = grepformat - execute cd.'`=dir`' - endtry -endfunction - -function! s:Log(cmd,...) - let path = s:buffer().path('/') - if path =~# '^/\.git\%(/\|$\)' || index(a:000,'--') != -1 - let path = '' - endif - let cmd = ['--no-pager', 'log', '--no-color'] - let cmd += [escape('--pretty=format:fugitive://'.s:repo().dir().'//%H'.path.'::'.g:fugitive_summary_format,'%')] - if empty(filter(a:000[0 : index(a:000,'--')],'v:val !~# "^-"')) - if s:buffer().commit() =~# '\x\{40\}' - let cmd += [s:buffer().commit()] - elseif s:buffer().path() =~# '^\.git/refs/\|^\.git/.*HEAD$' - let cmd += [s:buffer().path()[5:-1]] - endif - end - let cmd += map(copy(a:000),'s:sub(v:val,"^\\%(%(:\\w)*)","\\=fnamemodify(s:buffer().path(),submatch(1))")') - if path =~# '/.' - let cmd += ['--',path[1:-1]] - endif - let grepformat = &grepformat - let grepprg = &grepprg - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - let &grepprg = call(s:repo().git_command,cmd,s:repo()) - let &grepformat = '%f::%m' - exe a:cmd - finally - let &grepformat = grepformat - let &grepprg = grepprg - execute cd.'`=dir`' - endtry -endfunction - -" }}}1 -" Gedit, Gpedit, Gsplit, Gvsplit, Gtabedit, Gread {{{1 - -function! s:Edit(cmd,bang,...) abort - if a:cmd !~# 'read' - if &previewwindow && getbufvar('','fugitive_type') ==# 'index' - wincmd p - if &diff - let mywinnr = winnr() - for winnr in range(winnr('$'),1,-1) - if winnr != mywinnr && getwinvar(winnr,'&diff') - execute winnr.'wincmd w' - close - wincmd p - endif - endfor - endif - endif - endif - - if a:bang - let args = s:gsub(a:0 ? a:1 : '', '\\@<!%(\\\\)*\zs[%#]', '\=s:buffer().expand(submatch(0))') - if a:cmd =~# 'read' - let git = s:repo().git_command() - let last = line('$') - silent call s:ExecuteInTree((a:cmd ==# 'read' ? '$read' : a:cmd).'!'.git.' --no-pager '.args) - if a:cmd ==# 'read' - silent execute '1,'.last.'delete_' - endif - call fugitive#reload_status() - diffupdate - return 'redraw|echo '.string(':!'.git.' '.args) - else - let temp = tempname() - let s:temp_files[temp] = s:repo().dir() - silent execute a:cmd.' '.temp - if a:cmd =~# 'pedit' - wincmd P - endif - let echo = s:Edit('read',1,args) - silent write! - setlocal buftype=nowrite nomodified filetype=git foldmarker=<<<<<<<,>>>>>>> - if getline(1) !~# '^diff ' - setlocal readonly nomodifiable - endif - if a:cmd =~# 'pedit' - wincmd p - endif - return echo - endif - return '' - endif - - if a:0 && a:1 == '' - return '' - elseif a:0 - let file = s:buffer().expand(a:1) - elseif expand('%') ==# '' - let file = ':' - elseif s:buffer().commit() ==# '' && s:buffer().path('/') !~# '^/.git\>' - let file = s:buffer().path(':') - else - let file = s:buffer().path('/') - endif - try - let file = s:repo().translate(file) - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - if a:cmd ==# 'read' - return 'silent %delete_|read '.s:fnameescape(file).'|silent 1delete_|diffupdate|'.line('.') - else - return a:cmd.' '.s:fnameescape(file) - endif -endfunction - -function! s:EditComplete(A,L,P) abort - return s:repo().superglob(a:A) -endfunction - -function! s:EditRunComplete(A,L,P) abort - if a:L =~# '^\w\+!' - return s:GitComplete(a:A,a:L,a:P) - else - return s:repo().superglob(a:A) - endif -endfunction - -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Ge :execute s:Edit('edit<bang>',0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gedit :execute s:Edit('edit<bang>',0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gpedit :execute s:Edit('pedit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gsplit :execute s:Edit('split',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gvsplit :execute s:Edit('vsplit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditRunComplete Gtabedit :execute s:Edit('tabedit',<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -count -complete=customlist,s:EditRunComplete Gread :execute s:Edit((!<count> && <line1> ? '' : <count>).'read',<bang>0,<f-args>)") - -" }}}1 -" Gwrite, Gwq {{{1 - -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gwrite :execute s:Write(<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gw :execute s:Write(<bang>0,<f-args>)") -call s:command("-bar -bang -nargs=? -complete=customlist,s:EditComplete Gwq :execute s:Wq(<bang>0,<f-args>)") - -function! s:Write(force,...) abort - if exists('b:fugitive_commit_arguments') - return 'write|bdelete' - elseif expand('%:t') == 'COMMIT_EDITMSG' && $GIT_INDEX_FILE != '' - return 'wq' - elseif s:buffer().type() == 'index' - return 'Gcommit' - elseif s:buffer().path() ==# '' && getline(4) =~# '^+++ ' - let filename = getline(4)[6:-1] - setlocal buftype= - silent write - setlocal buftype=nowrite - if matchstr(getline(2),'index [[:xdigit:]]\+\.\.\zs[[:xdigit:]]\{7\}') ==# s:repo().rev_parse(':0:'.filename)[0:6] - let err = s:repo().git_chomp('apply','--cached','--reverse',s:buffer().spec()) - else - let err = s:repo().git_chomp('apply','--cached',s:buffer().spec()) - endif - if err !=# '' - let v:errmsg = split(err,"\n")[0] - return 'echoerr v:errmsg' - elseif a:force - return 'bdelete' - else - return 'Gedit '.fnameescape(filename) - endif - endif - let mytab = tabpagenr() - let mybufnr = bufnr('') - let path = a:0 ? a:1 : s:buffer().path() - if path =~# '^:\d\>' - return 'write'.(a:force ? '! ' : ' ').s:fnameescape(s:repo().translate(s:buffer().expand(path))) - endif - let always_permitted = (s:buffer().path() ==# path && s:buffer().commit() =~# '^0\=$') - if !always_permitted && !a:force && s:repo().git_chomp_in_tree('diff','--name-status','HEAD','--',path) . s:repo().git_chomp_in_tree('ls-files','--others','--',path) !=# '' - let v:errmsg = 'fugitive: file has uncommitted changes (use ! to override)' - return 'echoerr v:errmsg' - endif - let file = s:repo().translate(path) - let treebufnr = 0 - for nr in range(1,bufnr('$')) - if fnamemodify(bufname(nr),':p') ==# file - let treebufnr = nr - endif - endfor - - if treebufnr > 0 && treebufnr != bufnr('') - let temp = tempname() - silent execute '%write '.temp - for tab in [mytab] + range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - if tabpagebuflist(tab)[winnr-1] == treebufnr - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - let lnum = line('.') - let last = line('$') - silent execute '$read '.temp - silent execute '1,'.last.'delete_' - silent write! - silent execute lnum - let did = 1 - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - endif - endfor - endfor - if !exists('did') - call writefile(readfile(temp,'b'),file,'b') - endif - else - execute 'write! '.s:fnameescape(s:repo().translate(path)) - endif - - if a:force - let error = s:repo().git_chomp_in_tree('add', '--force', file) - else - let error = s:repo().git_chomp_in_tree('add', file) - endif - if v:shell_error - let v:errmsg = 'fugitive: '.error - return 'echoerr v:errmsg' - endif - if s:buffer().path() ==# path && s:buffer().commit() =~# '^\d$' - set nomodified - endif - - let one = s:repo().translate(':1:'.path) - let two = s:repo().translate(':2:'.path) - let three = s:repo().translate(':3:'.path) - for nr in range(1,bufnr('$')) - if bufloaded(nr) && !getbufvar(nr,'&modified') && (bufname(nr) == one || bufname(nr) == two || bufname(nr) == three) - execute nr.'bdelete' - endif - endfor - - unlet! restorewinnr - let zero = s:repo().translate(':0:'.path) - for tab in range(1,tabpagenr('$')) - for winnr in range(1,tabpagewinnr(tab,'$')) - let bufnr = tabpagebuflist(tab)[winnr-1] - let bufname = bufname(bufnr) - if bufname ==# zero && bufnr != mybufnr - execute 'tabnext '.tab - if winnr != winnr() - execute winnr.'wincmd w' - let restorewinnr = 1 - endif - try - let lnum = line('.') - let last = line('$') - silent $read `=file` - silent execute '1,'.last.'delete_' - silent execute lnum - set nomodified - diffupdate - finally - if exists('restorewinnr') - wincmd p - endif - execute 'tabnext '.mytab - endtry - break - endif - endfor - endfor - call fugitive#reload_status() - return 'checktime' -endfunction - -function! s:Wq(force,...) abort - let bang = a:force ? '!' : '' - if exists('b:fugitive_commit_arguments') - return 'wq'.bang - endif - let result = call(s:function('s:Write'),[a:force]+a:000) - if result =~# '^\%(write\|wq\|echoerr\)' - return s:sub(result,'^write','wq') - else - return result.'|quit'.bang - endif -endfunction - -" }}}1 -" Gdiff {{{1 - -call s:command("-bang -bar -nargs=? -complete=customlist,s:EditComplete Gdiff :execute s:Diff(<bang>0,<f-args>)") -call s:command("-bar -nargs=? -complete=customlist,s:EditComplete Gvdiff :execute s:Diff(0,<f-args>)") -call s:command("-bar -nargs=? -complete=customlist,s:EditComplete Gsdiff :execute s:Diff(1,<f-args>)") - -augroup fugitive_diff - autocmd! - autocmd BufWinLeave * if s:diff_window_count() == 2 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff_all(getbufvar(+expand('<abuf>'), 'git_dir')) | endif - autocmd BufWinEnter * if s:diff_window_count() == 1 && &diff && getbufvar(+expand('<abuf>'), 'git_dir') !=# '' | call s:diffoff() | endif -augroup END - -function! s:diff_window_count() - let c = 0 - for nr in range(1,winnr('$')) - let c += getwinvar(nr,'&diff') - endfor - return c -endfunction - -function! s:diffthis() - if !&diff - let w:fugitive_diff_restore = 'setlocal nodiff noscrollbind' - let w:fugitive_diff_restore .= ' scrollopt=' . &l:scrollopt - let w:fugitive_diff_restore .= &l:wrap ? ' wrap' : ' nowrap' - let w:fugitive_diff_restore .= ' foldmethod=' . &l:foldmethod - let w:fugitive_diff_restore .= ' foldcolumn=' . &l:foldcolumn - diffthis - endif -endfunction - -function! s:diffoff() - if exists('w:fugitive_diff_restore') - execute w:fugitive_diff_restore - unlet w:fugitive_diff_restore - else - diffoff - endif -endfunction - -function! s:diffoff_all(dir) - for nr in range(1,winnr('$')) - if getwinvar(nr,'&diff') - if nr != winnr() - execute nr.'wincmd w' - let restorewinnr = 1 - endif - if exists('b:git_dir') && b:git_dir ==# a:dir - call s:diffoff() - endif - if exists('restorewinnr') - wincmd p - endif - endif - endfor -endfunction - -function! s:buffer_compare_age(commit) dict abort - let scores = {':0': 1, ':1': 2, ':2': 3, ':': 4, ':3': 5} - let my_score = get(scores,':'.self.commit(),0) - let their_score = get(scores,':'.a:commit,0) - if my_score || their_score - return my_score < their_score ? -1 : my_score != their_score - elseif self.commit() ==# a:commit - return 0 - endif - let base = self.repo().git_chomp('merge-base',self.commit(),a:commit) - if base ==# self.commit() - return -1 - elseif base ==# a:commit - return 1 - endif - let my_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',self.commit()) - let their_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',a:commit) - return my_time < their_time ? -1 : my_time != their_time -endfunction - -call s:add_methods('buffer',['compare_age']) - -function! s:Diff(bang,...) abort - let split = a:bang ? 'split' : 'vsplit' - if exists(':DiffGitCached') - return 'DiffGitCached' - elseif (!a:0 || a:1 == ':') && s:buffer().commit() =~# '^[0-1]\=$' && s:repo().git_chomp_in_tree('ls-files', '--unmerged', '--', s:buffer().path()) !=# '' - let nr = bufnr('') - execute 'leftabove '.split.' `=fugitive#buffer().repo().translate(s:buffer().expand('':2''))`' - execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>' - call s:diffthis() - wincmd p - execute 'rightbelow '.split.' `=fugitive#buffer().repo().translate(s:buffer().expand('':3''))`' - execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>' - call s:diffthis() - wincmd p - call s:diffthis() - return '' - elseif a:0 - if a:1 ==# '' - return '' - elseif a:1 ==# '/' - let file = s:buffer().path('/') - elseif a:1 ==# ':' - let file = s:buffer().path(':0:') - elseif a:1 =~# '^:/.' - try - let file = s:repo().rev_parse(a:1).s:buffer().path(':') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry - else - let file = s:buffer().expand(a:1) - endif - if file !~# ':' && file !~# '^/' && s:repo().git_chomp('cat-file','-t',file) =~# '^\%(tag\|commit\)$' - let file = file.s:buffer().path(':') - endif - else - let file = s:buffer().path(s:buffer().commit() == '' ? ':0:' : '/') - endif - try - let spec = s:repo().translate(file) - let commit = matchstr(spec,'\C[^:/]//\zs\x\+') - if s:buffer().compare_age(commit) < 0 - execute 'rightbelow '.split.' `=spec`' - else - execute 'leftabove '.split.' `=spec`' - endif - call s:diffthis() - wincmd p - call s:diffthis() - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -" }}}1 -" Gmove, Gremove {{{1 - -function! s:Move(force,destination) - if a:destination =~# '^/' - let destination = a:destination[1:-1] - else - let destination = fnamemodify(s:sub(a:destination,'[%#]%(:\w)*','\=expand(submatch(0))'),':p') - if destination[0:strlen(s:repo().tree())] ==# s:repo().tree('') - let destination = destination[strlen(s:repo().tree('')):-1] - endif - endif - if isdirectory(s:buffer().name()) - " Work around Vim parser idiosyncrasy - let discarded = s:buffer().setvar('&swapfile',0) - endif - let message = call(s:repo().git_chomp_in_tree,['mv']+(a:force ? ['-f'] : [])+['--', s:buffer().path(), destination], s:repo()) - if v:shell_error - let v:errmsg = 'fugitive: '.message - return 'echoerr v:errmsg' - endif - let destination = s:repo().tree(destination) - if isdirectory(destination) - let destination = fnamemodify(s:sub(destination,'/$','').'/'.expand('%:t'),':.') - endif - call fugitive#reload_status() - if s:buffer().commit() == '' - if isdirectory(destination) - return 'edit '.s:fnameescape(destination) - else - return 'saveas! '.s:fnameescape(destination) - endif - else - return 'file '.s:fnameescape(s:repo().translate(':0:'.destination) - endif -endfunction - -function! s:MoveComplete(A,L,P) - if a:A =~ '^/' - return s:repo().superglob(a:A) - else - let matches = split(glob(a:A.'*'),"\n") - call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val') - return matches - endif -endfunction - -function! s:Remove(force) - if s:buffer().commit() ==# '' - let cmd = ['rm'] - elseif s:buffer().commit() ==# '0' - let cmd = ['rm','--cached'] - else - let v:errmsg = 'fugitive: rm not supported here' - return 'echoerr v:errmsg' - endif - if a:force - let cmd += ['--force'] - endif - let message = call(s:repo().git_chomp_in_tree,cmd+['--',s:buffer().path()],s:repo()) - if v:shell_error - let v:errmsg = 'fugitive: '.s:sub(message,'error:.*\zs\n\(.*-f.*',' (add ! to force)') - return 'echoerr '.string(v:errmsg) - else - call fugitive#reload_status() - return 'bdelete'.(a:force ? '!' : '') - endif -endfunction - -augroup fugitive_remove - autocmd! - autocmd User Fugitive if s:buffer().commit() =~# '^0\=$' | - \ exe "command! -buffer -bar -bang -nargs=1 -complete=customlist,s:MoveComplete Gmove :execute s:Move(<bang>0,<q-args>)" | - \ exe "command! -buffer -bar -bang Gremove :execute s:Remove(<bang>0)" | - \ endif -augroup END - -" }}}1 -" Gblame {{{1 - -augroup fugitive_blame - autocmd! - autocmd BufReadPost *.fugitiveblame setfiletype fugitiveblame - autocmd FileType fugitiveblame setlocal nomodeline | if exists('b:git_dir') | let &l:keywordprg = s:repo().keywordprg() | endif - autocmd Syntax fugitiveblame call s:BlameSyntax() - autocmd User Fugitive if s:buffer().type('file', 'blob') | exe "command! -buffer -bar -bang -range=0 -nargs=* Gblame :execute s:Blame(<bang>0,<line1>,<line2>,<count>,[<f-args>])" | endif -augroup END - -function! s:Blame(bang,line1,line2,count,args) abort - try - if s:buffer().path() == '' - call s:throw('file or blob required') - endif - if filter(copy(a:args),'v:val !~# "^\\%(--root\|--show-name\\|-\\=\\%([ltwfs]\\|[MC]\\d*\\)\\+\\)$"') != [] - call s:throw('unsupported option') - endif - call map(a:args,'s:sub(v:val,"^\\ze[^-]","-")') - let cmd = ['--no-pager', 'blame', '--show-number'] + a:args - if s:buffer().commit() =~# '\D\|..' - let cmd += [s:buffer().commit()] - else - let cmd += ['--contents', '-'] - endif - let basecmd = escape(call(s:repo().git_command,cmd+['--',s:buffer().path()],s:repo()),'!') - try - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - if !s:repo().bare() - let dir = getcwd() - execute cd.'`=s:repo().tree()`' - endif - if a:count - execute 'write !'.substitute(basecmd,' blame ',' blame -L '.a:line1.','.a:line2.' ','g') - else - let error = tempname() - let temp = error.'.fugitiveblame' - if &shell =~# 'csh' - silent! execute '%write !('.basecmd.' > '.temp.') >& '.error - else - silent! execute '%write !'.basecmd.' > '.temp.' 2> '.error - endif - if exists('l:dir') - execute cd.'`=dir`' - unlet dir - endif - if v:shell_error - call s:throw(join(readfile(error),"\n")) - endif - let bufnr = bufnr('') - let restore = 'call setwinvar(bufwinnr('.bufnr.'),"&scrollbind",0)' - if &l:wrap - let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&wrap",1)' - endif - if &l:foldenable - let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&foldenable",1)' - endif - let winnr = winnr() - windo set noscrollbind - exe winnr.'wincmd w' - setlocal scrollbind nowrap nofoldenable - let top = line('w0') + &scrolloff - let current = line('.') - let s:temp_files[temp] = s:repo().dir() - exe 'leftabove vsplit '.temp - let b:fugitive_blamed_bufnr = bufnr - let w:fugitive_leave = restore - let b:fugitive_blame_arguments = join(a:args,' ') - execute top - normal! zt - execute current - execute "vertical resize ".(match(getline('.'),'\s\+\d\+)')+1) - setlocal nomodified nomodifiable nonumber scrollbind nowrap foldcolumn=0 nofoldenable filetype=fugitiveblame - if exists('+relativenumber') - setlocal norelativenumber - endif - nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>BlameJump('')<CR> - nnoremap <buffer> <silent> P :<C-U>exe <SID>BlameJump('^'.v:count1)<CR> - nnoremap <buffer> <silent> ~ :<C-U>exe <SID>BlameJump('~'.v:count1)<CR> - nnoremap <buffer> <silent> o :<C-U>exe <SID>Edit((&splitbelow ? "botright" : "topleft")." split", 0, matchstr(getline('.'),'\x\+'))<CR> - nnoremap <buffer> <silent> O :<C-U>exe <SID>Edit("tabedit", 0, matchstr(getline('.'),'\x\+'))<CR> - syncbind - endif - finally - if exists('l:dir') - execute cd.'`=dir`' - endif - endtry - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BlameJump(suffix) abort - let commit = matchstr(getline('.'),'^\^\=\zs\x\+') - if commit =~# '^0\+$' - let commit = ':0' - endif - let lnum = matchstr(getline('.'),'\d\+\ze\s\+[([:digit:]]') - let path = matchstr(getline('.'),'^\^\=\zs\x\+\s\+\zs.\{-\}\ze\s*\d\+ ') - if path ==# '' - let path = s:buffer(b:fugitive_blamed_bufnr).path() - endif - let args = b:fugitive_blame_arguments - let offset = line('.') - line('w0') - let bufnr = bufnr('%') - let winnr = bufwinnr(b:fugitive_blamed_bufnr) - if winnr > 0 - exe winnr.'wincmd w' - endif - execute s:Edit('edit', 0, commit.a:suffix.':'.path) - if winnr > 0 - exe bufnr.'bdelete' - endif - execute 'Gblame '.args - execute lnum - let delta = line('.') - line('w0') - offset - if delta > 0 - execute 'norm! 'delta."\<C-E>" - elseif delta < 0 - execute 'norm! '(-delta)."\<C-Y>" - endif - syncbind - return '' -endfunction - -function! s:BlameSyntax() abort - let b:current_syntax = 'fugitiveblame' - syn match FugitiveblameBoundary "^\^" - syn match FugitiveblameBlank "^\s\+\s\@=" nextgroup=FugitiveblameAnnotation,fugitiveblameOriginalFile,FugitiveblameOriginalLineNumber skipwhite - syn match FugitiveblameHash "\%(^\^\=\)\@<=\x\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite - syn match FugitiveblameUncommitted "\%(^\^\=\)\@<=0\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite - syn region FugitiveblameAnnotation matchgroup=FugitiveblameDelimiter start="(" end="\%( \d\+\)\@<=)" contained keepend oneline - syn match FugitiveblameTime "[0-9:/+-][0-9:/+ -]*[0-9:/+-]\%( \+\d\+)\)\@=" contained containedin=FugitiveblameAnnotation - syn match FugitiveblameLineNumber " \@<=\d\+)\@=" contained containedin=FugitiveblameAnnotation - syn match FugitiveblameOriginalFile " \%(\f\+\D\@<=\|\D\@=\f\+\)\%(\%(\s\+\d\+\)\=\s\%((\|\s*\d\+)\)\)\@=" contained nextgroup=FugitiveblameOriginalLineNumber,FugitiveblameAnnotation skipwhite - syn match FugitiveblameOriginalLineNumber " \@<=\d\+\%(\s(\)\@=" contained nextgroup=FugitiveblameAnnotation skipwhite - syn match FugitiveblameOriginalLineNumber " \@<=\d\+\%(\s\+\d\+)\)\@=" contained nextgroup=FugitiveblameShort skipwhite - syn match FugitiveblameShort "\d\+)" contained contains=FugitiveblameLineNumber - syn match FugitiveblameNotCommittedYet "(\@<=Not Committed Yet\>" contained containedin=FugitiveblameAnnotation - hi def link FugitiveblameBoundary Keyword - hi def link FugitiveblameHash Identifier - hi def link FugitiveblameUncommitted Function - hi def link FugitiveblameTime PreProc - hi def link FugitiveblameLineNumber Number - hi def link FugitiveblameOriginalFile String - hi def link FugitiveblameOriginalLineNumber Float - hi def link FugitiveblameShort FugitiveblameDelimiter - hi def link FugitiveblameDelimiter Delimiter - hi def link FugitiveblameNotCommittedYet Comment -endfunction - -" }}}1 -" Gbrowse {{{1 - -call s:command("-bar -bang -count=0 -nargs=? -complete=customlist,s:EditComplete Gbrowse :execute s:Browse(<bang>0,<line1>,<count>,<f-args>)") - -function! s:Browse(bang,line1,count,...) abort - try - let rev = a:0 ? substitute(a:1,'@[[:alnum:]_-]*\%(://.\{-\}\)\=$','','') : '' - if rev ==# '' - let expanded = s:buffer().rev() - elseif rev ==# ':' - let expanded = s:buffer().path('/') - else - let expanded = s:buffer().expand(rev) - endif - let full = s:repo().translate(expanded) - let commit = '' - if full =~# '^fugitive://' - let commit = matchstr(full,'://.*//\zs\w\+') - let path = matchstr(full,'://.*//\w\+\zs/.*') - if commit =~ '..' - let type = s:repo().git_chomp('cat-file','-t',commit.s:sub(path,'^/',':')) - else - let type = 'blob' - endif - let path = path[1:-1] - elseif s:repo().bare() - let path = '.git/' . full[strlen(s:repo().dir())+1:-1] - let type = '' - else - let path = full[strlen(s:repo().tree())+1:-1] - if path =~# '^\.git/' - let type = '' - elseif isdirectory(full) - let type = 'tree' - else - let type = 'blob' - endif - endif - if path =~# '^\.git/.*HEAD' && filereadable(s:repo().dir(path[5:-1])) - let body = readfile(s:repo().dir(path[5:-1]))[0] - if body =~# '^\x\{40\}$' - let commit = body - let type = 'commit' - let path = '' - elseif body =~# '^ref: refs/' - let path = '.git/' . matchstr(body,'ref: \zs.*') - endif - endif - - if a:0 && a:1 =~# '@[[:alnum:]_-]*\%(://.\{-\}\)\=$' - let remote = matchstr(a:1,'@\zs[[:alnum:]_-]\+\%(://.\{-\}\)\=$') - elseif path =~# '^\.git/refs/remotes/.' - let remote = matchstr(path,'^\.git/refs/remotes/\zs[^/]\+') - else - let remote = 'origin' - let branch = matchstr(rev,'^[[:alnum:]/._-]\+\ze[:^~@]') - if branch ==# '' && path =~# '^\.git/refs/\w\+/' - let branch = s:sub(path,'^\.git/refs/\w+/','') - endif - if filereadable(s:repo().dir('refs/remotes/'.branch)) - let remote = matchstr(branch,'[^/]\+') - let rev = rev[strlen(remote)+1:-1] - else - if branch ==# '' - let branch = matchstr(s:repo().head_ref(),'\<refs/heads/\zs.*') - endif - if branch != '' - let remote = s:repo().git_chomp('config','branch.'.branch.'.remote') - if remote =~# '^\.\=$' - let remote = 'origin' - elseif rev[0:strlen(branch)-1] ==# branch && rev[strlen(branch)] =~# '[:^~@]' - let rev = s:repo().git_chomp('config','branch.'.branch.'.merge')[11:-1] . rev[strlen(branch):-1] - endif - endif - endif - endif - - let raw = s:repo().git_chomp('config','remote.'.remote.'.url') - if raw ==# '' - let raw = remote - endif - - let url = s:github_url(s:repo(),raw,rev,commit,path,type,a:line1,a:count) - if url == '' - let url = s:instaweb_url(s:repo(),rev,commit,path,type,a:count ? a:line1 : 0) - endif - - if url == '' - call s:throw("Instaweb failed to start and '".remote."' is not a GitHub remote") - endif - - if a:bang - let @* = url - return 'echomsg '.string(url) - else - return 'echomsg '.string(url).'|call fugitive#buffer().repo().git_chomp("web--browse",'.string(url).')' - endif - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:github_url(repo,url,rev,commit,path,type,line1,line2) abort - let path = a:path - let repo_path = matchstr(a:url,'^\%(https\=://\|git://\|git@\)github\.com[/:]\zs.\{-\}\ze\%(\.git\)\=$') - if repo_path ==# '' - return '' - endif - let root = 'https://github.com/' . repo_path - if path =~# '^\.git/refs/heads/' - let branch = a:repo.git_chomp('config','branch.'.path[16:-1].'.merge')[11:-1] - if branch ==# '' - return root . '/commits/' . path[16:-1] - else - return root . '/commits/' . branch - endif - elseif path =~# '^\.git/refs/.' - return root . '/commits/' . matchstr(path,'[^/]\+$') - elseif path =~# '.git/\%(config$\|hooks\>\)' - return root . '/admin' - elseif path =~# '^\.git\>' - return root - endif - if a:rev =~# '^[[:alnum:]._-]\+:' - let commit = matchstr(a:rev,'^[^:]*') - elseif a:commit =~# '^\d\=$' - let local = matchstr(a:repo.head_ref(),'\<refs/heads/\zs.*') - let commit = a:repo.git_chomp('config','branch.'.local.'.merge')[11:-1] - if commit ==# '' - let commit = local - endif - else - let commit = a:commit - endif - if a:type == 'tree' - let url = s:sub(root . '/tree/' . commit . '/' . path,'/$','') - elseif a:type == 'blob' - let url = root . '/blob/' . commit . '/' . path - if a:line2 && a:line1 == a:line2 - let url .= '#L' . a:line1 - elseif a:line2 - let url .= '#L' . a:line1 . '-' . a:line2 - endif - elseif a:type == 'tag' - let commit = matchstr(getline(3),'^tag \zs.*') - let url = root . '/tree/' . commit - else - let url = root . '/commit/' . commit - endif - return url -endfunction - -function! s:instaweb_url(repo,rev,commit,path,type,...) abort - let output = a:repo.git_chomp('instaweb','-b','unknown') - if output =~# 'http://' - let root = matchstr(output,'http://.*').'/?p='.fnamemodify(a:repo.dir(),':t') - else - return '' - endif - if a:path =~# '^\.git/refs/.' - return root . ';a=shortlog;h=' . matchstr(a:path,'^\.git/\zs.*') - elseif a:path =~# '^\.git\>' - return root - endif - let url = root - if a:commit =~# '^\x\{40\}$' - if a:type ==# 'commit' - let url .= ';a=commit' - endif - let url .= ';h=' . a:repo.rev_parse(a:commit . (a:path == '' ? '' : ':' . a:path)) - else - if a:type ==# 'blob' - let tmp = tempname() - silent execute 'write !'.a:repo.git_command('hash-object','-w','--stdin').' > '.tmp - let url .= ';h=' . readfile(tmp)[0] - else - try - let url .= ';h=' . a:repo.rev_parse((a:commit == '' ? 'HEAD' : ':' . a:commit) . ':' . a:path) - catch /^fugitive:/ - call s:throw('fugitive: cannot browse uncommitted file') - endtry - endif - let root .= ';hb=' . matchstr(a:repo.head_ref(),'[^ ]\+$') - endif - if a:path !=# '' - let url .= ';f=' . a:path - endif - if a:0 && a:1 - let url .= '#l' . a:1 - endif - return url -endfunction - -" }}}1 -" File access {{{1 - -function! s:ReplaceCmd(cmd,...) abort - let fn = bufname('') - let tmp = tempname() - let prefix = '' - try - if a:0 && a:1 != '' - if &shell =~# 'cmd' - let old_index = $GIT_INDEX_FILE - let $GIT_INDEX_FILE = a:1 - else - let prefix = 'env GIT_INDEX_FILE='.s:shellesc(a:1).' ' - endif - endif - if &shell =~# 'cmd' - call system('cmd /c "'.prefix.a:cmd.' > '.tmp.'"') - else - call system(' ('.prefix.a:cmd.' > '.tmp.') ') - endif - finally - if exists('old_index') - let $GIT_INDEX_FILE = old_index - endif - endtry - silent exe 'keepalt file '.tmp - silent edit! - silent exe 'keepalt file '.s:fnameescape(fn) - call delete(tmp) - if bufname('$') == tmp - silent execute 'bwipeout '.bufnr('$') - endif - silent exe 'doau BufReadPost '.s:fnameescape(fn) -endfunction - -function! s:BufReadIndex() - if !exists('b:fugitive_display_format') - let b:fugitive_display_format = filereadable(expand('%').'.lock') - endif - let b:fugitive_display_format = b:fugitive_display_format % 2 - let b:fugitive_type = 'index' - try - let b:git_dir = s:repo().dir() - setlocal noro ma - if fnamemodify($GIT_INDEX_FILE !=# '' ? $GIT_INDEX_FILE : b:git_dir . '/index', ':p') ==# expand('%:p') - let index = '' - else - let index = expand('%:p') - endif - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('ls-files','--stage'),index) - set ft=git nospell - else - let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd ' - let dir = getcwd() - try - execute cd.'`=s:repo().tree()`' - call s:ReplaceCmd(s:repo().git_command('status'),index) - finally - execute cd.'`=dir`' - endtry - set ft=gitcommit - endif - setlocal ro noma nomod nomodeline bufhidden=wipe - call s:JumpInit() - nunmap <buffer> P - nunmap <buffer> ~ - nnoremap <buffer> <silent> <C-N> :call search('^#\t.*','W')<Bar>.<CR> - nnoremap <buffer> <silent> <C-P> :call search('^#\t.*','Wbe')<Bar>.<CR> - nnoremap <buffer> <silent> - :<C-U>execute <SID>StageToggle(line('.'),line('.')+v:count1-1)<CR> - xnoremap <buffer> <silent> - :<C-U>execute <SID>StageToggle(line("'<"),line("'>"))<CR> - nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += 1<Bar>exe <SID>BufReadIndex()<CR> - nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= 1<Bar>exe <SID>BufReadIndex()<CR> - nnoremap <buffer> <silent> C :<C-U>Gcommit<CR> - nnoremap <buffer> <silent> cA :<C-U>Gcommit --amend --reuse-message=HEAD<CR> - nnoremap <buffer> <silent> ca :<C-U>Gcommit --amend<CR> - nnoremap <buffer> <silent> cc :<C-U>Gcommit<CR> - nnoremap <buffer> <silent> D :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> dd :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> dh :<C-U>execute <SID>StageDiff('Gsdiff')<CR> - nnoremap <buffer> <silent> ds :<C-U>execute <SID>StageDiff('Gsdiff')<CR> - nnoremap <buffer> <silent> dp :<C-U>execute <SID>StageDiffEdit()<CR> - nnoremap <buffer> <silent> dv :<C-U>execute <SID>StageDiff('Gvdiff')<CR> - nnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line('.'),line('.')+v:count1-1)<CR> - xnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line("'<"),line("'>"))<CR> - nnoremap <buffer> <silent> q :<C-U>if bufnr('$') == 1<Bar>quit<Bar>else<Bar>bdelete<Bar>endif<CR> - nnoremap <buffer> <silent> R :<C-U>edit<CR> - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:FileRead() - try - let repo = s:repo(s:ExtractGitDir(expand('<amatch>'))) - let path = s:sub(s:sub(matchstr(expand('<amatch>'),'fugitive://.\{-\}//\zs.*'),'/',':'),'^\d:',':&') - let hash = repo.rev_parse(path) - if path =~ '^:' - let type = 'blob' - else - let type = repo.git_chomp('cat-file','-t',hash) - endif - " TODO: use count, if possible - return "read !".escape(repo.git_command('cat-file',type,hash),'%#\') - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BufReadIndexFile() - try - let b:fugitive_type = 'blob' - let b:git_dir = s:repo().dir() - call s:ReplaceCmd(s:repo().git_command('cat-file','blob',s:buffer().sha1())) - if &bufhidden ==# '' - setlocal bufhidden=delete - endif - return '' - catch /^fugitive: rev-parse/ - silent exe 'doau BufNewFile '.s:fnameescape(bufname('')) - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -function! s:BufWriteIndexFile() - let tmp = tempname() - try - let path = matchstr(expand('<amatch>'),'//\d/\zs.*') - let stage = matchstr(expand('<amatch>'),'//\zs\d') - silent execute 'write !'.s:repo().git_command('hash-object','-w','--stdin').' > '.tmp - let sha1 = readfile(tmp)[0] - let old_mode = matchstr(s:repo().git_chomp('ls-files','--stage',path),'^\d\+') - if old_mode == '' - let old_mode = executable(s:repo().tree(path)) ? '100755' : '100644' - endif - let info = old_mode.' '.sha1.' '.stage."\t".path - call writefile([info],tmp) - if has('win32') - let error = system('type '.tmp.'|'.s:repo().git_command('update-index','--index-info')) - else - let error = system(s:repo().git_command('update-index','--index-info').' < '.tmp) - endif - if v:shell_error == 0 - setlocal nomodified - silent execute 'doautocmd BufWritePost '.s:fnameescape(expand('%:p')) - call fugitive#reload_status() - return '' - else - return 'echoerr '.string('fugitive: '.error) - endif - finally - call delete(tmp) - endtry -endfunction - -function! s:BufReadObject() - try - setlocal noro ma - let b:git_dir = s:repo().dir() - let hash = s:buffer().sha1() - if !exists("b:fugitive_type") - let b:fugitive_type = s:repo().git_chomp('cat-file','-t',hash) - endif - if b:fugitive_type !~# '^\%(tag\|commit\|tree\|blob\)$' - return "echoerr 'fugitive: unrecognized git type'" - endif - let firstline = getline('.') - if !exists('b:fugitive_display_format') && b:fugitive_type != 'blob' - let b:fugitive_display_format = +getbufvar('#','fugitive_display_format') - endif - - let pos = getpos('.') - silent %delete - setlocal endofline - - if b:fugitive_type == 'tree' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('ls-tree',hash)) - else - call s:ReplaceCmd(s:repo().git_command('show','--no-color',hash)) - endif - elseif b:fugitive_type == 'tag' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - else - call s:ReplaceCmd(s:repo().git_command('cat-file','-p',hash)) - endif - elseif b:fugitive_type == 'commit' - let b:fugitive_display_format = b:fugitive_display_format % 2 - if b:fugitive_display_format - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - else - call s:ReplaceCmd(s:repo().git_command('show','--no-color','--pretty=format:tree %T%nparent %P%nauthor %an <%ae> %ad%ncommitter %cn <%ce> %cd%nencoding %e%n%n%s%n%n%b',hash)) - call search('^parent ') - if getline('.') ==# 'parent ' - silent delete_ - else - silent s/\%(^parent\)\@<! /\rparent /ge - endif - if search('^encoding \%(<unknown>\)\=$','W',line('.')+3) - silent delete_ - end - 1 - endif - elseif b:fugitive_type ==# 'blob' - call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash)) - endif - call setpos('.',pos) - setlocal ro noma nomod nomodeline - if &bufhidden ==# '' - setlocal bufhidden=delete - endif - if b:fugitive_type !=# 'blob' - set filetype=git - nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += v:count1<Bar>exe <SID>BufReadObject()<CR> - nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= v:count1<Bar>exe <SID>BufReadObject()<CR> - else - call s:JumpInit() - endif - - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -augroup fugitive_files - autocmd! - autocmd BufReadCmd *.git/index exe s:BufReadIndex() - autocmd BufReadCmd *.git/*index*.lock exe s:BufReadIndex() - autocmd FileReadCmd fugitive://**//[0-3]/** exe s:FileRead() - autocmd BufReadCmd fugitive://**//[0-3]/** exe s:BufReadIndexFile() - autocmd BufWriteCmd fugitive://**//[0-3]/** exe s:BufWriteIndexFile() - autocmd BufReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:BufReadObject() - autocmd FileReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:FileRead() - autocmd FileType git call s:JumpInit() -augroup END - -" }}}1 -" Temp files {{{1 - -let s:temp_files = {} - -augroup fugitive_temp - autocmd! - autocmd BufNewFile,BufReadPost * - \ if has_key(s:temp_files,expand('<amatch>:p')) | - \ let b:git_dir = s:temp_files[expand('<amatch>:p')] | - \ let b:git_type = 'temp' | - \ call s:Detect(expand('<amatch>:p')) | - \ setlocal bufhidden=delete | - \ nnoremap <buffer> <silent> q :<C-U>bdelete<CR> | - \ endif -augroup END - -" }}}1 -" Go to file {{{1 - -function! s:JumpInit() abort - nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>GF("edit")<CR> - if !&modifiable - nnoremap <buffer> <silent> o :<C-U>exe <SID>GF("split")<CR> - nnoremap <buffer> <silent> O :<C-U>exe <SID>GF("tabedit")<CR> - nnoremap <buffer> <silent> P :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'^'.v:count1.<SID>buffer().path(':'))<CR> - nnoremap <buffer> <silent> ~ :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'~'.v:count1.<SID>buffer().path(':'))<CR> - nnoremap <buffer> <silent> C :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cc :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> co :<C-U>exe <SID>Edit('split',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cO :<C-U>exe <SID>Edit('tabedit',0,<SID>buffer().containing_commit())<CR> - nnoremap <buffer> <silent> cp :<C-U>exe <SID>Edit('pedit',0,<SID>buffer().containing_commit())<CR> - endif -endfunction - -function! s:GF(mode) abort - try - let buffer = s:buffer() - let myhash = buffer.sha1() - if myhash ==# '' && getline(1) =~# '^\%(commit\|tag\) \w' - let myhash = matchstr(getline(1),'^\w\+ \zs\S\+') - endif - - if buffer.type('tree') - let showtree = (getline(1) =~# '^tree ' && getline(2) == "") - if showtree && line('.') == 1 - return "" - elseif showtree && line('.') > 2 - return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(getline('.'),'/$','')) - elseif getline('.') =~# '^\d\{6\} \l\{3,8\} \x\{40\}\t' - return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(matchstr(getline('.'),'\t\zs.*'),'/$','')) - endif - - elseif buffer.type('blob') - let ref = expand("<cfile>") - try - let sha1 = buffer.repo().rev_parse(ref) - catch /^fugitive:/ - endtry - if exists('sha1') - return s:Edit(a:mode,0,ref) - endif - - else - - " Index - if getline('.') =~# '^\d\{6\} \x\{40\} \d\t' - let ref = matchstr(getline('.'),'\x\{40\}') - let file = ':'.s:sub(matchstr(getline('.'),'\d\t.*'),'\t',':') - return s:Edit(a:mode,0,file) - - elseif getline('.') =~# '^#\trenamed:.* -> ' - let file = '/'.matchstr(getline('.'),' -> \zs.*') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# '^#\t[[:alpha:] ]\+: *.' - let file = '/'.matchstr(getline('.'),': *\zs.\{-\}\ze\%( (new commits)\)\=$') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# '^#\t.' - let file = '/'.matchstr(getline('.'),'#\t\zs.*') - return s:Edit(a:mode,0,file) - elseif getline('.') =~# ': needs merge$' - let file = '/'.matchstr(getline('.'),'.*\ze: needs merge$') - return s:Edit(a:mode,0,file).'|Gdiff' - - elseif getline('.') ==# '# Not currently on any branch.' - return s:Edit(a:mode,0,'HEAD') - elseif getline('.') =~# '^# On branch ' - let file = 'refs/heads/'.getline('.')[12:] - return s:Edit(a:mode,0,file) - elseif getline('.') =~# "^# Your branch .*'" - let file = matchstr(getline('.'),"'\\zs\\S\\+\\ze'") - return s:Edit(a:mode,0,file) - endif - - let showtree = (getline(1) =~# '^tree ' && getline(2) == "") - - if getline('.') =~# '^ref: ' - let ref = strpart(getline('.'),5) - - elseif getline('.') =~# '^commit \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~# '^parent \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - let line = line('.') - let parent = 0 - while getline(line) =~# '^parent ' - let parent += 1 - let line -= 1 - endwhile - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~ '^tree \x\{40\}$' - let ref = matchstr(getline('.'),'\x\{40\}') - if s:repo().rev_parse(myhash.':') == ref - let ref = myhash.':' - endif - return s:Edit(a:mode,0,ref) - - elseif getline('.') =~# '^object \x\{40\}$' && getline(line('.')+1) =~ '^type \%(commit\|tree\|blob\)$' - let ref = matchstr(getline('.'),'\x\{40\}') - let type = matchstr(getline(line('.')+1),'type \zs.*') - - elseif getline('.') =~# '^\l\{3,8\} '.myhash.'$' - return '' - - elseif getline('.') =~# '^\l\{3,8\} \x\{40\}\>' - let ref = matchstr(getline('.'),'\x\{40\}') - echoerr "warning: unknown context ".matchstr(getline('.'),'^\l*') - - elseif getline('.') =~# '^[+-]\{3\} [ab/]' - let ref = getline('.')[4:] - - elseif getline('.') =~# '^rename from ' - let ref = 'a/'.getline('.')[12:] - elseif getline('.') =~# '^rename to ' - let ref = 'b/'.getline('.')[10:] - - elseif getline('.') =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)' - let dref = matchstr(getline('.'),'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)') - let ref = matchstr(getline('.'),'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)') - let dcmd = 'Gdiff' - - elseif getline('.') =~# '^index ' && getline(line('.')-1) =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)' - let line = getline(line('.')-1) - let dref = matchstr(line,'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)') - let ref = matchstr(line,'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)') - let dcmd = 'Gdiff!' - - elseif line('$') == 1 && getline('.') =~ '^\x\{40\}$' - let ref = getline('.') - else - let ref = '' - endif - - if myhash ==# '' - let ref = s:sub(ref,'^a/','HEAD:') - let ref = s:sub(ref,'^b/',':0:') - if exists('dref') - let dref = s:sub(dref,'^a/','HEAD:') - endif - else - let ref = s:sub(ref,'^a/',myhash.'^:') - let ref = s:sub(ref,'^b/',myhash.':') - if exists('dref') - let dref = s:sub(dref,'^a/',myhash.'^:') - endif - endif - - if ref ==# '/dev/null' - " Empty blob - let ref = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391' - endif - - if exists('dref') - return s:Edit(a:mode,0,ref) . '|'.dcmd.' '.s:fnameescape(dref) - elseif ref != "" - return s:Edit(a:mode,0,ref) - endif - - endif - return '' - catch /^fugitive:/ - return 'echoerr v:errmsg' - endtry -endfunction - -" }}}1 -" Statusline {{{1 - -function! s:repo_head_ref() dict abort - return readfile(s:repo().dir('HEAD'))[0] -endfunction - -call s:add_methods('repo',['head_ref']) - -function! fugitive#statusline(...) - if !exists('b:git_dir') - return '' - endif - let status = '' - if s:buffer().commit() != '' - let status .= ':' . s:buffer().commit()[0:7] - endif - let head = s:repo().head_ref() - if head =~# '^ref: ' - let status .= s:sub(head,'^ref: %(refs/%(heads/|remotes/|tags/)=)=','(').')' - elseif head =~# '^\x\{40\}$' - let status .= '('.head[0:7].')' - endif - if &statusline =~# '%[MRHWY]' && &statusline !~# '%[mrhwy]' - return ',GIT'.status - else - return '[Git'.status.']' - endif -endfunction - -" }}}1 - -" vim:set ft=vim ts=8 sw=2 sts=2: diff --git a/vim/plugin/gist.vim b/vim/plugin/gist.vim deleted file mode 100644 index 9081d00..0000000 --- a/vim/plugin/gist.vim +++ /dev/null @@ -1,826 +0,0 @@ -"============================================================================= -" File: gist.vim -" Author: Yasuhiro Matsumoto <mattn.jp@gmail.com> -" Last Change: 20-Aug-2011. -" Version: 5.0 -" WebPage: http://github.com/mattn/gist-vim -" License: BSD -" Usage: -" -" :Gist -" post current buffer to gist, using default privicy option -" (see g:gist_private) -" -" :'<,'>Gist -" post selected text to gist., using default privicy option -" This applies to all permutations listed below (except multi) -" (see g:gist_private) -" -" :Gist -p -" create a private gist -" -" :Gist -P -" create a public gist -" (only relevant if you've set gists to be private by default) -" -" :Gist -P -" post whole text to gist as public -" This is only relevant if you've set gists to be private by default -" :Gist -a -" create a gist anonymously -" -" :Gist -m -" create a gist with all open buffers -" -" :Gist -e -" edit the gist. (you need to have opend the gist buffer first) -" you can update the gist with :w command on gist buffer -" -" :Gist -d -" delete the gist. (you need to have opend the gist buffer first) -" password authentication is needed -" -" :Gist -f -" fork the gist. (you need to have opend the gist buffer first) -" password authentication is needed -" -" :Gist -e foo.js -" edit the gist with name 'foo.js'. (you need to have opend the gist buffer first) -" -" :Gist XXXXX -" get gist XXXXX -" -" :Gist -c XXXXX -" get gist XXXXX and add to clipboard -" -" :Gist -l -" list your public gists -" -" :Gist -l mattn -" list gists from mattn -" -" :Gist -la -" list all your (public and private) gists -" -" Tips: -" * if set g:gist_clip_command, gist.vim will copy the gist code -" with option '-c'. -" -" # mac -" let g:gist_clip_command = 'pbcopy' -" -" # linux -" let g:gist_clip_command = 'xclip -selection clipboard' -" -" # others(cygwin?) -" let g:gist_clip_command = 'putclip' -" -" * if you want to detect filetype from gist's filename... -" -" # detect filetype if vim failed auto-detection. -" let g:gist_detect_filetype = 1 -" -" # detect filetype always. -" let g:gist_detect_filetype = 2 -" -" * if you want to open browser after the post... -" -" let g:gist_open_browser_after_post = 1 -" -" * if you want to change the browser... -" -" let g:gist_browser_command = 'w3m %URL%' -" -" or -" -" let g:gist_browser_command = 'opera %URL% &' -" -" on windows, should work with original setting. -" -" * if you want to show your private gists with ':Gist -l' -" -" let g:gist_show_privates = 1 -" -" * if don't you want to copy URL of the post... -" -" let g:gist_put_url_to_clipboard_after_post = 0 -" -" or if you want to copy URL and add linefeed at the last of URL, -" -" let g:gist_put_url_to_clipboard_after_post = 2 -" -" default value is 1. -" -" Thanks: -" MATSUU Takuto: -" removed carriage return -" gist_browser_command enhancement -" edit support -" -" GetLatestVimScripts: 2423 1 :AutoInstall: gist.vim -" script type: plugin - -if &cp || (exists('g:loaded_gist_vim') && g:loaded_gist_vim) - finish -endif -let g:loaded_gist_vim = 1 - -if (!exists('g:github_user') || !exists('g:github_token')) && !executable('git') - echohl ErrorMsg | echomsg "Gist: require 'git' command" | echohl None - finish -endif - -if !executable('curl') - echohl ErrorMsg | echomsg "Gist: require 'curl' command" | echohl None - finish -endif - -if !exists('g:gist_open_browser_after_post') - let g:gist_open_browser_after_post = 0 -endif - -if !exists('g:gist_put_url_to_clipboard_after_post') - let g:gist_put_url_to_clipboard_after_post = 1 -endif - -if !exists('g:gist_curl_options') - let g:gist_curl_options = "" -endif - -if !exists('g:gist_browser_command') - if has('win32') || has('win64') - let g:gist_browser_command = "!start rundll32 url.dll,FileProtocolHandler %URL%" - elseif has('mac') - let g:gist_browser_command = "open %URL%" - elseif executable('xdg-open') - let g:gist_browser_command = "xdg-open %URL%" - else - let g:gist_browser_command = "firefox %URL% &" - endif -endif - -if !exists('g:gist_detect_filetype') - let g:gist_detect_filetype = 0 -endif - -if !exists('g:gist_private') - let g:gist_private = 0 -endif - -if !exists('g:gist_show_privates') - let g:gist_show_privates = 0 -endif - -if !exists('g:gist_cookie_dir') - let g:gist_cookie_dir = substitute(expand('<sfile>:p:h'), '[/\\]plugin$', '', '').'/cookies' -endif - -function! s:nr2hex(nr) - let n = a:nr - let r = "" - while n - let r = '0123456789ABCDEF'[n % 16] . r - let n = n / 16 - endwhile - return r -endfunction - -function! s:encodeURIComponent(instr) - let instr = iconv(a:instr, &enc, "utf-8") - let len = strlen(instr) - let i = 0 - let outstr = '' - while i < len - let ch = instr[i] - if ch =~# '[0-9A-Za-z-._~!''()*]' - let outstr = outstr . ch - elseif ch == ' ' - let outstr = outstr . '+' - else - let outstr = outstr . '%' . substitute('0' . s:nr2hex(char2nr(ch)), '^.*\(..\)$', '\1', '') - endif - let i = i + 1 - endwhile - return outstr -endfunction - -" Note: A colon in the file name has side effects on Windows due to NTFS Alternate Data Streams; avoid it. -let s:bufprefix = 'gist' . (has('unix') ? ':' : '_') -function! s:GistList(user, token, gistls, page) - if a:gistls == '-all' - let url = 'https://gist.github.com/gists' - elseif g:gist_show_privates && a:gistls == a:user - let url = 'https://gist.github.com/mine' - else - let url = 'https://gist.github.com/'.a:gistls - endif - let winnum = bufwinnr(bufnr(s:bufprefix.a:gistls)) - if winnum != -1 - if winnum != bufwinnr('%') - exe winnum 'wincmd w' - endif - setlocal modifiable - else - exec 'silent split' s:bufprefix.a:gistls - endif - if a:page > 1 - let oldlines = getline(0, line('$')) - let url = url . '?page=' . a:page - endif - - setlocal foldmethod=manual - let oldlines = [] - if g:gist_show_privates - echon 'Login to gist... ' - silent %d _ - let res = s:GistGetPage(url, a:user, '', '-L') - silent put =res.content - else - silent %d _ - exec 'silent r! curl -s' g:gist_curl_options url - endif - - 1delete _ - silent! %s/>/>\r/g - silent! %s/</\r</g - silent! %g/<pre/,/<\/pre/join! - silent! %g/<span class="date"/,/<\/span/join - silent! %g/^<span class="date"/s/> */>/g - silent! %v/^\(gist:\|<pre>\|<span class="date">\)/d _ - silent! %s/<div[^>]*>/\r /g - silent! %s/<\/pre>/\r/g - silent! %g/^gist:/,/<span class="date"/join - silent! %s/<[^>]\+>//g - silent! %s/\r//g - silent! %s/ / /g - silent! %s/"/"/g - silent! %s/&/\&/g - silent! %s/>/>/g - silent! %s/</</g - silent! %s/&#\(\d\d\);/\=nr2char(submatch(1))/g - silent! %g/^gist: /s/ //g - - call append(0, oldlines) - $put='more...' - - let b:user = a:user - let b:token = a:token - let b:gistls = a:gistls - let b:page = a:page - setlocal buftype=nofile bufhidden=hide noswapfile - setlocal nomodified - syntax match SpecialKey /^gist:/he=e-1 - nnoremap <silent> <buffer> <cr> :call <SID>GistListAction()<cr> - - cal cursor(1+len(oldlines),1) - setlocal foldmethod=expr - setlocal foldexpr=getline(v:lnum)=~'^\\(gist:\\\|more\\)'?'>1':'=' - setlocal foldtext=getline(v:foldstart) -endfunction - -function! s:GistGetFileName(gistid) - let url = 'https://gist.github.com/'.a:gistid - let res = system('curl -s '.g:gist_curl_options.' '.url) - let res = substitute(res, '^.*<a href="/raw/[^"]\+/\([^"]\+\)".*$', '\1', '') - if res =~ '/' - return '' - else - return res - endif -endfunction - -function! s:GistDetectFiletype(gistid) - let url = 'https://gist.github.com/'.a:gistid - let mx = '^.*<div class=".\{-}type-\([^"]\+\)">.*$' - let res = system('curl -s '.g:gist_curl_options.' '.url) - let res = substitute(matchstr(res, mx), mx, '\1', '') - let res = substitute(res, '.*\(\.[^\.]\+\)$', '\1', '') - let res = substitute(res, '-', '', 'g') - " TODO: more filetype detection that is specified in html. - if res == 'bat' | let res = 'dosbatch' | endif - if res == 'as' | let res = 'actionscript' | endif - if res == 'bash' | let res = 'sh' | endif - if res == 'cl' | let res = 'lisp' | endif - if res == 'rb' | let res = 'ruby' | endif - if res == 'viml' | let res = 'vim' | endif - if res == 'plain' || res == 'text' | let res = '' | endif - - if res =~ '^\.' - silent! exec "doau BufRead *".res - else - silent! exec "setlocal ft=".tolower(res) - endif -endfunction - -function! s:GistWrite(fname) - if substitute(a:fname, '\\', '/', 'g') == expand("%:p:gs@\\@/@") - Gist -e - else - exe "w".(v:cmdbang ? "!" : "") fnameescape(v:cmdarg) fnameescape(a:fname) - silent! exe "file" fnameescape(a:fname) - silent! au! BufWriteCmd <buffer> - endif -endfunction - -function! s:GistGet(user, token, gistid, clipboard) - let url = 'https://raw.github.com/gist/'.a:gistid - let winnum = bufwinnr(bufnr(s:bufprefix.a:gistid)) - if winnum != -1 - if winnum != bufwinnr('%') - exe winnum 'wincmd w' - endif - setlocal modifiable - else - exec 'silent split' s:bufprefix.a:gistid - endif - filetype detect - silent %d _ - exec 'silent 0r! curl -s' g:gist_curl_options url - $delete _ - setlocal buftype=acwrite bufhidden=delete noswapfile - setlocal nomodified - doau StdinReadPost <buffer> - if (&ft == '' && g:gist_detect_filetype == 1) || g:gist_detect_filetype == 2 - call s:GistDetectFiletype(a:gistid) - endif - if a:clipboard - if exists('g:gist_clip_command') - exec 'silent w !'.g:gist_clip_command - else - %yank + - endif - endif - 1 - au! BufWriteCmd <buffer> call s:GistWrite(expand("<amatch>")) -endfunction - -function! s:GistListAction() - let line = getline('.') - let mx = '^gist:\(\w\+\).*' - if line =~# mx - let gistid = substitute(line, mx, '\1', '') - call s:GistGet(g:github_user, g:github_token, gistid, 0) - return - endif - if line =~# '^more\.\.\.$' - delete - call s:GistList(b:user, b:token, b:gistls, b:page+1) - return - endif -endfunction - -function! s:GistUpdate(user, token, content, gistid, gistnm) - if len(a:gistnm) == 0 - let name = s:GistGetFileName(a:gistid) - else - let name = a:gistnm - endif - let namemx = '^[^.]\+\(.\+\)$' - let ext = '' - if name =~ namemx - let ext = substitute(name, namemx, '\1', '') - endif - let query = [ - \ '_method=put', - \ 'file_ext[gistfile1%s]=%s', - \ 'file_name[gistfile1%s]=%s', - \ 'file_contents[gistfile1%s]=%s', - \ 'login=%s', - \ 'token=%s', - \ ] - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(ext), s:encodeURIComponent(ext), - \ s:encodeURIComponent(ext), s:encodeURIComponent(name), - \ s:encodeURIComponent(ext), s:encodeURIComponent(a:content), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) - unlet query - - let file = tempname() - call writefile([squery], file) - echon 'Updating it to gist... ' - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists/'.a:gistid - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let headers = split(res, '\(\r\?\n\|\r\n\?\)') - let location = matchstr(headers, '^Location: ') - let location = substitute(location, '^[^:]\+: ', '', '') - if len(location) > 0 && location =~ '^\(http\|https\):\/\/gist\.github\.com\/' - setlocal nomodified - redraw - echo 'Done: '.location - else - let message = matchstr(headers, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Edit failed: '.message | echohl None - endif - return location -endfunction - -function! s:GistGetPage(url, user, param, opt) - if !isdirectory(g:gist_cookie_dir) - call mkdir(g:gist_cookie_dir, 'p') - endif - let cookie_file = g:gist_cookie_dir.'/github' - - if len(a:url) == 0 - call delete(cookie_file) - return - endif - - let quote = &shellxquote == '"' ? "'" : '"' - if !filereadable(cookie_file) - let password = inputsecret('Password:') - if len(password) == 0 - echo 'Canceled' - return - endif - let url = 'https://gist.github.com/login?return_to=gist' - let res = system('curl -L -s '.g:gist_curl_options.' -c '.quote.cookie_file.quote.' '.quote.url.quote) - let token = substitute(res, '^.* name="authenticity_token" type="hidden" value="\([^"]\+\)".*$', '\1', '') - - let query = [ - \ 'authenticity_token=%s', - \ 'login=%s', - \ 'password=%s', - \ 'return_to=gist', - \ 'commit=Log+in', - \ ] - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(token), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(password)) - unlet query - - let file = tempname() - let command = 'curl -s '.g:gist_curl_options.' -i' - let command .= ' -b '.quote.cookie_file.quote - let command .= ' -c '.quote.cookie_file.quote - let command .= ' '.quote.'https://gist.github.com/session'.quote - let command .= ' -d @' . quote.file.quote - call writefile([squery], file) - let res = system(command) - call delete(file) - let res = matchstr(split(res, '\(\r\?\n\|\r\n\?\)'), '^Location: ') - let res = substitute(res, '^[^:]\+: ', '', '') - if len(res) == 0 - call delete(cookie_file) - return '' - endif - endif - let command = 'curl -s '.g:gist_curl_options.' -i '.a:opt - if len(a:param) - let command .= ' -d '.quote.a:param.quote - endif - let command .= ' -b '.quote.cookie_file.quote - let command .= ' '.quote.a:url.quote - let res = iconv(system(command), "utf-8", &encoding) - let pos = stridx(res, "\r\n\r\n") - if pos != -1 - let content = res[pos+4:] - else - let pos = stridx(res, "\n\n") - let content = res[pos+2:] - endif - return { - \ "header" : split(res[0:pos], '\r\?\n'), - \ "content" : content - \} -endfunction - -function! s:GistDelete(user, token, gistid) - echon 'Deleting gist... ' - let res = s:GistGetPage('https://gist.github.com/'.a:gistid, a:user, '', '') - if (!len(res)) - echohl ErrorMsg | echomsg 'Wrong password? no response received from github trying to delete ' . a:gistid | echohl None - return - endif - let mx = '^.* name="authenticity_token" type="hidden" value="\([^"]\+\)".*$' - let token = substitute(matchstr(res.content, mx), mx, '\1', '') - if len(token) > 0 - let res = s:GistGetPage('https://gist.github.com/delete/'.a:gistid, a:user, '_method=delete&authenticity_token='.token, '') - if len(res.content) > 0 - redraw - echo 'Done: ' - else - let message = matchstr(res.header, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Delete failed: '.message | echohl None - endif - else - echohl ErrorMsg | echomsg 'Delete failed' | echohl None - endif -endfunction - - -" GistPost function: -" Post new gist to github -" -" if there is an embedded gist url or gist id in your file, -" it will just update it. -" -- by c9s -" -" embedded gist url format: -" -" Gist: https://gist.github.com/123123 -" -" embedded gist id format: -" -" GistID: 123123 -" -function! s:GistPost(user, token, content, private) - - " find GistID: in content, then we should just update - for l in split(a:content, "\n") - if l =~ '\<GistID:' - let gistid = matchstr(l, 'GistID:\s*[0-9a-z]\+') - - if strlen(gistid) == 0 - echohl WarningMsg | echo "GistID error" | echohl None - return - endif - echo "Found GistID: " . gistid - - cal s:GistUpdate(a:user, a:token, a:content, gistid, '') - return - elseif l =~ '\<Gist:' - let gistid = matchstr(l, 'Gist:\s*https://gist.github.com/[0-9a-z]\+') - - if strlen(gistid) == 0 - echohl WarningMsg | echo "GistID error" | echohl None - return - endif - echo "Found GistID: " . gistid - - cal s:GistUpdate(a:user, a:token, a:content, gistid, '') - return - endif - endfor - - let ext = expand('%:e') - let ext = len(ext) ? '.'.ext : '' - let name = expand('%:t') - - let query = [ - \ 'file_ext[gistfile1]=%s', - \ 'file_name[gistfile1]=%s', - \ 'file_contents[gistfile1]=%s', - \ ] - - if len(a:user) > 0 && len(a:token) > 0 - call add(query, 'login=%s') - call add(query, 'token=%s') - else - call add(query, '%.0s%.0s') - endif - - if a:private - call add(query, 'action_button=private') - endif - let squery = printf(join(query, '&'), - \ s:encodeURIComponent(ext), - \ s:encodeURIComponent(name), - \ s:encodeURIComponent(a:content), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) - unlet query - - let file = tempname() - call writefile([squery], file) - echon 'Posting it to gist... ' - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists' - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let headers = split(res, '\(\r\?\n\|\r\n\?\)') - let location = matchstr(headers, '^Location: ') - let location = substitute(location, '^[^:]\+: ', '', '') - if len(location) > 0 && location =~ '^\(http\|https\):\/\/gist\.github\.com\/' - redraw - echo 'Done: '.location - else - let message = matchstr(headers, '^Status: ') - let message = substitute(message, '^[^:]\+: [0-9]\+ ', '', '') - echohl ErrorMsg | echomsg 'Post failed: '.message | echohl None - endif - return location -endfunction - -function! s:GistPostBuffers(user, token, private) - let bufnrs = range(1, bufnr("$")) - let bn = bufnr('%') - let query = [] - if len(a:user) > 0 && len(a:token) > 0 - call add(query, 'login=%s') - call add(query, 'token=%s') - else - call add(query, '%.0s%.0s') - endif - if a:private - call add(query, 'action_button=private') - endif - let squery = printf(join(query, "&"), - \ s:encodeURIComponent(a:user), - \ s:encodeURIComponent(a:token)) . '&' - - let query = [ - \ 'file_ext[gistfile]=%s', - \ 'file_name[gistfile]=%s', - \ 'file_contents[gistfile]=%s', - \ ] - let format = join(query, "&") . '&' - - let index = 1 - for bufnr in bufnrs - if !bufexists(bufnr) || buflisted(bufnr) == 0 - continue - endif - echo "Creating gist content".index."... " - silent! exec "buffer!" bufnr - let content = join(getline(1, line('$')), "\n") - let ext = expand('%:e') - let ext = len(ext) ? '.'.ext : '' - let name = expand('%:t') - let squery .= printf(substitute(format, 'gistfile', 'gistfile'.index, 'g'), - \ s:encodeURIComponent(ext), - \ s:encodeURIComponent(name), - \ s:encodeURIComponent(content)) - let index = index + 1 - endfor - silent! exec "buffer!" bn - - let file = tempname() - call writefile([squery], file) - echo "Posting it to gist... " - let quote = &shellxquote == '"' ? "'" : '"' - let url = 'https://gist.github.com/gists' - let res = system('curl -i '.g:gist_curl_options.' -d @'.quote.file.quote.' '.url) - call delete(file) - let res = matchstr(split(res, '\(\r\?\n\|\r\n\?\)'), '^Location: ') - let res = substitute(res, '^.*: ', '', '') - if len(res) > 0 && res =~ '^\(http\|https\):\/\/gist\.github\.com\/' - redraw - echo 'Done: '.res - else - echohl ErrorMsg | echomsg 'Post failed' | echohl None - endif - return res -endfunction - -function! Gist(line1, line2, ...) - if !exists('g:github_user') - let g:github_user = substitute(system('git config --global github.user'), "\n", '', '') - if strlen(g:github_user) == 0 - let g:github_user = $GITHUB_USER - end - endif - if !exists('g:github_token') - let g:github_token = substitute(system('git config --global github.token'), "\n", '', '') - if strlen(g:github_token) == 0 - let g:github_token = $GITHUB_TOKEN - end - endif - if strlen(g:github_user) == 0 || strlen(g:github_token) == 0 - echohl ErrorMsg - echomsg "You have no setting for github." - echohl WarningMsg - echo "git config --global github.user your-name" - echo "git config --global github.token your-token" - echo "or set g:github_user and g:github_token in your vimrc" - echo "or set shell env vars GITHUB_USER and GITHUB_TOKEN" - echohl None - return 0 - end - - let bufname = bufname("%") - let user = g:github_user - let token = g:github_token - let gistid = '' - let gistls = '' - let gistnm = '' - let private = g:gist_private - let multibuffer = 0 - let clipboard = 0 - let deletepost = 0 - let editpost = 0 - let listmx = '^\(-l\|--list\)\s*\([^\s]\+\)\?$' - let bufnamemx = '^' . s:bufprefix .'\([0-9a-f]\+\)$' - - let args = (a:0 > 0) ? split(a:1, ' ') : [] - for arg in args - if arg =~ '^\(-la\|--listall\)$\C' - let gistls = '-all' - elseif arg =~ '^\(-l\|--list\)$\C' - if g:gist_show_privates - let gistls = 'mine' - else - let gistls = g:github_user - endif - elseif arg == '--abandon\C' - call s:GistGetPage('', '', '', '') - return - elseif arg =~ '^\(-m\|--multibuffer\)$\C' - let multibuffer = 1 - elseif arg =~ '^\(-p\|--private\)$\C' - let private = 1 - elseif arg =~ '^\(-P\|--public\)$\C' - let private = 0 - elseif arg =~ '^\(-a\|--anonymous\)$\C' - let user = '' - let token = '' - elseif arg =~ '^\(-c\|--clipboard\)$\C' - let clipboard = 1 - elseif arg =~ '^\(-d\|--delete\)$\C' && bufname =~ bufnamemx - let deletepost = 1 - let gistid = substitute(bufname, bufnamemx, '\1', '') - elseif arg =~ '^\(-e\|--edit\)$\C' && bufname =~ bufnamemx - let editpost = 1 - let gistid = substitute(bufname, bufnamemx, '\1', '') - elseif arg =~ '^\(-f\|--fork\)$\C' && bufname =~ bufnamemx - let gistid = substitute(bufname, bufnamemx, '\1', '') - let res = s:GistGetPage("https://gist.github.com/fork/".gistid, g:github_user, '', '') - let loc = filter(res.header, 'v:val =~ "^Location:"')[0] - let loc = substitute(loc, '^[^:]\+: ', '', '') - let mx = '^https://gist.github.com/\([0-9a-z]\+\)$' - if loc =~ mx - let gistid = substitute(loc, mx, '\1', '') - else - echohl ErrorMsg | echomsg 'Fork failed' | echohl None - return - endif - elseif arg !~ '^-' && len(gistnm) == 0 - if editpost == 1 || deletepost == 1 - let gistnm = arg - elseif len(gistls) > 0 && arg != '^\w\+$\C' - let gistls = arg - elseif arg =~ '^[0-9a-z]\+$\C' - let gistid = arg - else - echohl ErrorMsg | echomsg 'Invalid arguments' | echohl None - unlet args - return 0 - endif - elseif len(arg) > 0 - echohl ErrorMsg | echomsg 'Invalid arguments' | echohl None - unlet args - return 0 - endif - endfor - unlet args - "echo "gistid=".gistid - "echo "gistls=".gistls - "echo "gistnm=".gistnm - "echo "private=".private - "echo "clipboard=".clipboard - "echo "editpost=".editpost - "echo "deletepost=".deletepost - - if len(gistls) > 0 - call s:GistList(user, token, gistls, 1) - elseif len(gistid) > 0 && editpost == 0 && deletepost == 0 - call s:GistGet(user, token, gistid, clipboard) - else - let url = '' - if multibuffer == 1 - let url = s:GistPostBuffers(user, token, private) - else - let content = join(getline(a:line1, a:line2), "\n") - if editpost == 1 - let url = s:GistUpdate(user, token, content, gistid, gistnm) - elseif deletepost == 1 - call s:GistDelete(user, token, gistid) - else - let url = s:GistPost(user, token, content, private) - endif - endif - if len(url) > 0 - if g:gist_open_browser_after_post - let cmd = substitute(g:gist_browser_command, '%URL%', url, 'g') - if cmd =~ '^!' - silent! exec cmd - elseif cmd =~ '^:[A-Z]' - exec cmd - else - call system(cmd) - endif - endif - if g:gist_put_url_to_clipboard_after_post > 0 - if g:gist_put_url_to_clipboard_after_post == 2 - let url = url . "\n" - endif - if exists('g:gist_clip_command') - call system(g:gist_clip_command, url) - elseif has('unix') && !has('xterm_clipboard') - let @" = url - else - let @+ = url - endif - endif - endif - endif - return 1 -endfunction - -command! -nargs=? -range=% Gist :call Gist(<line1>, <line2>, <f-args>) -" vim:set et: diff --git a/vim/plugin/indent-object.vim b/vim/plugin/indent-object.vim deleted file mode 100644 index afb8edd..0000000 --- a/vim/plugin/indent-object.vim +++ /dev/null @@ -1,224 +0,0 @@ -"-------------------------------------------------------------------------------- -" -" Copyright (c) 2010 Michael Smith <msmith@msmith.id.au> -" -" http://github.com/michaeljsmith/vim-indent-object -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to -" deal in the Software without restriction, including without limitation the -" rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -" sell copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -" FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -" IN THE SOFTWARE. -" -"-------------------------------------------------------------------------------- - -" Mappings excluding line below. -onoremap <silent>ai :<C-u>cal <Sid>HandleTextObjectMapping(0, 0, 0, [line("."), line("."), col("."), col(".")])<CR> -onoremap <silent>ii :<C-u>cal <Sid>HandleTextObjectMapping(1, 0, 0, [line("."), line("."), col("."), col(".")])<CR> -vnoremap <silent>ai :<C-u>cal <Sid>HandleTextObjectMapping(0, 0, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv -vnoremap <silent>ii :<C-u>cal <Sid>HandleTextObjectMapping(1, 0, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv - -" Mappings including line below. -onoremap <silent>aI :<C-u>cal <Sid>HandleTextObjectMapping(0, 1, 0, [line("."), line("."), col("."), col(".")])<CR> -onoremap <silent>iI :<C-u>cal <Sid>HandleTextObjectMapping(1, 1, 0, [line("."), line("."), col("."), col(".")])<CR> -vnoremap <silent>aI :<C-u>cal <Sid>HandleTextObjectMapping(0, 1, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv -vnoremap <silent>iI :<C-u>cal <Sid>HandleTextObjectMapping(1, 1, 1, [line("'<"), line("'>"), col("'<"), col("'>")])<CR><Esc>gv - -let s:l0 = -1 -let s:l1 = -1 -let s:c0 = -1 -let s:c1 = -1 - -function! <Sid>TextObject(inner, incbelow, vis, range, count) - - " Record the current state of the visual region. - let vismode = "V" - - " Detect if this is a completely new visual selction session. - let new_vis = 0 - let new_vis = new_vis || s:l0 != a:range[0] - let new_vis = new_vis || s:l1 != a:range[1] - let new_vis = new_vis || s:c0 != a:range[2] - let new_vis = new_vis || s:c1 != a:range[3] - - let s:l0 = a:range[0] - let s:l1 = a:range[1] - let s:c0 = a:range[2] - let s:c1 = a:range[3] - - " Repeatedly increase the scope of the selection. - let itr_cnt = 0 - let cnt = a:count - while cnt > 0 - - " Look for the minimum indentation in the current visual region. - let l = s:l0 - let idnt_invalid = 1000 - let idnt = idnt_invalid - while l <= s:l1 - if !(getline(l) =~ "^\\s*$") - let idnt = min([idnt, indent(l)]) - endif - let l += 1 - endwhile - - " Keep track of where the range should be expanded to. - let l_1 = s:l0 - let l_1o = l_1 - let l2 = s:l1 - let l2o = l2 - - " If we are highlighting only blank lines, we may not have found a - " valid indent. In this case we need to look for the next and previous - " non blank lines and check which of those has the largest indent. - if idnt == idnt_invalid - let idnt = 0 - let pnb = prevnonblank(s:l0) - if pnb - let idnt = max([idnt, indent(pnb)]) - let l_1 = pnb - endif - let nnb = nextnonblank(s:l0) - if nnb - let idnt = max([idnt, indent(nnb)]) - endif - - " If we are in whitespace at the beginning of a block, skip over - " it when we are selecting the range. Similarly, if we are in - " whitespace at the end, ignore it. - if idnt > indent(pnb) - let l_1 = nnb - endif - if idnt > indent(nnb) - let l2 = pnb - endif - endif - - " Search backward for the first line with less indent than the target - " indent (skipping blank lines). - let blnk = getline(l_1) =~ "^\\s*$" - while l_1 > 0 && ((idnt == 0 && !blnk) || (idnt != 0 && (blnk || indent(l_1) >= idnt))) - if !blnk || !a:inner - let l_1o = l_1 - endif - let l_1 -= 1 - let blnk = getline(l_1) =~ "^\\s*$" - endwhile - - " Search forward for the first line with more indent than the target - " indent (skipping blank lines). - let line_cnt = line("$") - let blnk = getline(l2) =~ "^\\s*$" - while l2 <= line_cnt && ((idnt == 0 && !blnk) || (idnt != 0 && (blnk || indent(l2) >= idnt))) - if !blnk || !a:inner - let l2o = l2 - endif - let l2 += 1 - let blnk = getline(l2) =~ "^\\s*$" - endwhile - - " Determine which of these extensions to include. Include neither if - " we are selecting an 'inner' object. Exclude the bottom unless are - " told to include it. - let idnt2 = max([indent(l_1), indent(l2)]) - if indent(l_1) < idnt2 || a:inner - let l_1 = l_1o - endif - if indent(l2) < idnt2 || a:inner || !a:incbelow - let l2 = l2o - endif - let l_1 = max([l_1, 1]) - let l2 = min([l2, line("$")]) - - " Extend the columns to the start and end. - " If inner is selected, set the final cursor pos to the start - " of the text in the line. - let c_1 = 1 - if a:inner - let c_1 = match(getline(l_1), "\\c\\S") + 1 - endif - let c2 = len(getline(l2)) - if !a:inner - let c2 += 1 - endif - - " Make sure there's no change if we haven't really made a - " significant change in linewise mode - this makes sure that - " we can iteratively increase selection in linewise mode. - if itr_cnt == 0 && vismode ==# 'V' && s:l0 == l_1 && s:l1 == l2 - let c_1 = s:c0 - let c2 = s:c1 - endif - - " Check whether the visual region has changed. - let chg = 0 - let chg = chg || s:l0 != l_1 - let chg = chg || s:l1 != l2 - let chg = chg || s:c0 != c_1 - let chg = chg || s:c1 != c2 - - if vismode ==# 'V' && new_vis - let chg = 1 - endif - - " Update the vars. - let s:l0 = l_1 - let s:l1 = l2 - let s:c0 = c_1 - let s:c1 = c2 - - " If there was no change, then don't decrement the count (it didn't - " count because it didn't do anything). - if chg - let cnt = cnt - 1 - else - " Since this didn't work, push the selection back one char. This - " will have the effect of getting the enclosing block. Do it at - " the beginning rather than the end - the beginning is very likely - " to be only one indentation level different. - if s:l0 == 0 - return - endif - let s:l0 -= 1 - let s:c0 = len(getline(s:l0)) - endif - - let itr_cnt += 1 - - endwhile - - " Apply the range we have found. Make sure to use the current visual mode. - call cursor(s:l0, s:c0) - exe "normal! " . vismode - call cursor(s:l1, s:c1) - normal! o - - " Update these static variables - we need to keep these up-to-date between - " invocations because it's the only way we can detect whether it's a new - " visual mode. We need to know if it's a new visual mode because otherwise - " if there's a single line block in visual line mode and we select it with - " "V", we can't tell whether it's already been selected using Vii. - exe "normal! \<Esc>" - let s:l0 = line("'<") - let s:l1 = line("'>") - let s:c0 = col("'<") - let s:c1 = col("'>") - normal gv - -endfunction - -function! <Sid>HandleTextObjectMapping(inner, incbelow, vis, range) - call <Sid>TextObject(a:inner, a:incbelow, a:vis, a:range, v:count1) -endfunction diff --git a/vim/plugin/rails.vim b/vim/plugin/rails.vim deleted file mode 100644 index 2dd17f7..0000000 --- a/vim/plugin/rails.vim +++ /dev/null @@ -1,339 +0,0 @@ -" rails.vim - Detect a rails application -" Author: Tim Pope <http://tpo.pe/> -" GetLatestVimScripts: 1567 1 :AutoInstall: rails.vim - -" Install this file as plugin/rails.vim. See doc/rails.txt for details. (Grab -" it from the URL above if you don't have it.) To access it from Vim, see -" :help add-local-help (hint: :helptags ~/.vim/doc) Afterwards, you should be -" able to do :help rails - -if exists('g:loaded_rails') || &cp || v:version < 700 - finish -endif -let g:loaded_rails = 1 - -" Utility Functions {{{1 - -function! s:error(str) - echohl ErrorMsg - echomsg a:str - echohl None - let v:errmsg = a:str -endfunction - -function! s:autoload(...) - if !exists("g:autoloaded_rails") && v:version >= 700 - runtime! autoload/rails.vim - endif - if exists("g:autoloaded_rails") - if a:0 - exe a:1 - endif - return 1 - endif - if !exists("g:rails_no_autoload_warning") - let g:rails_no_autoload_warning = 1 - if v:version >= 700 - call s:error("Disabling rails.vim: autoload/rails.vim is missing") - else - call s:error("Disabling rails.vim: Vim version 7 or higher required") - endif - endif - return "" -endfunction - -" }}}1 -" Configuration {{{ - -function! s:SetOptDefault(opt,val) - if !exists("g:".a:opt) - let g:{a:opt} = a:val - endif -endfunction - -call s:SetOptDefault("rails_statusline",1) -call s:SetOptDefault("rails_syntax",1) -call s:SetOptDefault("rails_mappings",1) -call s:SetOptDefault("rails_abbreviations",1) -call s:SetOptDefault("rails_ctags_arguments","--languages=-javascript") -call s:SetOptDefault("rails_default_file","README") -call s:SetOptDefault("rails_root_url",'http://localhost:3000/') -call s:SetOptDefault("rails_modelines",0) -call s:SetOptDefault("rails_menu",0) -call s:SetOptDefault("rails_gnu_screen",1) -call s:SetOptDefault("rails_history_size",5) -call s:SetOptDefault("rails_generators","controller\ngenerator\nhelper\nintegration_test\nmailer\nmetal\nmigration\nmodel\nobserver\nperformance_test\nplugin\nresource\nscaffold\nscaffold_controller\nsession_migration\nstylesheets") -if exists("g:loaded_dbext") && executable("sqlite3") && ! executable("sqlite") - " Since dbext can't find it by itself - call s:SetOptDefault("dbext_default_SQLITE_bin","sqlite3") -endif - -" }}}1 -" Detection {{{1 - -function! s:escvar(r) - let r = fnamemodify(a:r,':~') - let r = substitute(r,'\W','\="_".char2nr(submatch(0))."_"','g') - let r = substitute(r,'^\d','_&','') - return r -endfunction - -function! s:Detect(filename) - let fn = substitute(fnamemodify(a:filename,":p"),'\c^file://','','') - let sep = matchstr(fn,'^[^\\/]\{3,\}\zs[\\/]') - if sep != "" - let fn = getcwd().sep.fn - endif - if fn =~ '[\/]config[\/]environment\.rb$' - return s:BufInit(strpart(fn,0,strlen(fn)-22)) - endif - if isdirectory(fn) - let fn = fnamemodify(fn,':s?[\/]$??') - else - let fn = fnamemodify(fn,':s?\(.*\)[\/][^\/]*$?\1?') - endif - let ofn = "" - let nfn = fn - while nfn != ofn && nfn != "" - if exists("s:_".s:escvar(nfn)) - return s:BufInit(nfn) - endif - let ofn = nfn - let nfn = fnamemodify(nfn,':h') - endwhile - let ofn = "" - while fn != ofn - if filereadable(fn . "/config/environment.rb") - return s:BufInit(fn) - endif - let ofn = fn - let fn = fnamemodify(ofn,':s?\(.*\)[\/]\(app\|config\|db\|doc\|features\|lib\|log\|public\|script\|spec\|stories\|test\|tmp\|vendor\)\($\|[\/].*$\)?\1?') - endwhile - return 0 -endfunction - -function! s:BufInit(path) - let s:_{s:escvar(a:path)} = 1 - if s:autoload() - return RailsBufInit(a:path) - endif -endfunction - -" }}}1 -" Initialization {{{1 - -augroup railsPluginDetect - autocmd! - autocmd BufNewFile,BufRead * call s:Detect(expand("<afile>:p")) - autocmd VimEnter * if expand("<amatch>") == "" && !exists("b:rails_root") | call s:Detect(getcwd()) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif - autocmd FileType netrw if !exists("b:rails_root") | call s:Detect(expand("<afile>:p")) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif - autocmd BufEnter * if exists("b:rails_root")|silent doau User BufEnterRails|endif - autocmd BufLeave * if exists("b:rails_root")|silent doau User BufLeaveRails|endif - autocmd Syntax railslog if s:autoload()|call rails#log_syntax()|endif -augroup END - -command! -bar -bang -nargs=* -complete=dir Rails :if s:autoload()|call rails#new_app_command(<bang>0,<f-args>)|endif - -" }}}1 -" abolish.vim support {{{1 - -function! s:function(name) - return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) -endfunction - -augroup railsPluginAbolish - autocmd! - autocmd VimEnter * call s:abolish_setup() -augroup END - -function! s:abolish_setup() - if exists('g:Abolish') && has_key(g:Abolish,'Coercions') - if !has_key(g:Abolish.Coercions,'l') - let g:Abolish.Coercions.l = s:function('s:abolish_l') - endif - if !has_key(g:Abolish.Coercions,'t') - let g:Abolish.Coercions.t = s:function('s:abolish_t') - endif - endif -endfunction - -function! s:abolish_l(word) - let singular = rails#singularize(a:word) - return a:word ==? singular ? rails#pluralize(a:word) : singular -endfunction - -function! s:abolish_t(word) - if a:word =~# '\u' - return rails#pluralize(rails#underscore(a:word)) - else - return rails#singularize(rails#camelize(a:word)) - endif -endfunction - -" }}}1 -" Menus {{{1 - -if !(g:rails_menu && has("menu")) - finish -endif - -function! s:sub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'') -endfunction - -function! s:gsub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'g') -endfunction - -function! s:menucmd(priority) - return 'anoremenu <script> '.(exists("$CREAM") ? 87 : '').s:gsub(g:rails_installed_menu,'[^.]','').'.'.a:priority.' ' -endfunction - -function! s:CreateMenus() abort - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - exe "aunmenu ".s:gsub(g:rails_installed_menu,'\&','') - unlet g:rails_installed_menu - endif - if has("menu") && (exists("g:did_install_default_menus") || exists("$CREAM")) && g:rails_menu - if g:rails_menu > 1 - let g:rails_installed_menu = '&Rails' - else - let g:rails_installed_menu = '&Plugin.&Rails' - endif - let dots = s:gsub(g:rails_installed_menu,'[^.]','') - let menucmd = s:menucmd(200) - if exists("$CREAM") - exe menucmd.g:rails_installed_menu.'.-PSep- :' - exe menucmd.g:rails_installed_menu.'.&Related\ file\ :R\ /\ Alt+] :R<CR>' - exe menucmd.g:rails_installed_menu.'.&Alternate\ file\ :A\ /\ Alt+[ :A<CR>' - exe menucmd.g:rails_installed_menu.'.&File\ under\ cursor\ Ctrl+Enter :Rfind<CR>' - else - exe menucmd.g:rails_installed_menu.'.-PSep- :' - exe menucmd.g:rails_installed_menu.'.&Related\ file\ :R\ /\ ]f :R<CR>' - exe menucmd.g:rails_installed_menu.'.&Alternate\ file\ :A\ /\ [f :A<CR>' - exe menucmd.g:rails_installed_menu.'.&File\ under\ cursor\ gf :Rfind<CR>' - endif - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Controller :Rcontroller application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Helper :Rhelper application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Javascript :Rjavascript application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &Layout :Rlayout application<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Application\ &README :R doc/README_FOR_APP<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Environment :Renvironment<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Database\ Configuration :R config/database.yml<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.Database\ &Schema :Rmigration 0<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.R&outes :Rinitializer<CR>' - exe menucmd.g:rails_installed_menu.'.&Other\ files.&Test\ Helper :Rintegrationtest<CR>' - exe menucmd.g:rails_installed_menu.'.-FSep- :' - exe menucmd.g:rails_installed_menu.'.Ra&ke\ :Rake :Rake<CR>' - let menucmd = substitute(menucmd,'200 $','500 ','') - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Start\ :Rserver :Rserver<CR>' - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Force\ start\ :Rserver! :Rserver!<CR>' - exe menucmd.g:rails_installed_menu.'.&Server\ :Rserver.&Kill\ :Rserver!\ - :Rserver! -<CR>' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.&Evaluate\ Ruby\.\.\.\ :Rp :call <SID>menuprompt("Rp","Code to execute and output: ")<CR>' - exe menucmd.g:rails_installed_menu.'.&Console\ :Rscript :Rscript console<CR>' - exe menucmd.g:rails_installed_menu.'.&Preview\ :Rpreview :Rpreview<CR>' - exe menucmd.g:rails_installed_menu.'.&Log\ file\ :Rlog :Rlog<CR>' - exe substitute(s:sub(menucmd,'anoremenu','vnoremenu'),'<script>','<script> <silent>','').g:rails_installed_menu.'.E&xtract\ as\ partial\ :Rextract :call <SID>menuprompt("'."'".'<,'."'".'>Rextract","Partial name (e.g., template or /controller/template): ")<CR>' - exe menucmd.g:rails_installed_menu.'.&Migration\ writer\ :Rinvert :Rinvert<CR>' - exe menucmd.' '.g:rails_installed_menu.'.-HSep- :' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.&Help\ :help\ rails :if <SID>autoload()<Bar>exe RailsHelpCommand("")<Bar>endif<CR>' - exe substitute(menucmd,'<script>','<script> <silent>','').g:rails_installed_menu.'.Abo&ut\ :if <SID>autoload()<Bar>exe RailsHelpCommand("about")<Bar>endif<CR>' - let g:rails_did_menus = 1 - call s:ProjectMenu() - call s:menuBufLeave() - if exists("b:rails_root") - call s:menuBufEnter() - endif - endif -endfunction - -function! s:ProjectMenu() - if exists("g:rails_did_menus") && g:rails_history_size > 0 - if !exists("g:RAILS_HISTORY") - let g:RAILS_HISTORY = "" - endif - let history = g:RAILS_HISTORY - let menu = s:gsub(g:rails_installed_menu,'\&','') - silent! exe "aunmenu <script> ".menu.".Projects" - let dots = s:gsub(menu,'[^.]','') - exe 'anoremenu <script> <silent> '.(exists("$CREAM") ? '87' : '').dots.'.100 '.menu.'.Pro&jects.&New\.\.\.\ :Rails :call <SID>menuprompt("Rails","New application path and additional arguments: ")<CR>' - exe 'anoremenu <script> '.menu.'.Pro&jects.-FSep- :' - while history =~ '\n' - let proj = matchstr(history,'^.\{-\}\ze\n') - let history = s:sub(history,'^.{-}\n','') - exe 'anoremenu <script> '.menu.'.Pro&jects.'.s:gsub(proj,'[.\\ ]','\\&').' :e '.s:gsub(proj."/".g:rails_default_file,'[ !%#]','\\&')."<CR>" - endwhile - endif -endfunction - -function! s:menuBufEnter() - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - let menu = s:gsub(g:rails_installed_menu,'\&','') - exe 'amenu enable '.menu.'.*' - if RailsFileType() !~ '^view\>' - exe 'vmenu disable '.menu.'.Extract\ as\ partial' - endif - if RailsFileType() !~ '^\%(db-\)\=migration$' || RailsFilePath() =~ '\<db/schema\.rb$' - exe 'amenu disable '.menu.'.Migration\ writer' - endif - call s:ProjectMenu() - silent! exe 'aunmenu '.menu.'.Rake\ tasks' - silent! exe 'aunmenu '.menu.'.Generate' - silent! exe 'aunmenu '.menu.'.Destroy' - if rails#app().cache.needs('rake_tasks') || empty(rails#app().rake_tasks()) - exe substitute(s:menucmd(300),'<script>','<script> <silent>','').g:rails_installed_menu.'.Rake\ &tasks\ :Rake.Fill\ this\ menu :call rails#app().rake_tasks()<Bar>call <SID>menuBufLeave()<Bar>call <SID>menuBufEnter()<CR>' - else - let i = 0 - while i < len(rails#app().rake_tasks()) - let task = rails#app().rake_tasks()[i] - exe s:menucmd(300).g:rails_installed_menu.'.Rake\ &tasks\ :Rake.'.s:sub(task,':',':.').' :Rake '.task.'<CR>' - let i += 1 - endwhile - endif - let i = 0 - let menucmd = substitute(s:menucmd(400),'<script>','<script> <silent>','').g:rails_installed_menu - while i < len(rails#app().generators()) - let generator = rails#app().generators()[i] - exe menucmd.'.&Generate\ :Rgen.'.s:gsub(generator,'_','\\ ').' :call <SID>menuprompt("Rgenerate '.generator.'","Arguments for script/generate '.generator.': ")<CR>' - exe menucmd.'.&Destroy\ :Rdestroy.'.s:gsub(generator,'_','\\ ').' :call <SID>menuprompt("Rdestroy '.generator.'","Arguments for script/destroy '.generator.': ")<CR>' - let i += 1 - endwhile - endif -endfunction - -function! s:menuBufLeave() - if exists("g:rails_installed_menu") && g:rails_installed_menu != "" - let menu = s:gsub(g:rails_installed_menu,'\&','') - exe 'amenu disable '.menu.'.*' - exe 'amenu enable '.menu.'.Help\ ' - exe 'amenu enable '.menu.'.About\ ' - exe 'amenu enable '.menu.'.Projects' - silent! exe 'aunmenu '.menu.'.Rake\ tasks' - silent! exe 'aunmenu '.menu.'.Generate' - silent! exe 'aunmenu '.menu.'.Destroy' - exe s:menucmd(300).g:rails_installed_menu.'.Rake\ tasks\ :Rake.-TSep- :' - exe s:menucmd(400).g:rails_installed_menu.'.&Generate\ :Rgen.-GSep- :' - exe s:menucmd(400).g:rails_installed_menu.'.&Destroy\ :Rdestroy.-DSep- :' - endif -endfunction - -function! s:menuprompt(vimcmd,prompt) - let res = inputdialog(a:prompt,'','!!!') - if res == '!!!' - return "" - endif - exe a:vimcmd." ".res -endfunction - -call s:CreateMenus() - -augroup railsPluginMenu - autocmd! - autocmd User BufEnterRails call s:menuBufEnter() - autocmd User BufLeaveRails call s:menuBufLeave() - " g:RAILS_HISTORY hasn't been set when s:InitPlugin() is called. - autocmd VimEnter * call s:ProjectMenu() -augroup END - -" }}}1 -" vim:set sw=2 sts=2: diff --git a/vim/plugin/searchfold_0.9.vim b/vim/plugin/searchfold_0.9.vim deleted file mode 100644 index 1fb9ba8..0000000 --- a/vim/plugin/searchfold_0.9.vim +++ /dev/null @@ -1,319 +0,0 @@ -" Vim global plugin -- create folds based on last search pattern -" General: {{{1 -" File: searchfold.vim -" Created: 2008 Jan 19 -" Last Change: 2011 May 24 -" Rev Days: 18 -" Author: Andy Wokula <anwoku@yahoo.de> -" Credits: Antonio Colombo's f.vim (Vimscript #318, 2005 May 10) -" Vim Version: Vim 7.0 -" Version: 0.9 - -" Description: -" Provide mappings to fold away lines not matching the last search pattern -" and to restore old fold settings afterwards. Uses manual fold method, -" which allows for nested folds to hide or show more context. Doesn't -" preserve the user's manual folds. - -" Usage: -" <Leader>z fold away lines not matching the last search pattern. -" -" With [count], change the initial foldlevel to ([count] minus -" one). The setting will be stored in g:searchfold_foldlevel -" and will be reused when [count] is omitted. -" -" <Leader>iz fold away lines that do match the last search pattern -" (inverse folding), also with [count]. -" -" <Leader>Z restore the previous fold settings. -" -" Minor Extra: If already in restored state, show a dialog to -" revert all involved local fold options to the global -" defaults. The "(s)how" just prints info. - -" Customization: -" :let g:searchfold_maxdepth = 7 -" (number) -" maximum fold depth -" -" :let g:searchfold_usestep = 1 -" (boolean) -" Controls how folds are organized: If 1 (default), each "zr" -" (after "\z") unfolds the same amount of lines above and -" below a match. If 0, only one more line is unfolded above a -" match. This applies for next "\z" or "\iz". -" -" :let g:searchfold_postZ_do_zv = 1 -" (boolean) -" If 1, execute "zv" (view cursor line) after <Leader>Z. -" -" :let g:searchfold_foldlevel = 0 -" (number) -" Initial 'foldlevel' to set for <Leader>z and <Leader>iz. -" -" :let g:searchfold_do_maps = 1 -" (boolean) -" Whether to map the default keys or not. -" -" Hint: For boolean options, 1 actually means any non-zero number. - -" Related: Vimscript #158 (foldutil.vim) ... still to be checked out -" http://www.noah.org/wiki/Vim#Folding -" Vimscript #2302 (foldsearch.vim) -" Vimscript #578 (allfold.tar.gz) -" -" Changes: -" v0.9 redraw removed, plug map renamed, comments (usestep ...) -" v0.8 added inverse folding (<Leader>iz), g:searchfold_foldlevel, -" count for <Leader>z, <Plug> mappings, disabled F(), (fixes) -" v0.7 b:searchfold fallback, s:foldtext check -" v0.6 (after v0.4) added customization vars (usestep, maxdepth, Zpost) -" reverting global fold settings adds to cmd-history -" v0.4 decreasing fold step always 1 -" maxdepth 7 (before: 6) -" v0.3 (after v0.1) added a modified F() from f.vim -" functions now with return values -" v0.2 (skipped) - -" Init Folklore: {{{1 -if exists("loaded_searchfold") - finish -endif -let loaded_searchfold = 1 - -if v:version<700 - echo "Searchfold: you need at least Vim 7.0" - finish -endif - -" Customization: {{{1 -if !exists("g:searchfold_maxdepth") - let g:searchfold_maxdepth = 7 -endif -if !exists("g:searchfold_usestep") - let g:searchfold_usestep = 1 -endif -if !exists("g:searchfold_postZ_do_zv") - let g:searchfold_postZ_do_zv = 1 -endif -if !exists("g:searchfold_foldlevel") - let g:searchfold_foldlevel = 0 -endif -if !exists("g:searchfold_do_maps") - let g:searchfold_do_maps = 1 -endif - -" s:variables {{{1 -let s:foldtext = "(v:folddashes.'').((v:foldend)-(v:foldstart)+(1))" -" use unique notation of 'foldtext' to identify active searchfold in a -" window - -func! s:FoldNested(from, to) " {{{1 - " create one fold from line a:from to line a:to, with more nested folds - " return 1 if folds were created - " return 0 if from > to - let nlines = a:to - a:from - if nlines < 0 - return 0 - elseif nlines < 3 - " range of 1 line possible - exec a:from.",".a:to. "fold" - return 1 - endif - - " calc folds, start with most outer fold - " - range of inner folds at least 2 lines (from<to) - " - limit nesting (depth) - " - snap folds at start and end of file - " - at greater "depth" (here depth->0), don't create folds with few - " lines only (check to-from>step) - if g:searchfold_maxdepth < 1 || g:searchfold_maxdepth > 12 - let g:searchfold_maxdepth = 7 - endif - let depth = g:searchfold_maxdepth - let step = 1 " decstep:'' - let step1 = 1 " (const) decstep:'1' - let from = a:from - let to = a:to - " let decstep = exists("g:searchfold_usestep") && g:searchfold_usestep ? "" : "1" - let decstep = g:searchfold_usestep ? "" : "1" - let foldranges = [] - let lined = line("$") - while depth>0 && from<to && to-from>step - call insert(foldranges, from.",".to) - let from += from>1 ? step : 0 - " let to -= to<lined ? 1 : 0 - let to -= to<lined ? step{decstep} : 0 - let step += step " arbitrary - let depth -= 1 - endwhile - - " create folds, start with most inner fold - for range in foldranges - exec range. "fold" - endfor - - return 1 -endfunc - -func! s:CreateFolds(inverse) " {{{1 - " create search folds for the whole buffer based on last search pattern - let sav_cur = getpos(".") - - let matches = [] " list of lnums - if !a:inverse - global//call add(matches, line(".")) - else - vglobal//call add(matches, line(".")) - endif - - let nmatches = len(matches) - if nmatches > 0 - call s:FoldNested(1, matches[0]-1) - let imax = nmatches - 1 - let i = 0 - while i < imax - if matches[i]+1 < matches[i+1] - call s:FoldNested(matches[i]+1, matches[i+1]-1) - endif - let i += 1 - endwhile - call s:FoldNested(matches[imax]+1, line("$")) - endif - - let &l:foldlevel = g:searchfold_foldlevel - call cursor(sav_cur[1:]) - - return nmatches -endfunc - -func! <sid>SearchFoldEnable(inverse) "{{{1 - " return number of matches - if !search("", "n") - " last search pattern not found, do nothing - return 0 - endif - if (!exists("w:searchfold") || w:searchfold.bufnr != bufnr("")) - \ && &fdt != s:foldtext - " remember settings - let w:searchfold = { "bufnr": bufnr(""), - \ "fdm": &fdm, - \ "fdl": &fdl, - \ "fdt": &fdt, - \ "fen": &fen, - \ "fml": &fml } - " else: do not remember settings if already enabled - endif - setlocal foldmethod=manual - setlocal foldlevel=0 - let &l:foldtext=s:foldtext - setlocal foldenable - setlocal foldminlines=0 - normal! zE - if exists("w:searchfold") - let b:searchfold = w:searchfold - endif - return s:CreateFolds(a:inverse) -endfunc -func! SearchFoldRestore() "{{{1 - " turn off - if exists("w:searchfold") && w:searchfold.bufnr == bufnr("") - " restore settings; var has the right settings if exists, but - " doesn't survive window split or win close/restore - let &l:fdm = w:searchfold.fdm - let &l:fdl = w:searchfold.fdl - let &l:fdt = w:searchfold.fdt - let &l:fen = w:searchfold.fen - let &l:fml = w:searchfold.fml - if &fdm == "manual" - " remove all search folds (old folds are lost anyway): - normal! zE - endif - unlet w:searchfold - elseif exists("b:searchfold") && &fdt == s:foldtext - " fallback only, may have wrong settings if overwritten - let &l:fdm = b:searchfold.fdm - let &l:fdl = b:searchfold.fdl - let &l:fdt = b:searchfold.fdt - let &l:fen = b:searchfold.fen - let &l:fml = b:searchfold.fml - if &fdm == "manual" - normal! zE - endif - else - let choice = input("Revert to global fold settings? (y/[n]/(s)how):")[0] - let setargs = 'fdm< fdl< fdt< fen< fml<' - if choice == "y" - let cmd = 'setlocal '. setargs - echo ':'. cmd - exec cmd - " call histadd(':', cmd) - elseif choice == "s" - let setargs = tr(setargs, "<","?") - let cmd = 'setglobal '. setargs - echo ':'. cmd - exec cmd - let cmd = 'setlocal '. setargs - echo ':'. cmd - exec cmd - endif - return - endif - if g:searchfold_postZ_do_zv - normal! zv - endif -endfunc - -"" func! F() range "{{{1 -" " commented out 2010 Jun 01 -" " range arg: ignore range given by accident -" let pat = input("Which regexp? ", @/) -" if pat == "" -" if exists("w:searchfold") -" call SearchFoldRestore() -" endif -" return -" endif -" let @/ = pat -" call histadd("search", @/) -" call SearchFold() -" endfunc - -" :call F() only for backwards compatibility - -func! SearchFold(...) "{{{1 - let inverse = a:0>=1 && a:1 - if v:count >= 1 - let g:searchfold_foldlevel = v:count - 1 - endif - let nmatches = <sid>SearchFoldEnable(inverse) - " at most one match per line counted - if nmatches == 0 - echohl ErrorMsg - echomsg "Searchfold: Pattern not found:" @/ - echohl none - elseif nmatches == line("$") - echomsg "Searchfold: Pattern found in every line:" @/ - elseif nmatches == 1 - echo "Searchfold: 1 line found" - else - echo "Searchfold:" nmatches "lines found" - endif - " 2011 Feb 06 commented out: - " let &hls = &hls - " redraw -endfunc - -" Mappings: {{{1 -nn <silent> <Plug>SearchFoldNormal :<C-U>call SearchFold(0)<CR> -nn <silent> <Plug>SearchFoldInverse :<C-U>call SearchFold(1)<CR> -nn <silent> <Plug>SearchFoldRestore :<C-U>call SearchFoldRestore()<CR> - -if g:searchfold_do_maps - nmap <Leader>z <Plug>SearchFoldNormal - nmap <Leader>iz <Plug>SearchFoldInverse - nmap <Leader>Z <Plug>SearchFoldRestore -endif - -" Modeline: {{{1 -" vim:set fdm=marker ts=8 sts=4 sw=4 noet: diff --git a/vim/plugin/showmarks.vim b/vim/plugin/showmarks.vim deleted file mode 100644 index c6931c2..0000000 --- a/vim/plugin/showmarks.vim +++ /dev/null @@ -1,507 +0,0 @@ -" ============================================================================== -" Name: ShowMarks -" Description: Visually displays the location of marks. -" Authors: Anthony Kruize <trandor@labyrinth.net.au> -" Michael Geddes <michaelrgeddes@optushome.com.au> -" Version: 2.2 -" Modified: 17 August 2004 -" License: Released into the public domain. -" ChangeLog: See :help showmarks-changelog -" -" Usage: Copy this file into the plugins directory so it will be -" automatically sourced. -" -" Default keymappings are: -" <Leader>mt - Toggles ShowMarks on and off. -" <Leader>mo - Turns ShowMarks on, and displays marks. -" <Leader>mh - Clears a mark. -" <Leader>ma - Clears all marks. -" <Leader>mm - Places the next available mark. -" -" Hiding a mark doesn't actually remove it, it simply moves it -" to line 1 and hides it visually. -" -" Configuration: *********************************************************** -" * PLEASE read the included help file(showmarks.txt) for a * -" * more thorough explanation of how to use ShowMarks. * -" *********************************************************** -" The following options can be used to customize the behavior -" of ShowMarks. Simply include them in your vimrc file with -" the desired settings. -" -" showmarks_enable (Default: 1) -" Defines whether ShowMarks is enabled by default. -" Example: let g:showmarks_enable=0 -" showmarks_include (Default: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.'`^<>[]{}()\"") -" Defines all marks, in precedence order (only the highest -" precence will show on lines having more than one mark). -" Can be buffer-specific (set b:showmarks_include) -" showmarks_ignore_type (Default: "hq") -" Defines the buffer types to be ignored. -" Valid types are: -" h - Help p - preview -" q - quickfix r - readonly -" m - non-modifiable -" showmarks_textlower (Default: ">") -" Defines how the mark is to be displayed. -" A maximum of two characters can be displayed. To include -" the mark in the text use a tab(\t) character. A single -" character will display as the mark with the character -" suffixed (same as "\t<character>") -" Examples: -" To display the mark with a > suffixed: -" let g:showmarks_textlower="\t>" -" or -" let g:showmarks_textlower=">" -" To display the mark with a ( prefixed: -" let g:showmarks_textlower="(\t" -" To display two > characters: -" let g:showmarks_textlower=">>" -" showmarks_textupper (Default: ">") -" Same as above but for the marks A-Z. -" Example: let g:showmarks_textupper="**" -" showmarks_textother (Default: ">") -" Same as above but for all other marks. -" Example: let g:showmarks_textother="--" -" showmarks_hlline_lower (Default: 0) -" showmarks_hlline_upper (Default: 0) -" showmarks_hlline_other (Default: 0) -" Defines whether the entire line for a particular mark -" should be highlighted. -" Example: let g:showmarks_hlline_lower=1 -" -" Setting Highlighting Colours -" ShowMarks uses the following highlighting groups: -" ShowMarksHLl - For marks a-z -" ShowMarksHLu - For marks A-Z -" ShowMarksHLo - For all other marks -" ShowMarksHLm - For multiple marks on the same line. -" (Highest precendece mark is shown) -" -" By default they are set to a bold blue on light blue. -" Defining a highlight for each of these groups will -" override the default highlighting. -" See the VIM help for more information about highlighting. -" ============================================================================== - -" Check if we should continue loading -if exists( "loaded_showmarks" ) - finish -endif -let loaded_showmarks = 1 - -" Bail if Vim isn't compiled with signs support. -if has( "signs" ) == 0 - echohl ErrorMsg - echo "ShowMarks requires Vim to have +signs support." - echohl None - finish -endif - -" Options: Set up some nice defaults -if !exists('g:showmarks_enable' ) | let g:showmarks_enable = 1 | endif -if !exists('g:showmarks_textlower' ) | let g:showmarks_textlower = ">" | endif -if !exists('g:showmarks_textupper' ) | let g:showmarks_textupper = ">" | endif -if !exists('g:showmarks_textother' ) | let g:showmarks_textother = ">" | endif -if !exists('g:showmarks_ignore_type' ) | let g:showmarks_ignore_type = "hq" | endif -if !exists('g:showmarks_ignore_name' ) | let g:showmarks_ignore_name = "" | endif -if !exists('g:showmarks_hlline_lower') | let g:showmarks_hlline_lower = "0" | endif -if !exists('g:showmarks_hlline_upper') | let g:showmarks_hlline_upper = "0" | endif -if !exists('g:showmarks_hlline_other') | let g:showmarks_hlline_other = "0" | endif - -" This is the default, and used in ShowMarksSetup to set up info for any -" possible mark (not just those specified in the possibly user-supplied list -" of marks to show -- it can be changed on-the-fly). -let s:all_marks = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.'`^<>[]{}()\"" - -" Commands -com! -nargs=0 ShowMarksToggle :call <sid>ShowMarksToggle() -com! -nargs=0 ShowMarksOn :call <sid>ShowMarksOn() -com! -nargs=0 ShowMarksClearMark :call <sid>ShowMarksClearMark() -com! -nargs=0 ShowMarksClearAll :call <sid>ShowMarksClearAll() -com! -nargs=0 ShowMarksPlaceMark :call <sid>ShowMarksPlaceMark() - -" Mappings (NOTE: Leave the '|'s immediately following the '<cr>' so the mapping does not contain any trailing spaces!) -if !hasmapto( '<Plug>ShowmarksShowMarksToggle' ) | map <silent> <unique> <leader>mt :ShowMarksToggle<cr>| endif -if !hasmapto( '<Plug>ShowmarksShowMarksOn' ) | map <silent> <unique> <leader>mo :ShowMarksOn<cr>| endif -if !hasmapto( '<Plug>ShowmarksClearMark' ) | map <silent> <unique> <leader>mh :ShowMarksClearMark<cr>| endif -if !hasmapto( '<Plug>ShowmarksClearAll' ) | map <silent> <unique> <leader>ma :ShowMarksClearAll<cr>| endif -if !hasmapto( '<Plug>ShowmarksPlaceMark' ) | map <silent> <unique> <leader>mm :ShowMarksPlaceMark<cr>| endif -noremap <unique> <script> \sm m -noremap <silent> m :exe 'norm \sm'.nr2char(getchar())<bar>call <sid>ShowMarks()<CR> - -" AutoCommands: Only if ShowMarks is enabled -if g:showmarks_enable == 1 - aug ShowMarks - au! - autocmd CursorHold * call s:ShowMarks() - aug END -endif - -" Highlighting: Setup some nice colours to show the mark positions. -hi default ShowMarksHLl ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold -hi default ShowMarksHLu ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold -hi default ShowMarksHLo ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold -hi default ShowMarksHLm ctermfg=darkblue ctermbg=blue cterm=bold guifg=blue guibg=lightblue gui=bold - -" Function: IncludeMarks() -" Description: This function returns the list of marks (in priority order) to -" show in this buffer. Each buffer, if not already set, inherits the global -" setting; if the global include marks have not been set; that is set to the -" default value. -fun! s:IncludeMarks() - if exists('b:showmarks_include') && exists('b:showmarks_previous_include') && b:showmarks_include != b:showmarks_previous_include - " The user changed the marks to include; hide all marks; change the - " included mark list, then show all marks. Prevent infinite - " recursion during this switch. - if exists('s:use_previous_include') - " Recursive call from ShowMarksHideAll() - return b:showmarks_previous_include - elseif exists('s:use_new_include') - " Recursive call from ShowMarks() - return b:showmarks_include - else - let s:use_previous_include = 1 - call <sid>ShowMarksHideAll() - unlet s:use_previous_include - let s:use_new_include = 1 - call <sid>ShowMarks() - unlet s:use_new_include - endif - endif - - if !exists('g:showmarks_include') - let g:showmarks_include = s:all_marks - endif - if !exists('b:showmarks_include') - let b:showmarks_include = g:showmarks_include - endif - - " Save this include setting so we can detect if it was changed. - let b:showmarks_previous_include = b:showmarks_include - - return b:showmarks_include -endf - -" Function: NameOfMark() -" Paramaters: mark - Specifies the mark to find the name of. -" Description: Convert marks that cannot be used as part of a variable name to -" something that can be. i.e. We cannot use [ as a variable-name suffix (as -" in 'placed_['; this function will return something like 63, so the variable -" will be something like 'placed_63'). -" 10 is added to the mark's index to avoid colliding with the numeric marks -" 0-9 (since a non-word mark could be listed in showmarks_include in the -" first 10 characters if the user overrides the default). -" Returns: The name of the requested mark. -fun! s:NameOfMark(mark) - let name = a:mark - if a:mark =~# '\W' - let name = stridx(s:all_marks, a:mark) + 10 - endif - return name -endf - -" Function: VerifyText() -" Paramaters: which - Specifies the variable to verify. -" Description: Verify the validity of a showmarks_text{upper,lower,other} setup variable. -" Default to ">" if it is found to be invalid. -fun! s:VerifyText(which) - if strlen(g:showmarks_text{a:which}) == 0 || strlen(g:showmarks_text{a:which}) > 2 - echohl ErrorMsg - echo "ShowMarks: text".a:which." must contain only 1 or 2 characters." - echohl None - let g:showmarks_text{a:which}=">" - endif -endf - -" Function: ShowMarksSetup() -" Description: This function sets up the sign definitions for each mark. -" It uses the showmarks_textlower, showmarks_textupper and showmarks_textother -" variables to determine how to draw the mark. -fun! s:ShowMarksSetup() - " Make sure the textlower, textupper, and textother options are valid. - call s:VerifyText('lower') - call s:VerifyText('upper') - call s:VerifyText('other') - - let n = 0 - let s:maxmarks = strlen(s:all_marks) - while n < s:maxmarks - let c = strpart(s:all_marks, n, 1) - let nm = s:NameOfMark(c) - let text = '>'.c - let lhltext = '' - if c =~# '[a-z]' - if strlen(g:showmarks_textlower) == 1 - let text=c.g:showmarks_textlower - elseif strlen(g:showmarks_textlower) == 2 - let t1 = strpart(g:showmarks_textlower,0,1) - let t2 = strpart(g:showmarks_textlower,1,1) - if t1 == "\t" - let text=c.t2 - elseif t2 == "\t" - let text=t1.c - else - let text=g:showmarks_textlower - endif - endif - let s:ShowMarksDLink{nm} = 'ShowMarksHLl' - if g:showmarks_hlline_lower == 1 - let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm - endif - elseif c =~# '[A-Z]' - if strlen(g:showmarks_textupper) == 1 - let text=c.g:showmarks_textupper - elseif strlen(g:showmarks_textupper) == 2 - let t1 = strpart(g:showmarks_textupper,0,1) - let t2 = strpart(g:showmarks_textupper,1,1) - if t1 == "\t" - let text=c.t2 - elseif t2 == "\t" - let text=t1.c - else - let text=g:showmarks_textupper - endif - endif - let s:ShowMarksDLink{nm} = 'ShowMarksHLu' - if g:showmarks_hlline_upper == 1 - let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm - endif - else " Other signs, like ', ., etc. - if strlen(g:showmarks_textother) == 1 - let text=c.g:showmarks_textother - elseif strlen(g:showmarks_textother) == 2 - let t1 = strpart(g:showmarks_textother,0,1) - let t2 = strpart(g:showmarks_textother,1,1) - if t1 == "\t" - let text=c.t2 - elseif t2 == "\t" - let text=t1.c - else - let text=g:showmarks_textother - endif - endif - let s:ShowMarksDLink{nm} = 'ShowMarksHLo' - if g:showmarks_hlline_other == 1 - let lhltext = 'linehl='.s:ShowMarksDLink{nm}.nm - endif - endif - - " Define the sign with a unique highlight which will be linked when placed. - exe 'sign define ShowMark'.nm.' '.lhltext.' text='.text.' texthl='.s:ShowMarksDLink{nm}.nm - let b:ShowMarksLink{nm} = '' - let n = n + 1 - endw -endf - -" Set things up -call s:ShowMarksSetup() - -" Function: ShowMarksOn -" Description: Enable showmarks, and show them now. -fun! s:ShowMarksOn() - if g:showmarks_enable == 0 - call <sid>ShowMarksToggle() - else - call <sid>ShowMarks() - endif -endf - -" Function: ShowMarksToggle() -" Description: This function toggles whether marks are displayed or not. -fun! s:ShowMarksToggle() - if g:showmarks_enable == 0 - let g:showmarks_enable = 1 - call <sid>ShowMarks() - aug ShowMarks - au! - autocmd CursorHold * call s:ShowMarks() - aug END - else - let g:showmarks_enable = 0 - call <sid>ShowMarksHideAll() - aug ShowMarks - au! - autocmd BufEnter * call s:ShowMarksHideAll() - aug END - endif -endf - -" Function: ShowMarks() -" Description: This function runs through all the marks and displays or -" removes signs as appropriate. It is called on the CursorHold autocommand. -" We use the marked_{ln} variables (containing a timestamp) to track what marks -" we've shown (placed) in this call to ShowMarks; to only actually place the -" first mark on any particular line -- this forces only the first mark -" (according to the order of showmarks_include) to be shown (i.e., letters -" take precedence over marks like paragraph and sentence.) -fun! s:ShowMarks() - if g:showmarks_enable == 0 - return - endif - - if ((match(g:showmarks_ignore_type, "[Hh]") > -1) && (&buftype == "help" )) - \ || ((match(g:showmarks_ignore_type, "[Qq]") > -1) && (&buftype == "quickfix")) - \ || ((match(g:showmarks_ignore_type, "[Pp]") > -1) && (&pvw == 1 )) - \ || ((match(g:showmarks_ignore_type, "[Rr]") > -1) && (&readonly == 1 )) - \ || ((match(g:showmarks_ignore_type, "[Mm]") > -1) && (&modifiable == 0 )) - return - endif - - let n = 0 - let s:maxmarks = strlen(s:IncludeMarks()) - while n < s:maxmarks - let c = strpart(s:IncludeMarks(), n, 1) - let nm = s:NameOfMark(c) - let id = n + (s:maxmarks * winbufnr(0)) - let ln = line("'".c) - - if ln == 0 && (exists('b:placed_'.nm) && b:placed_{nm} != ln) - exe 'sign unplace '.id.' buffer='.winbufnr(0) - elseif ln > 1 || c !~ '[a-zA-Z]' - " Have we already placed a mark here in this call to ShowMarks? - if exists('mark_at'.ln) - " Already placed a mark, set the highlight to multiple - if c =~# '[a-zA-Z]' && b:ShowMarksLink{mark_at{ln}} != 'ShowMarksHLm' - let b:ShowMarksLink{mark_at{ln}} = 'ShowMarksHLm' - exe 'hi link '.s:ShowMarksDLink{mark_at{ln}}.mark_at{ln}.' '.b:ShowMarksLink{mark_at{ln}} - endif - else - if !exists('b:ShowMarksLink'.nm) || b:ShowMarksLink{nm} != s:ShowMarksDLink{nm} - let b:ShowMarksLink{nm} = s:ShowMarksDLink{nm} - exe 'hi link '.s:ShowMarksDLink{nm}.nm.' '.b:ShowMarksLink{nm} - endif - let mark_at{ln} = nm - if !exists('b:placed_'.nm) || b:placed_{nm} != ln - exe 'sign unplace '.id.' buffer='.winbufnr(0) - exe 'sign place '.id.' name=ShowMark'.nm.' line='.ln.' buffer='.winbufnr(0) - let b:placed_{nm} = ln - endif - endif - endif - let n = n + 1 - endw -endf - -" Function: ShowMarksClearMark() -" Description: This function hides the mark at the current line. -" It simply moves the mark to line 1 and removes the sign. -" Only marks a-z and A-Z are supported. -fun! s:ShowMarksClearMark() - let ln = line(".") - let n = 0 - let s:maxmarks = strlen(s:IncludeMarks()) - while n < s:maxmarks - let c = strpart(s:IncludeMarks(), n, 1) - if c =~# '[a-zA-Z]' && ln == line("'".c) - let nm = s:NameOfMark(c) - let id = n + (s:maxmarks * winbufnr(0)) - exe 'sign unplace '.id.' buffer='.winbufnr(0) - exe '1 mark '.c - let b:placed_{nm} = 1 - endif - let n = n + 1 - endw -endf - -" Function: ShowMarksClearAll() -" Description: This function clears all marks in the buffer. -" It simply moves the marks to line 1 and removes the signs. -" Only marks a-z and A-Z are supported. -fun! s:ShowMarksClearAll() - let n = 0 - let s:maxmarks = strlen(s:IncludeMarks()) - while n < s:maxmarks - let c = strpart(s:IncludeMarks(), n, 1) - if c =~# '[a-zA-Z]' - let nm = s:NameOfMark(c) - let id = n + (s:maxmarks * winbufnr(0)) - exe 'sign unplace '.id.' buffer='.winbufnr(0) - exe '1 mark '.c - let b:placed_{nm} = 1 - endif - let n = n + 1 - endw -endf - -" Function: ShowMarksHideAll() -" Description: This function hides all marks in the buffer. -" It simply removes the signs. -fun! s:ShowMarksHideAll() - let n = 0 - let s:maxmarks = strlen(s:IncludeMarks()) - while n < s:maxmarks - let c = strpart(s:IncludeMarks(), n, 1) - let nm = s:NameOfMark(c) - if exists('b:placed_'.nm) - let id = n + (s:maxmarks * winbufnr(0)) - exe 'sign unplace '.id.' buffer='.winbufnr(0) - unlet b:placed_{nm} - endif - let n = n + 1 - endw -endf - -" Function: ShowMarksPlaceMark() -" Description: This function will place the next unplaced mark (in priority -" order) to the current location. The idea here is to automate the placement -" of marks so the user doesn't have to remember which marks are placed or not. -" Hidden marks are considered to be unplaced. -" Only marks a-z are supported. -fun! s:ShowMarksPlaceMark() - " Find the first, next, and last [a-z] mark in showmarks_include (i.e. - " priority order), so we know where to "wrap". - let first_alpha_mark = -1 - let last_alpha_mark = -1 - let next_mark = -1 - - if !exists('b:previous_auto_mark') - let b:previous_auto_mark = -1 - endif - - " Find the next unused [a-z] mark (in priority order); if they're all - " used, find the next one after the previously auto-assigned mark. - let n = 0 - let s:maxmarks = strlen(s:IncludeMarks()) - while n < s:maxmarks - let c = strpart(s:IncludeMarks(), n, 1) - if c =~# '[a-z]' - if line("'".c) <= 1 - " Found an unused [a-z] mark; we're done. - let next_mark = n - break - endif - - if first_alpha_mark < 0 - let first_alpha_mark = n - endif - let last_alpha_mark = n - if n > b:previous_auto_mark && next_mark == -1 - let next_mark = n - endif - endif - let n = n + 1 - endw - - if next_mark == -1 && (b:previous_auto_mark == -1 || b:previous_auto_mark == last_alpha_mark) - " Didn't find an unused mark, and haven't placed any auto-chosen marks yet, - " or the previously placed auto-chosen mark was the last alpha mark -- - " use the first alpha mark this time. - let next_mark = first_alpha_mark - endif - - if (next_mark == -1) - echohl WarningMsg - echo 'No marks in [a-z] included! (No "next mark" to choose from)' - echohl None - return - endif - - let c = strpart(s:IncludeMarks(), next_mark, 1) - let b:previous_auto_mark = next_mark - exe 'mark '.c - call <sid>ShowMarks() -endf - -" ----------------------------------------------------------------------------- -" vim:ts=4:sw=4:noet diff --git a/vim/plugin/snipMate.vim b/vim/plugin/snipMate.vim deleted file mode 100644 index ef03b12..0000000 --- a/vim/plugin/snipMate.vim +++ /dev/null @@ -1,271 +0,0 @@ -" File: snipMate.vim -" Author: Michael Sanders -" Version: 0.84 -" Description: snipMate.vim implements some of TextMate's snippets features in -" Vim. A snippet is a piece of often-typed text that you can -" insert into your document using a trigger word followed by a "<tab>". -" -" For more help see snipMate.txt; you can do this by using: -" :helptags ~/.vim/doc -" :h snipMate.txt - -if exists('loaded_snips') || &cp || version < 700 - finish -endif -let loaded_snips = 1 -if !exists('snips_author') | let snips_author = 'Me' | endif - -au BufRead,BufNewFile *.snippets\= set ft=snippet -au FileType snippet setl noet fdm=indent - -let s:snippets = {} | let s:multi_snips = {} - -if !exists('snippets_dir') - let snippets_dir = substitute(globpath(&rtp, 'snippets/'), "\n", ',', 'g') -endif - -fun! MakeSnip(scope, trigger, content, ...) - let multisnip = a:0 && a:1 != '' - let var = multisnip ? 's:multi_snips' : 's:snippets' - if !has_key({var}, a:scope) | let {var}[a:scope] = {} | endif - if !has_key({var}[a:scope], a:trigger) - let {var}[a:scope][a:trigger] = multisnip ? [[a:1, a:content]] : a:content - elseif multisnip | let {var}[a:scope][a:trigger] += [[a:1, a:content]] - else - echom 'Warning in snipMate.vim: Snippet '.a:trigger.' is already defined.' - \ .' See :h multi_snip for help on snippets with multiple matches.' - endif -endf - -fun! ExtractSnips(dir, ft) - for path in split(globpath(a:dir, '*'), "\n") - if isdirectory(path) - let pathname = fnamemodify(path, ':t') - for snipFile in split(globpath(path, '*.snippet'), "\n") - call s:ProcessFile(snipFile, a:ft, pathname) - endfor - elseif fnamemodify(path, ':e') == 'snippet' - call s:ProcessFile(path, a:ft) - endif - endfor -endf - -" Processes a single-snippet file; optionally add the name of the parent -" directory for a snippet with multiple matches. -fun s:ProcessFile(file, ft, ...) - let keyword = fnamemodify(a:file, ':t:r') - if keyword == '' | return | endif - try - let text = join(readfile(a:file), "\n") - catch /E484/ - echom "Error in snipMate.vim: couldn't read file: ".a:file - endtry - return a:0 ? MakeSnip(a:ft, a:1, text, keyword) - \ : MakeSnip(a:ft, keyword, text) -endf - -fun! ExtractSnipsFile(file, ft) - if !filereadable(a:file) | return | endif - let text = readfile(a:file) - let inSnip = 0 - for line in text + ["\n"] - if inSnip && (line[0] == "\t" || line == '') - let content .= strpart(line, 1)."\n" - continue - elseif inSnip - call MakeSnip(a:ft, trigger, content[:-2], name) - let inSnip = 0 - endif - - if line[:6] == 'snippet' - let inSnip = 1 - let trigger = strpart(line, 8) - let name = '' - let space = stridx(trigger, ' ') + 1 - if space " Process multi snip - let name = strpart(trigger, space) - let trigger = strpart(trigger, 0, space - 1) - endif - let content = '' - endif - endfor -endf - -" Reset snippets for filetype. -fun! ResetSnippets(ft) - let ft = a:ft == '' ? '_' : a:ft - for dict in [s:snippets, s:multi_snips, g:did_ft] - if has_key(dict, ft) - unlet dict[ft] - endif - endfor -endf - -" Reset snippets for all filetypes. -fun! ResetAllSnippets() - let s:snippets = {} | let s:multi_snips = {} | let g:did_ft = {} -endf - -" Reload snippets for filetype. -fun! ReloadSnippets(ft) - let ft = a:ft == '' ? '_' : a:ft - call ResetSnippets(ft) - call GetSnippets(g:snippets_dir, ft) -endf - -" Reload snippets for all filetypes. -fun! ReloadAllSnippets() - for ft in keys(g:did_ft) - call ReloadSnippets(ft) - endfor -endf - -let g:did_ft = {} -fun! GetSnippets(dir, filetypes) - for ft in split(a:filetypes, '\.') - if has_key(g:did_ft, ft) | continue | endif - call s:DefineSnips(a:dir, ft, ft) - if ft == 'objc' || ft == 'cpp' || ft == 'cs' - call s:DefineSnips(a:dir, 'c', ft) - elseif ft == 'xhtml' - call s:DefineSnips(a:dir, 'html', 'xhtml') - endif - let g:did_ft[ft] = 1 - endfor -endf - -" Define "aliasft" snippets for the filetype "realft". -fun s:DefineSnips(dir, aliasft, realft) - for path in split(globpath(a:dir, a:aliasft.'/')."\n". - \ globpath(a:dir, a:aliasft.'-*/'), "\n") - call ExtractSnips(path, a:realft) - endfor - for path in split(globpath(a:dir, a:aliasft.'.snippets')."\n". - \ globpath(a:dir, a:aliasft.'-*.snippets'), "\n") - call ExtractSnipsFile(path, a:realft) - endfor -endf - -fun! TriggerSnippet() - if exists('g:SuperTabMappingForward') - if g:SuperTabMappingForward == "<tab>" - let SuperTabKey = "\<c-n>" - elseif g:SuperTabMappingBackward == "<tab>" - let SuperTabKey = "\<c-p>" - endif - endif - - if pumvisible() " Update snippet if completion is used, or deal with supertab - if exists('SuperTabKey') - call feedkeys(SuperTabKey) | return '' - endif - call feedkeys("\<esc>a", 'n') " Close completion menu - call feedkeys("\<tab>") | return '' - endif - - if exists('g:snipPos') | return snipMate#jumpTabStop(0) | endif - - let word = matchstr(getline('.'), '\S\+\%'.col('.').'c') - for scope in [bufnr('%')] + split(&ft, '\.') + ['_'] - let [trigger, snippet] = s:GetSnippet(word, scope) - " If word is a trigger for a snippet, delete the trigger & expand - " the snippet. - if snippet != '' - let col = col('.') - len(trigger) - sil exe 's/\V'.escape(trigger, '/\.').'\%#//' - return snipMate#expandSnip(snippet, col) - endif - endfor - - if exists('SuperTabKey') - call feedkeys(SuperTabKey) - return '' - endif - return "\<tab>" -endf - -fun! BackwardsSnippet() - if exists('g:snipPos') | return snipMate#jumpTabStop(1) | endif - - if exists('g:SuperTabMappingForward') - if g:SuperTabMappingBackward == "<s-tab>" - let SuperTabKey = "\<c-p>" - elseif g:SuperTabMappingForward == "<s-tab>" - let SuperTabKey = "\<c-n>" - endif - endif - if exists('SuperTabKey') - call feedkeys(SuperTabKey) - return '' - endif - return "\<s-tab>" -endf - -" Check if word under cursor is snippet trigger; if it isn't, try checking if -" the text after non-word characters is (e.g. check for "foo" in "bar.foo") -fun s:GetSnippet(word, scope) - let word = a:word | let snippet = '' - while snippet == '' - if exists('s:snippets["'.a:scope.'"]["'.escape(word, '\"').'"]') - let snippet = s:snippets[a:scope][word] - elseif exists('s:multi_snips["'.a:scope.'"]["'.escape(word, '\"').'"]') - let snippet = s:ChooseSnippet(a:scope, word) - if snippet == '' | break | endif - else - if match(word, '\W') == -1 | break | endif - let word = substitute(word, '.\{-}\W', '', '') - endif - endw - if word == '' && a:word != '.' && stridx(a:word, '.') != -1 - let [word, snippet] = s:GetSnippet('.', a:scope) - endif - return [word, snippet] -endf - -fun s:ChooseSnippet(scope, trigger) - let snippet = [] - let i = 1 - for snip in s:multi_snips[a:scope][a:trigger] - let snippet += [i.'. '.snip[0]] - let i += 1 - endfor - if i == 2 | return s:multi_snips[a:scope][a:trigger][0][1] | endif - let num = inputlist(snippet) - 1 - return num == -1 ? '' : s:multi_snips[a:scope][a:trigger][num][1] -endf - -fun! ShowAvailableSnips() - let line = getline('.') - let col = col('.') - let word = matchstr(getline('.'), '\S\+\%'.col.'c') - let words = [word] - if stridx(word, '.') - let words += split(word, '\.', 1) - endif - let matchlen = 0 - let matches = [] - for scope in [bufnr('%')] + split(&ft, '\.') + ['_'] - let triggers = has_key(s:snippets, scope) ? keys(s:snippets[scope]) : [] - if has_key(s:multi_snips, scope) - let triggers += keys(s:multi_snips[scope]) - endif - for trigger in triggers - for word in words - if word == '' - let matches += [trigger] " Show all matches if word is empty - elseif trigger =~ '^'.word - let matches += [trigger] - let len = len(word) - if len > matchlen | let matchlen = len | endif - endif - endfor - endfor - endfor - - " This is to avoid a bug with Vim when using complete(col - matchlen, matches) - " (Issue#46 on the Google Code snipMate issue tracker). - call setline(line('.'), substitute(line, repeat('.', matchlen).'\%'.col.'c', '', '')) - call complete(col, matches) - return '' -endf -" vim:noet:sw=4:ts=4:ft=vim diff --git a/vim/plugin/supertab.vim b/vim/plugin/supertab.vim deleted file mode 100644 index 67f8c5c..0000000 --- a/vim/plugin/supertab.vim +++ /dev/null @@ -1,737 +0,0 @@ -" Author: -" Original: Gergely Kontra <kgergely@mcl.hu> -" Current: Eric Van Dewoestine <ervandew@gmail.com> (as of version 0.4) -" Please direct all correspondence to Eric. -" Version: 1.6 -" GetLatestVimScripts: 1643 1 :AutoInstall: supertab.vim -" -" Description: {{{ -" Use your tab key to do all your completion in insert mode! -" You can cycle forward and backward with the <Tab> and <S-Tab> keys -" Note: you must press <Tab> once to be able to cycle back -" -" http://www.vim.org/scripts/script.php?script_id=1643 -" }}} -" -" License: {{{ -" Copyright (c) 2002 - 2011 -" All rights reserved. -" -" Redistribution and use of this software in source and binary forms, with -" or without modification, are permitted provided that the following -" conditions are met: -" -" * Redistributions of source code must retain the above -" copyright notice, this list of conditions and the -" following disclaimer. -" -" * Redistributions in binary form must reproduce the above -" copyright notice, this list of conditions and the -" following disclaimer in the documentation and/or other -" materials provided with the distribution. -" -" * Neither the name of Gergely Kontra or Eric Van Dewoestine nor the names -" of its contributors may be used to endorse or promote products derived -" from this software without specific prior written permission of Gergely -" Kontra or Eric Van Dewoestine. -" -" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -" IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -" THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -" CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -" EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -" PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -" LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -" NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -" SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -" }}} -" -" Testing Info: {{{ -" Running vim + supertab with the absolute bar minimum settings: -" $ vim -u NONE -U NONE -c "set nocp | runtime plugin/supertab.vim" -" }}} - -if v:version < 700 - finish -endif - -if exists('complType') " Integration with other completion functions. - finish -endif - -let s:save_cpo=&cpo -set cpo&vim - -" Global Variables {{{ - - if !exists("g:SuperTabDefaultCompletionType") - let g:SuperTabDefaultCompletionType = "<c-p>" - endif - - if !exists("g:SuperTabContextDefaultCompletionType") - let g:SuperTabContextDefaultCompletionType = "<c-p>" - endif - - if !exists("g:SuperTabCompletionContexts") - let g:SuperTabCompletionContexts = ['s:ContextText'] - endif - - if !exists("g:SuperTabRetainCompletionDuration") - let g:SuperTabRetainCompletionDuration = 'insert' - endif - - if !exists("g:SuperTabNoCompleteBefore") - " retain backwards compatability - if exists("g:SuperTabMidWordCompletion") && !g:SuperTabMidWordCompletion - let g:SuperTabNoCompleteBefore = ['\k'] - else - let g:SuperTabNoCompleteBefore = [] - endif - endif - - if !exists("g:SuperTabNoCompleteAfter") - " retain backwards compatability - if exists("g:SuperTabLeadingSpaceCompletion") && g:SuperTabLeadingSpaceCompletion - let g:SuperTabNoCompleteAfter = [] - else - let g:SuperTabNoCompleteAfter = ['\s'] - endif - endif - - if !exists("g:SuperTabMappingForward") - let g:SuperTabMappingForward = '<tab>' - endif - if !exists("g:SuperTabMappingBackward") - let g:SuperTabMappingBackward = '<s-tab>' - endif - - if !exists("g:SuperTabMappingTabLiteral") - let g:SuperTabMappingTabLiteral = '<c-tab>' - endif - - if !exists("g:SuperTabLongestEnhanced") - let g:SuperTabLongestEnhanced = 0 - endif - - if !exists("g:SuperTabLongestHighlight") - let g:SuperTabLongestHighlight = 0 - endif - - if !exists("g:SuperTabCrMapping") - let g:SuperTabCrMapping = 1 - endif - -" }}} - -" Script Variables {{{ - - " construct the help text. - let s:tabHelp = - \ "Hit <CR> or CTRL-] on the completion type you wish to switch to.\n" . - \ "Use :help ins-completion for more information.\n" . - \ "\n" . - \ "|<c-n>| - Keywords in 'complete' searching down.\n" . - \ "|<c-p>| - Keywords in 'complete' searching up (SuperTab default).\n" . - \ "|<c-x><c-l>| - Whole lines.\n" . - \ "|<c-x><c-n>| - Keywords in current file.\n" . - \ "|<c-x><c-k>| - Keywords in 'dictionary'.\n" . - \ "|<c-x><c-t>| - Keywords in 'thesaurus', thesaurus-style.\n" . - \ "|<c-x><c-i>| - Keywords in the current and included files.\n" . - \ "|<c-x><c-]>| - Tags.\n" . - \ "|<c-x><c-f>| - File names.\n" . - \ "|<c-x><c-d>| - Definitions or macros.\n" . - \ "|<c-x><c-v>| - Vim command-line.\n" . - \ "|<c-x><c-u>| - User defined completion.\n" . - \ "|<c-x><c-o>| - Omni completion.\n" . - \ "|<c-x>s| - Spelling suggestions." - - " set the available completion types and modes. - let s:types = - \ "\<c-e>\<c-y>\<c-l>\<c-n>\<c-k>\<c-t>\<c-i>\<c-]>" . - \ "\<c-f>\<c-d>\<c-v>\<c-n>\<c-p>\<c-u>\<c-o>\<c-n>\<c-p>s" - let s:modes = '/^E/^Y/^L/^N/^K/^T/^I/^]/^F/^D/^V/^P/^U/^O/s' - let s:types = s:types . "np" - let s:modes = s:modes . '/n/p' - -" }}} - -" SuperTabSetDefaultCompletionType(type) {{{ -" Globally available function that users can use to set the default -" completion type for the current buffer, like in an ftplugin. -function! SuperTabSetDefaultCompletionType(type) - " init hack for <c-x><c-v> workaround. - let b:complCommandLine = 0 - - let b:SuperTabDefaultCompletionType = a:type - - " set the current completion type to the default - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) -endfunction " }}} - -" SuperTabSetCompletionType(type) {{{ -" Globally available function that users can use to create mappings to quickly -" switch completion modes. Useful when a user wants to restore the default or -" switch to another mode without having to kick off a completion of that type -" or use SuperTabHelp. Note, this function only changes the current -" completion type, not the default, meaning that the default will still be -" restored once the configured retension duration has been met (see -" g:SuperTabRetainCompletionDuration). To change the default for the current -" buffer, use SuperTabDefaultCompletionType(type) instead. Example mapping to -" restore SuperTab default: -" nmap <F6> :call SetSuperTabCompletionType("<c-p>")<cr> -function! SuperTabSetCompletionType(type) - call s:InitBuffer() - exec "let b:complType = \"" . escape(a:type, '<') . "\"" -endfunction " }}} - -" SuperTabAlternateCompletion(type) {{{ -" Function which can be mapped to a key to kick off an alternate completion -" other than the default. For instance, if you have 'context' as the default -" and want to map ctrl+space to issue keyword completion. -" Note: due to the way vim expands ctrl characters in mappings, you cannot -" create the alternate mapping like so: -" imap <c-space> <c-r>=SuperTabAlternateCompletion("<c-p>")<cr> -" instead, you have to use \<lt> to prevent vim from expanding the key -" when creating the mapping. -" gvim: -" imap <c-space> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr> -" console: -" imap <nul> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr> -function! SuperTabAlternateCompletion(type) - call SuperTabSetCompletionType(a:type) - " end any current completion before attempting to start the new one. - " use feedkeys to prevent possible remapping of <c-e> from causing issues. - "call feedkeys("\<c-e>", 'n') - " ^ since we can't detect completion mode vs regular insert mode, we force - " vim into keyword completion mode and end that mode to prevent the regular - " insert behavior of <c-e> from occurring. - call feedkeys("\<c-x>\<c-p>\<c-e>", 'n') - call feedkeys(b:complType, 'n') - return '' -endfunction " }}} - -" SuperTabLongestHighlight(dir) {{{ -" When longest highlight is enabled, this function is used to do the actual -" selection of the completion popup entry. -function! SuperTabLongestHighlight(dir) - if !pumvisible() - return '' - endif - return a:dir == -1 ? "\<up>" : "\<down>" -endfunction " }}} - -" s:Init {{{ -" Global initilization when supertab is loaded. -function! s:Init() - " Setup mechanism to restore original completion type upon leaving insert - " mode if configured to do so - if g:SuperTabRetainCompletionDuration == 'insert' - augroup supertab_retain - autocmd! - autocmd InsertLeave * call s:SetDefaultCompletionType() - augroup END - endif -endfunction " }}} - -" s:InitBuffer {{{ -" Per buffer initilization. -function! s:InitBuffer() - if exists('b:SuperTabNoCompleteBefore') - return - endif - - let b:complReset = 0 - let b:complTypeManual = !exists('b:complTypeManual') ? '' : b:complTypeManual - let b:complTypeContext = '' - - " init hack for <c-x><c-v> workaround. - let b:complCommandLine = 0 - - if !exists('b:SuperTabNoCompleteBefore') - let b:SuperTabNoCompleteBefore = g:SuperTabNoCompleteBefore - endif - if !exists('b:SuperTabNoCompleteAfter') - let b:SuperTabNoCompleteAfter = g:SuperTabNoCompleteAfter - endif - - let b:SuperTabDefaultCompletionType = g:SuperTabDefaultCompletionType - - " set the current completion type to the default - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) -endfunction " }}} - -" s:ManualCompletionEnter() {{{ -" Handles manual entrance into completion mode. -function! s:ManualCompletionEnter() - if &smd - echo '' | echohl ModeMsg | echo '-- ^X++ mode (' . s:modes . ')' | echohl None - endif - let complType = nr2char(getchar()) - if stridx(s:types, complType) != -1 - if stridx("\<c-e>\<c-y>", complType) != -1 " no memory, just scroll... - return "\<c-x>" . complType - elseif stridx('np', complType) != -1 - let complType = nr2char(char2nr(complType) - 96) - else - let complType = "\<c-x>" . complType - endif - - let b:complTypeManual = complType - - if index(['insert', 'session'], g:SuperTabRetainCompletionDuration) != -1 - let b:complType = complType - endif - - " Hack to workaround bug when invoking command line completion via <c-r>= - if complType == "\<c-x>\<c-v>" - return s:CommandLineCompletion() - endif - - " optionally enable enhanced longest completion - if g:SuperTabLongestEnhanced && &completeopt =~ 'longest' - call s:EnableLongestEnhancement() - endif - - if g:SuperTabLongestHighlight && - \ &completeopt =~ 'longest' && - \ &completeopt =~ 'menu' && - \ !pumvisible() - let dir = (complType == "\<c-x>\<c-p>") ? -1 : 1 - call feedkeys("\<c-r>=SuperTabLongestHighlight(" . dir . ")\<cr>", 'n') - endif - - return complType - endif - - echohl "Unknown mode" - return complType -endfunction " }}} - -" s:SetCompletionType() {{{ -" Sets the completion type based on what the user has chosen from the help -" buffer. -function! s:SetCompletionType() - let chosen = substitute(getline('.'), '.*|\(.*\)|.*', '\1', '') - if chosen != getline('.') - let winnr = b:winnr - close - exec winnr . 'winc w' - call SuperTabSetCompletionType(chosen) - endif -endfunction " }}} - -" s:SetDefaultCompletionType() {{{ -function! s:SetDefaultCompletionType() - if exists('b:SuperTabDefaultCompletionType') && - \ (!exists('b:complCommandLine') || !b:complCommandLine) - call SuperTabSetCompletionType(b:SuperTabDefaultCompletionType) - endif -endfunction " }}} - -" s:SuperTab(command) {{{ -" Used to perform proper cycle navigation as the user requests the next or -" previous entry in a completion list, and determines whether or not to simply -" retain the normal usage of <tab> based on the cursor position. -function! s:SuperTab(command) - if exists('b:SuperTabDisabled') && b:SuperTabDisabled - return "\<tab>" - endif - - call s:InitBuffer() - - if s:WillComplete() - " optionally enable enhanced longest completion - if g:SuperTabLongestEnhanced && &completeopt =~ 'longest' - call s:EnableLongestEnhancement() - endif - - if !pumvisible() - let b:complTypeManual = '' - endif - - " exception: if in <c-p> mode, then <c-n> should move up the list, and - " <c-p> down the list. - if a:command == 'p' && !b:complReset && - \ (b:complType == "\<c-p>" || - \ (b:complType == 'context' && - \ b:complTypeManual == '' && - \ b:complTypeContext == "\<c-p>")) - return "\<c-n>" - - elseif a:command == 'p' && !b:complReset && - \ (b:complType == "\<c-n>" || - \ (b:complType == 'context' && - \ b:complTypeManual == '' && - \ b:complTypeContext == "\<c-n>")) - return "\<c-p>" - - " already in completion mode and not resetting for longest enhancement, so - " just scroll to next/previous - elseif pumvisible() && !b:complReset - let type = b:complType == 'context' ? b:complTypeContext : b:complType - if a:command == 'n' - return type == "\<c-p>" ? "\<c-p>" : "\<c-n>" - endif - return type == "\<c-p>" ? "\<c-n>" : "\<c-p>" - endif - - " handle 'context' completion. - if b:complType == 'context' - let complType = s:ContextCompletion() - if complType == '' - exec "let complType = \"" . - \ escape(g:SuperTabContextDefaultCompletionType, '<') . "\"" - endif - let b:complTypeContext = complType - - " Hack to workaround bug when invoking command line completion via <c-r>= - elseif b:complType == "\<c-x>\<c-v>" - let complType = s:CommandLineCompletion() - else - let complType = b:complType - endif - - " highlight first result if longest enabled - if g:SuperTabLongestHighlight && - \ &completeopt =~ 'longest' && - \ &completeopt =~ 'menu' && - \ (!pumvisible() || b:complReset) - let dir = (complType == "\<c-p>") ? -1 : 1 - call feedkeys("\<c-r>=SuperTabLongestHighlight(" . dir . ")\<cr>", 'n') - endif - - if b:complReset - let b:complReset = 0 - " not an accurate condition for everyone, but better than sending <c-e> - " at the wrong time. - if pumvisible() - return "\<c-e>" . complType - endif - endif - - return complType - endif - - return "\<tab>" -endfunction " }}} - -" s:SuperTabHelp() {{{ -" Opens a help window where the user can choose a completion type to enter. -function! s:SuperTabHelp() - let winnr = winnr() - if bufwinnr("SuperTabHelp") == -1 - botright split SuperTabHelp - - setlocal noswapfile - setlocal buftype=nowrite - setlocal bufhidden=delete - - let saved = @" - let @" = s:tabHelp - silent put - call cursor(1, 1) - silent 1,delete - call cursor(4, 1) - let @" = saved - exec "resize " . line('$') - - syntax match Special "|.\{-}|" - - setlocal readonly - setlocal nomodifiable - - nmap <silent> <buffer> <cr> :call <SID>SetCompletionType()<cr> - nmap <silent> <buffer> <c-]> :call <SID>SetCompletionType()<cr> - else - exec bufwinnr("SuperTabHelp") . "winc w" - endif - let b:winnr = winnr -endfunction " }}} - -" s:WillComplete() {{{ -" Determines if completion should be kicked off at the current location. -function! s:WillComplete() - if pumvisible() - return 1 - endif - - let line = getline('.') - let cnum = col('.') - - " Start of line. - if line =~ '^\s*\%' . cnum . 'c' - return 0 - endif - - " honor SuperTabNoCompleteAfter - let pre = line[:cnum - 2] - for pattern in b:SuperTabNoCompleteAfter - if pre =~ pattern . '$' - return 0 - endif - endfor - - " honor SuperTabNoCompleteBefore - " Within a word, but user does not have mid word completion enabled. - let post = line[cnum - 1:] - for pattern in b:SuperTabNoCompleteBefore - if post =~ '^' . pattern - return 0 - endif - endfor - - return 1 -endfunction " }}} - -" s:EnableLongestEnhancement() {{{ -function! s:EnableLongestEnhancement() - augroup supertab_reset - autocmd! - autocmd InsertLeave,CursorMovedI <buffer> - \ call s:ReleaseKeyPresses() | autocmd! supertab_reset - augroup END - call s:CaptureKeyPresses() -endfunction " }}} - -" s:CompletionReset(char) {{{ -function! s:CompletionReset(char) - let b:complReset = 1 - return a:char -endfunction " }}} - -" s:CaptureKeyPresses() {{{ -function! s:CaptureKeyPresses() - if !exists('b:capturing') || !b:capturing - let b:capturing = 1 - " save any previous mappings - " TODO: capture additional info provided by vim 7.3.032 and up. - let b:captured = { - \ '<bs>': maparg('<bs>', 'i'), - \ '<c-h>': maparg('<c-h>', 'i'), - \ } - " TODO: use &keyword to get an accurate list of chars to map - for c in split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_', '.\zs') - exec 'imap <buffer> ' . c . ' <c-r>=<SID>CompletionReset("' . c . '")<cr>' - endfor - imap <buffer> <bs> <c-r>=<SID>CompletionReset("\<lt>bs>")<cr> - imap <buffer> <c-h> <c-r>=<SID>CompletionReset("\<lt>c-h>")<cr> - endif -endfunction " }}} - -" s:ReleaseKeyPresses() {{{ -function! s:ReleaseKeyPresses() - if exists('b:capturing') && b:capturing - let b:capturing = 0 - for c in split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_', '.\zs') - exec 'iunmap <buffer> ' . c - endfor - - iunmap <buffer> <bs> - iunmap <buffer> <c-h> - - " restore any previous mappings - for [key, rhs] in items(b:captured) - if rhs != '' - let args = substitute(rhs, '.*\(".\{-}"\).*', '\1', '') - if args != rhs - let args = substitute(args, '<', '<lt>', 'g') - let expr = substitute(rhs, '\(.*\)".\{-}"\(.*\)', '\1%s\2', '') - let rhs = printf(expr, args) - endif - exec printf("imap <silent> %s %s", key, rhs) - endif - endfor - unlet b:captured - - if mode() == 'i' && &completeopt =~ 'menu' - " force full exit from completion mode (don't exit insert mode since - " that will break repeating with '.') - call feedkeys("\<space>\<bs>", 'n') - endif - endif -endfunction " }}} - -" s:CommandLineCompletion() {{{ -" Hack needed to account for apparent bug in vim command line mode completion -" when invoked via <c-r>= -function! s:CommandLineCompletion() - " This hack will trigger InsertLeave which will then invoke - " s:SetDefaultCompletionType. To prevent default completion from being - " restored prematurely, set an internal flag for s:SetDefaultCompletionType - " to check for. - let b:complCommandLine = 1 - return "\<c-\>\<c-o>:call feedkeys('\<c-x>\<c-v>\<c-v>', 'n') | " . - \ "let b:complCommandLine = 0\<cr>" -endfunction " }}} - -" s:ContextCompletion() {{{ -function! s:ContextCompletion() - let contexts = exists('b:SuperTabCompletionContexts') ? - \ b:SuperTabCompletionContexts : g:SuperTabCompletionContexts - - for context in contexts - try - let Context = function(context) - let complType = Context() - unlet Context - if type(complType) == 1 && complType != '' - return complType - endif - catch /E700/ - echohl Error - echom 'supertab: no context function "' . context . '" found.' - echohl None - endtry - endfor - return '' -endfunction " }}} - -" s:ContextDiscover() {{{ -function! s:ContextDiscover() - let discovery = exists('g:SuperTabContextDiscoverDiscovery') ? - \ g:SuperTabContextDiscoverDiscovery : [] - - " loop through discovery list to find the default - if !empty(discovery) - for pair in discovery - let var = substitute(pair, '\(.*\):.*', '\1', '') - let type = substitute(pair, '.*:\(.*\)', '\1', '') - exec 'let value = ' . var - if value !~ '^\s*$' && value != '0' - exec "let complType = \"" . escape(type, '<') . "\"" - return complType - endif - endfor - endif -endfunction " }}} - -" s:ContextText() {{{ -function! s:ContextText() - let exclusions = exists('g:SuperTabContextTextFileTypeExclusions') ? - \ g:SuperTabContextTextFileTypeExclusions : [] - - if index(exclusions, &ft) == -1 - let curline = getline('.') - let cnum = col('.') - let synname = synIDattr(synID(line('.'), cnum - 1, 1), 'name') - if curline =~ '.*/\w*\%' . cnum . 'c' || - \ ((has('win32') || has('win64')) && curline =~ '.*\\\w*\%' . cnum . 'c') - return "\<c-x>\<c-f>" - - elseif curline =~ '.*\(\w\|[\])]\)\(\.\|::\|->\)\w*\%' . cnum . 'c' && - \ synname !~ '\(String\|Comment\)' - let omniPrecedence = exists('g:SuperTabContextTextOmniPrecedence') ? - \ g:SuperTabContextTextOmniPrecedence : ['&completefunc', '&omnifunc'] - - for omniFunc in omniPrecedence - if omniFunc !~ '^&' - let omniFunc = '&' . omniFunc - endif - if getbufvar(bufnr('%'), omniFunc) != '' - return omniFunc == '&omnifunc' ? "\<c-x>\<c-o>" : "\<c-x>\<c-u>" - endif - endfor - endif - endif -endfunction " }}} - -" s:ExpandMap(map) {{{ -function! s:ExpandMap(map) - let map = a:map - if map =~ '<Plug>' - let plug = substitute(map, '.\{-}\(<Plug>\w\+\).*', '\1', '') - let plug_map = maparg(plug, 'i') - let map = substitute(map, '.\{-}\(<Plug>\w\+\).*', plug_map, '') - endif - return map -endfunction " }}} - -" Key Mappings {{{ - " map a regular tab to ctrl-tab (note: doesn't work in console vim) - exec 'inoremap ' . g:SuperTabMappingTabLiteral . ' <tab>' - - imap <c-x> <c-r>=<SID>ManualCompletionEnter()<cr> - - imap <script> <Plug>SuperTabForward <c-r>=<SID>SuperTab('n')<cr> - imap <script> <Plug>SuperTabBackward <c-r>=<SID>SuperTab('p')<cr> - - exec 'imap ' . g:SuperTabMappingForward . ' <Plug>SuperTabForward' - exec 'imap ' . g:SuperTabMappingBackward . ' <Plug>SuperTabBackward' - - " After hitting <Tab>, hitting it once more will go to next match - " (because in XIM mode <c-n> and <c-p> mappings are ignored) - " and wont start a brand new completion - " The side effect, that in the beginning of line <c-n> and <c-p> inserts a - " <Tab>, but I hope it may not be a problem... - let ctrl_n = maparg('<c-n>', 'i') - if ctrl_n != '' - let ctrl_n = substitute(ctrl_n, '<', '<lt>', 'g') - exec 'imap <c-n> <c-r>=<SID>ForwardBack("n", "' . ctrl_n . '")<cr>' - else - imap <c-n> <Plug>SuperTabForward - endif - let ctrl_p = maparg('<c-p>', 'i') - if ctrl_p != '' - let ctrl_p = substitute(ctrl_p, '<', '<lt>', 'g') - exec 'imap <c-p> <c-r>=<SID>ForwardBack("p", "' . ctrl_p . '")<cr>' - else - imap <c-p> <Plug>SuperTabBackward - endif - function! s:ForwardBack(command, map) - exec "let map = \"" . escape(a:map, '<') . "\"" - return pumvisible() ? s:SuperTab(a:command) : map - endfunction - - if g:SuperTabCrMapping - if maparg('<CR>','i') =~ '<CR>' - let map = maparg('<cr>', 'i') - let cr = (map =~? '\(^\|[^)]\)<cr>') - let map = s:ExpandMap(map) - exec "inoremap <script> <cr> <c-r>=<SID>SelectCompletion(" . cr . ")<cr>" . map - else - inoremap <cr> <c-r>=<SID>SelectCompletion(1)<cr> - endif - function! s:SelectCompletion(cr) - " selecting a completion - if pumvisible() - " ugly hack to let other <cr> mappings for other plugins cooperate - " with supertab - let b:supertab_pumwasvisible = 1 - return "\<c-y>" - endif - - " only needed when chained with other mappings and one of them will - " issue a <cr>. - if exists('b:supertab_pumwasvisible') && !a:cr - unlet b:supertab_pumwasvisible - return '' - endif - - " not so pleasant hack to keep <cr> working for abbreviations - let word = substitute(getline('.'), '^.*\s\+\(.*\%' . col('.') . 'c\).*', '\1', '') - if maparg(word, 'i', 1) != '' - call feedkeys("\<c-]>", 't') - call feedkeys("\<cr>", 'n') - return '' - endif - - " only return a cr if nothing else is mapped to it since we don't want - " to duplicate a cr returned by another mapping. - return a:cr ? "\<cr>" : "" - endfunction - endif -" }}} - -" Command Mappings {{{ - if !exists(":SuperTabHelp") - command SuperTabHelp :call <SID>SuperTabHelp() - endif -" }}} - -call s:Init() - -let &cpo = s:save_cpo - -" vim:ft=vim:fdm=marker diff --git a/vim/plugin/surround.vim b/vim/plugin/surround.vim deleted file mode 100644 index ea28c02..0000000 --- a/vim/plugin/surround.vim +++ /dev/null @@ -1,625 +0,0 @@ -" surround.vim - Surroundings -" Author: Tim Pope <vimNOSPAM@tpope.org> -" Version: 1.90 -" GetLatestVimScripts: 1697 1 :AutoInstall: surround.vim -" -" See surround.txt for help. This can be accessed by doing -" -" :helptags ~/.vim/doc -" :help surround -" -" Licensed under the same terms as Vim itself. - -" ============================================================================ - -" Exit quickly when: -" - this plugin was already loaded or disabled -" - when 'compatible' is set -if (exists("g:loaded_surround") && g:loaded_surround) || &cp - finish -endif -let g:loaded_surround = 1 - -let s:cpo_save = &cpo -set cpo&vim - -" Input functions {{{1 - -function! s:getchar() - let c = getchar() - if c =~ '^\d\+$' - let c = nr2char(c) - endif - return c -endfunction - -function! s:inputtarget() - let c = s:getchar() - while c =~ '^\d\+$' - let c = c . s:getchar() - endwhile - if c == " " - let c = c . s:getchar() - endif - if c =~ "\<Esc>\|\<C-C>\|\0" - return "" - else - return c - endif -endfunction - -function! s:inputreplacement() - "echo '-- SURROUND --' - let c = s:getchar() - if c == " " - let c = c . s:getchar() - endif - if c =~ "\<Esc>" || c =~ "\<C-C>" - return "" - else - return c - endif -endfunction - -function! s:beep() - exe "norm! \<Esc>" - return "" -endfunction - -function! s:redraw() - redraw - return "" -endfunction - -" }}}1 - -" Wrapping functions {{{1 - -function! s:extractbefore(str) - if a:str =~ '\r' - return matchstr(a:str,'.*\ze\r') - else - return matchstr(a:str,'.*\ze\n') - endif -endfunction - -function! s:extractafter(str) - if a:str =~ '\r' - return matchstr(a:str,'\r\zs.*') - else - return matchstr(a:str,'\n\zs.*') - endif -endfunction - -function! s:repeat(str,count) - let cnt = a:count - let str = "" - while cnt > 0 - let str = str . a:str - let cnt = cnt - 1 - endwhile - return str -endfunction - -function! s:fixindent(str,spc) - let str = substitute(a:str,'\t',s:repeat(' ',&sw),'g') - let spc = substitute(a:spc,'\t',s:repeat(' ',&sw),'g') - let str = substitute(str,'\(\n\|\%^\).\@=','\1'.spc,'g') - if ! &et - let str = substitute(str,'\s\{'.&ts.'\}',"\t",'g') - endif - return str -endfunction - -function! s:process(string) - let i = 0 - while i < 7 - let i = i + 1 - let repl_{i} = '' - let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i)) - if m != '' - let m = substitute(strpart(m,1),'\r.*','','') - let repl_{i} = input(substitute(m,':\s*$','','').': ') - endif - endwhile - let s = "" - let i = 0 - while i < strlen(a:string) - let char = strpart(a:string,i,1) - if char2nr(char) < 8 - let next = stridx(a:string,char,i+1) - if next == -1 - let s = s . char - else - let insertion = repl_{char2nr(char)} - let subs = strpart(a:string,i+1,next-i-1) - let subs = matchstr(subs,'\r.*') - while subs =~ '^\r.*\r' - let sub = matchstr(subs,"^\r\\zs[^\r]*\r[^\r]*") - let subs = strpart(subs,strlen(sub)+1) - let r = stridx(sub,"\r") - let insertion = substitute(insertion,strpart(sub,0,r),strpart(sub,r+1),'') - endwhile - let s = s . insertion - let i = next - endif - else - let s = s . char - endif - let i = i + 1 - endwhile - return s -endfunction - -function! s:wrap(string,char,type,...) - let keeper = a:string - let newchar = a:char - let type = a:type - let linemode = type ==# 'V' ? 1 : 0 - let special = a:0 ? a:1 : 0 - let before = "" - let after = "" - if type ==# "V" - let initspaces = matchstr(keeper,'\%^\s*') - else - let initspaces = matchstr(getline('.'),'\%^\s*') - endif - " Duplicate b's are just placeholders (removed) - let pairs = "b()B{}r[]a<>" - let extraspace = "" - if newchar =~ '^ ' - let newchar = strpart(newchar,1) - let extraspace = ' ' - endif - let idx = stridx(pairs,newchar) - if newchar == ' ' - let before = '' - let after = '' - elseif exists("b:surround_".char2nr(newchar)) - let all = s:process(b:surround_{char2nr(newchar)}) - let before = s:extractbefore(all) - let after = s:extractafter(all) - elseif exists("g:surround_".char2nr(newchar)) - let all = s:process(g:surround_{char2nr(newchar)}) - let before = s:extractbefore(all) - let after = s:extractafter(all) - elseif newchar ==# "p" - let before = "\n" - let after = "\n\n" - elseif newchar =~# "[tT\<C-T><,]" - let dounmapp = 0 - let dounmapb = 0 - if !maparg(">","c") - let dounmapb= 1 - " Hide from AsNeeded - exe "cn"."oremap > <CR>" - endif - let default = "" - if newchar ==# "T" - if !exists("s:lastdel") - let s:lastdel = "" - endif - let default = matchstr(s:lastdel,'<\zs.\{-\}\ze>') - endif - let tag = input("<",default) - echo "<".substitute(tag,'>*$','>','') - if dounmapb - silent! cunmap > - endif - if tag != "" - let tag = substitute(tag,'>*$','','') - let before = '<'.tag.'>' - if tag =~ '/$' - let after = '' - else - let after = '</'.substitute(tag,' .*','','').'>' - endif - if newchar == "\<C-T>" || newchar == "," - if type ==# "v" || type ==# "V" - let before = before . "\n\t" - endif - if type ==# "v" - let after = "\n". after - endif - endif - endif - elseif newchar ==# 'l' || newchar == '\' - " LaTeX - let env = input('\begin{') - let env = '{' . env - let env = env . s:closematch(env) - echo '\begin'.env - if env != "" - let before = '\begin'.env - let after = '\end'.matchstr(env,'[^}]*').'}' - endif - "if type ==# 'v' || type ==# 'V' - "let before = before ."\n\t" - "endif - "if type ==# 'v' - "let after = "\n".initspaces.after - "endif - elseif newchar ==# 'f' || newchar ==# 'F' - let fnc = input('function: ') - if fnc != "" - let before = substitute(fnc,'($','','').'(' - let after = ')' - if newchar ==# 'F' - let before = before . ' ' - let after = ' ' . after - endif - endif - elseif idx >= 0 - let spc = (idx % 3) == 1 ? " " : "" - let idx = idx / 3 * 3 - let before = strpart(pairs,idx+1,1) . spc - let after = spc . strpart(pairs,idx+2,1) - elseif newchar == "\<C-[>" || newchar == "\<C-]>" - let before = "{\n\t" - let after = "\n}" - elseif newchar !~ '\a' - let before = newchar - let after = newchar - else - let before = '' - let after = '' - endif - "let before = substitute(before,'\n','\n'.initspaces,'g') - let after = substitute(after ,'\n','\n'.initspaces,'g') - "let after = substitute(after,"\n\\s*\<C-U>\\s*",'\n','g') - if type ==# 'V' || (special && type ==# "v") - let before = substitute(before,' \+$','','') - let after = substitute(after ,'^ \+','','') - if after !~ '^\n' - let after = initspaces.after - endif - if keeper !~ '\n$' && after !~ '^\n' - let keeper = keeper . "\n" - elseif keeper =~ '\n$' && after =~ '^\n' - let after = strpart(after,1) - endif - if before !~ '\n\s*$' - let before = before . "\n" - if special - let before = before . "\t" - endif - endif - endif - if type ==# 'V' - let before = initspaces.before - endif - if before =~ '\n\s*\%$' - if type ==# 'v' - let keeper = initspaces.keeper - endif - let padding = matchstr(before,'\n\zs\s\+\%$') - let before = substitute(before,'\n\s\+\%$','\n','') - let keeper = s:fixindent(keeper,padding) - endif - if type ==# 'V' - let keeper = before.keeper.after - elseif type =~ "^\<C-V>" - " Really we should be iterating over the buffer - let repl = substitute(before,'[\\~]','\\&','g').'\1'.substitute(after,'[\\~]','\\&','g') - let repl = substitute(repl,'\n',' ','g') - let keeper = substitute(keeper."\n",'\(.\{-\}\)\(\n\)',repl.'\n','g') - let keeper = substitute(keeper,'\n\%$','','') - else - let keeper = before.extraspace.keeper.extraspace.after - endif - return keeper -endfunction - -function! s:wrapreg(reg,char,...) - let orig = getreg(a:reg) - let type = substitute(getregtype(a:reg),'\d\+$','','') - let special = a:0 ? a:1 : 0 - let new = s:wrap(orig,a:char,type,special) - call setreg(a:reg,new,type) -endfunction -" }}}1 - -function! s:insert(...) " {{{1 - " Optional argument causes the result to appear on 3 lines, not 1 - "call inputsave() - let linemode = a:0 ? a:1 : 0 - let char = s:inputreplacement() - while char == "\<CR>" || char == "\<C-S>" - " TODO: use total count for additional blank lines - let linemode = linemode + 1 - let char = s:inputreplacement() - endwhile - "call inputrestore() - if char == "" - return "" - endif - "call inputsave() - let cb_save = &clipboard - set clipboard-=unnamed - let reg_save = @@ - call setreg('"',"\r",'v') - call s:wrapreg('"',char,linemode) - " If line mode is used and the surrounding consists solely of a suffix, - " remove the initial newline. This fits a use case of mine but is a - " little inconsistent. Is there anyone that would prefer the simpler - " behavior of just inserting the newline? - if linemode && match(getreg('"'),'^\n\s*\zs.*') == 0 - call setreg('"',matchstr(getreg('"'),'^\n\s*\zs.*'),getregtype('"')) - endif - " This can be used to append a placeholder to the end - if exists("g:surround_insert_tail") - call setreg('"',g:surround_insert_tail,"a".getregtype('"')) - endif - "if linemode - "call setreg('"',substitute(getreg('"'),'^\s\+','',''),'c') - "endif - if col('.') >= col('$') - norm! ""p - else - norm! ""P - endif - if linemode - call s:reindent() - endif - norm! `] - call search('\r','bW') - let @@ = reg_save - let &clipboard = cb_save - return "\<Del>" -endfunction " }}}1 - -function! s:reindent() " {{{1 - if exists("b:surround_indent") ? b:surround_indent : (exists("g:surround_indent") && g:surround_indent) - silent norm! '[='] - endif -endfunction " }}}1 - -function! s:dosurround(...) " {{{1 - let scount = v:count1 - let char = (a:0 ? a:1 : s:inputtarget()) - let spc = "" - if char =~ '^\d\+' - let scount = scount * matchstr(char,'^\d\+') - let char = substitute(char,'^\d\+','','') - endif - if char =~ '^ ' - let char = strpart(char,1) - let spc = 1 - endif - if char == 'a' - let char = '>' - endif - if char == 'r' - let char = ']' - endif - let newchar = "" - if a:0 > 1 - let newchar = a:2 - if newchar == "\<Esc>" || newchar == "\<C-C>" || newchar == "" - return s:beep() - endif - endif - let cb_save = &clipboard - set clipboard-=unnamed - let append = "" - let original = getreg('"') - let otype = getregtype('"') - call setreg('"',"") - let strcount = (scount == 1 ? "" : scount) - if char == '/' - exe 'norm! '.strcount.'[/d'.strcount.']/' - else - exe 'norm! d'.strcount.'i'.char - endif - let keeper = getreg('"') - let okeeper = keeper " for reindent below - if keeper == "" - call setreg('"',original,otype) - let &clipboard = cb_save - return "" - endif - let oldline = getline('.') - let oldlnum = line('.') - if char ==# "p" - call setreg('"','','V') - elseif char ==# "s" || char ==# "w" || char ==# "W" - " Do nothing - call setreg('"','') - elseif char =~ "[\"'`]" - exe "norm! i \<Esc>d2i".char - call setreg('"',substitute(getreg('"'),' ','','')) - elseif char == '/' - norm! "_x - call setreg('"','/**/',"c") - let keeper = substitute(substitute(keeper,'^/\*\s\=','',''),'\s\=\*$','','') - else - " One character backwards - call search('.','bW') - exe "norm! da".char - endif - let removed = getreg('"') - let rem2 = substitute(removed,'\n.*','','') - let oldhead = strpart(oldline,0,strlen(oldline)-strlen(rem2)) - let oldtail = strpart(oldline, strlen(oldline)-strlen(rem2)) - let regtype = getregtype('"') - if char =~# '[\[({<T]' || spc - let keeper = substitute(keeper,'^\s\+','','') - let keeper = substitute(keeper,'\s\+$','','') - endif - if col("']") == col("$") && col('.') + 1 == col('$') - if oldhead =~# '^\s*$' && a:0 < 2 - let keeper = substitute(keeper,'\%^\n'.oldhead.'\(\s*.\{-\}\)\n\s*\%$','\1','') - endif - let pcmd = "p" - else - let pcmd = "P" - endif - if line('.') < oldlnum && regtype ==# "V" - let pcmd = "p" - endif - call setreg('"',keeper,regtype) - if newchar != "" - call s:wrapreg('"',newchar) - endif - silent exe 'norm! ""'.pcmd.'`[' - if removed =~ '\n' || okeeper =~ '\n' || getreg('"') =~ '\n' - call s:reindent() - endif - if getline('.') =~ '^\s\+$' && keeper =~ '^\s*\n' - silent norm! cc - endif - call setreg('"',removed,regtype) - let s:lastdel = removed - let &clipboard = cb_save - if newchar == "" - silent! call repeat#set("\<Plug>Dsurround".char,scount) - else - silent! call repeat#set("\<Plug>Csurround".char.newchar,scount) - endif -endfunction " }}}1 - -function! s:changesurround() " {{{1 - let a = s:inputtarget() - if a == "" - return s:beep() - endif - let b = s:inputreplacement() - if b == "" - return s:beep() - endif - call s:dosurround(a,b) -endfunction " }}}1 - -function! s:opfunc(type,...) " {{{1 - let char = s:inputreplacement() - if char == "" - return s:beep() - endif - let reg = '"' - let sel_save = &selection - let &selection = "inclusive" - let cb_save = &clipboard - set clipboard-=unnamed - let reg_save = getreg(reg) - let reg_type = getregtype(reg) - "call setreg(reg,"\n","c") - let type = a:type - if a:type == "char" - silent exe 'norm! v`[o`]"'.reg.'y' - let type = 'v' - elseif a:type == "line" - silent exe 'norm! `[V`]"'.reg.'y' - let type = 'V' - elseif a:type ==# "v" || a:type ==# "V" || a:type ==# "\<C-V>" - let ve = &virtualedit - if !(a:0 && a:1) - set virtualedit= - endif - silent exe 'norm! gv"'.reg.'y' - let &virtualedit = ve - elseif a:type =~ '^\d\+$' - let type = 'v' - silent exe 'norm! ^v'.a:type.'$h"'.reg.'y' - if mode() ==# 'v' - norm! v - return s:beep() - endif - else - let &selection = sel_save - let &clipboard = cb_save - return s:beep() - endif - let keeper = getreg(reg) - if type ==# "v" && a:type !=# "v" - let append = matchstr(keeper,'\_s\@<!\s*$') - let keeper = substitute(keeper,'\_s\@<!\s*$','','') - endif - call setreg(reg,keeper,type) - call s:wrapreg(reg,char,a:0 && a:1) - if type ==# "v" && a:type !=# "v" && append != "" - call setreg(reg,append,"ac") - endif - silent exe 'norm! gv'.(reg == '"' ? '' : '"' . reg).'p`[' - if type ==# 'V' || (getreg(reg) =~ '\n' && type ==# 'v') - call s:reindent() - endif - call setreg(reg,reg_save,reg_type) - let &selection = sel_save - let &clipboard = cb_save - if a:type =~ '^\d\+$' - silent! call repeat#set("\<Plug>Y".(a:0 && a:1 ? "S" : "s")."surround".char,a:type) - endif -endfunction - -function! s:opfunc2(arg) - call s:opfunc(a:arg,1) -endfunction " }}}1 - -function! s:closematch(str) " {{{1 - " Close an open (, {, [, or < on the command line. - let tail = matchstr(a:str,'.[^\[\](){}<>]*$') - if tail =~ '^\[.\+' - return "]" - elseif tail =~ '^(.\+' - return ")" - elseif tail =~ '^{.\+' - return "}" - elseif tail =~ '^<.+' - return ">" - else - return "" - endif -endfunction " }}}1 - -nnoremap <silent> <Plug>Dsurround :<C-U>call <SID>dosurround(<SID>inputtarget())<CR> -nnoremap <silent> <Plug>Csurround :<C-U>call <SID>changesurround()<CR> -nnoremap <silent> <Plug>Yssurround :<C-U>call <SID>opfunc(v:count1)<CR> -nnoremap <silent> <Plug>YSsurround :<C-U>call <SID>opfunc2(v:count1)<CR> -" <C-U> discards the numerical argument but there's not much we can do with it -nnoremap <silent> <Plug>Ysurround :<C-U>set opfunc=<SID>opfunc<CR>g@ -nnoremap <silent> <Plug>YSurround :<C-U>set opfunc=<SID>opfunc2<CR>g@ -vnoremap <silent> <Plug>Vsurround :<C-U>call <SID>opfunc(visualmode())<CR> -vnoremap <silent> <Plug>VSurround :<C-U>call <SID>opfunc(visualmode(),visualmode() ==# 'V' ? 1 : 0)<CR> -vnoremap <silent> <Plug>VgSurround :<C-U>call <SID>opfunc(visualmode(),visualmode() ==# 'V' ? 0 : 1)<CR> -inoremap <silent> <Plug>Isurround <C-R>=<SID>insert()<CR> -inoremap <silent> <Plug>ISurround <C-R>=<SID>insert(1)<CR> - -if !exists("g:surround_no_mappings") || ! g:surround_no_mappings - nmap ds <Plug>Dsurround - nmap cs <Plug>Csurround - nmap ys <Plug>Ysurround - nmap yS <Plug>YSurround - nmap yss <Plug>Yssurround - nmap ySs <Plug>YSsurround - nmap ySS <Plug>YSsurround - if !hasmapto("<Plug>Vsurround","v") && !hasmapto("<Plug>VSurround","v") - if exists(":xmap") - xmap s <Plug>Vsurround - else - vmap s <Plug>Vsurround - endif - endif - if !hasmapto("<Plug>VSurround","v") - if exists(":xmap") - xmap S <Plug>VSurround - else - vmap S <Plug>VSurround - endif - endif - if exists(":xmap") - xmap gS <Plug>VgSurround - else - vmap gS <Plug>VgSurround - endif - if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i") - imap <C-S> <Plug>Isurround - endif - imap <C-G>s <Plug>Isurround - imap <C-G>S <Plug>ISurround - "Implemented internally instead - "imap <C-S><C-S> <Plug>ISurround -endif - -let &cpo = s:cpo_save - -" vim:set ft=vim sw=2 sts=2 et: diff --git a/vim/plugin/syntastic.vim b/vim/plugin/syntastic.vim deleted file mode 100644 index 0eb657a..0000000 --- a/vim/plugin/syntastic.vim +++ /dev/null @@ -1,614 +0,0 @@ -"============================================================================ -"File: syntastic.vim -"Description: vim plugin for on the fly syntax checking -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"Version: 2.3.0 -"Last Change: 16 Feb, 2012 -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists("g:loaded_syntastic_plugin") - finish -endif -let g:loaded_syntastic_plugin = 1 - -let s:running_windows = has("win16") || has("win32") || has("win64") - -if !s:running_windows - let s:uname = system('uname') -endif - -if !exists("g:syntastic_enable_signs") - let g:syntastic_enable_signs = 1 -endif -if !has('signs') - let g:syntastic_enable_signs = 0 -endif - -if !exists("g:syntastic_enable_balloons") - let g:syntastic_enable_balloons = 1 -endif -if !has('balloon_eval') - let g:syntastic_enable_balloons = 0 -endif - -if !exists("g:syntastic_enable_highlighting") - let g:syntastic_enable_highlighting = 1 -endif - -if !exists("g:syntastic_echo_current_error") - let g:syntastic_echo_current_error = 1 -endif - -if !exists("g:syntastic_auto_loc_list") - let g:syntastic_auto_loc_list = 2 -endif - -if !exists("g:syntastic_auto_jump") - let syntastic_auto_jump=0 -endif - -if !exists("g:syntastic_quiet_warnings") - let g:syntastic_quiet_warnings = 0 -endif - -if !exists("g:syntastic_stl_format") - let g:syntastic_stl_format = '[Syntax: line:%F (%t)]' -endif - -if !exists("g:syntastic_mode_map") - let g:syntastic_mode_map = {} -endif - -if !has_key(g:syntastic_mode_map, "mode") - let g:syntastic_mode_map['mode'] = 'active' -endif - -if !has_key(g:syntastic_mode_map, "active_filetypes") - let g:syntastic_mode_map['active_filetypes'] = [] -endif - -if !has_key(g:syntastic_mode_map, "passive_filetypes") - let g:syntastic_mode_map['passive_filetypes'] = [] -endif - -if !exists("g:syntastic_check_on_open") - let g:syntastic_check_on_open = 0 -endif - -if !exists("g:syntastic_loc_list_height") - let g:syntastic_loc_list_height = 10 -endif - -command! SyntasticToggleMode call s:ToggleMode() -command! SyntasticCheck call s:UpdateErrors(0) <bar> redraw! -command! Errors call s:ShowLocList() - -highlight link SyntasticError SpellBad -highlight link SyntasticWarning SpellCap - -augroup syntastic - if g:syntastic_echo_current_error - autocmd cursormoved * call s:EchoCurrentError() - endif - - autocmd BufReadPost * if g:syntastic_check_on_open | call s:UpdateErrors(1) | endif - autocmd BufWritePost * call s:UpdateErrors(1) - - autocmd BufWinEnter * if empty(&bt) | call s:AutoToggleLocList() | endif - autocmd BufWinLeave * if empty(&bt) | lclose | endif -augroup END - - -"refresh and redraw all the error info for this buf when saving or reading -function! s:UpdateErrors(auto_invoked) - if !empty(&buftype) - return - endif - - if !a:auto_invoked || s:ModeMapAllowsAutoChecking() - call s:CacheErrors() - end - - if s:BufHasErrorsOrWarningsToDisplay() - call setloclist(0, s:LocList()) - endif - - if g:syntastic_enable_balloons - call s:RefreshBalloons() - endif - - if g:syntastic_enable_signs - call s:RefreshSigns() - endif - - if g:syntastic_auto_jump && s:BufHasErrorsOrWarningsToDisplay() - silent! ll - endif - - call s:AutoToggleLocList() -endfunction - -"automatically open/close the location list window depending on the users -"config and buffer error state -function! s:AutoToggleLocList() - if s:BufHasErrorsOrWarningsToDisplay() - if g:syntastic_auto_loc_list == 1 - call s:ShowLocList() - endif - else - if g:syntastic_auto_loc_list > 0 - - "TODO: this will close the loc list window if one was opened by - "something other than syntastic - lclose - endif - endif -endfunction - -"lazy init the loc list for the current buffer -function! s:LocList() - if !exists("b:syntastic_loclist") - let b:syntastic_loclist = [] - endif - return b:syntastic_loclist -endfunction - -"clear the loc list for the buffer -function! s:ClearLocList() - let b:syntastic_loclist = [] -endfunction - -"detect and cache all syntax errors in this buffer -" -"depends on a function called SyntaxCheckers_{&ft}_GetLocList() existing -"elsewhere -function! s:CacheErrors() - call s:ClearLocList() - - if filereadable(expand("%")) - - "sub - for _ in filetypes otherwise we cant name syntax checker - "functions legally for filetypes like "gentoo-metadata" - let fts = substitute(&ft, '-', '_', 'g') - for ft in split(fts, '\.') - if s:Checkable(ft) - let errors = SyntaxCheckers_{ft}_GetLocList() - "make errors have type "E" by default - call SyntasticAddToErrors(errors, {'type': 'E'}) - call extend(s:LocList(), errors) - endif - endfor - endif -endfunction - -"toggle the g:syntastic_mode_map['mode'] -function! s:ToggleMode() - if g:syntastic_mode_map['mode'] == "active" - let g:syntastic_mode_map['mode'] = "passive" - else - let g:syntastic_mode_map['mode'] = "active" - endif - - call s:ClearLocList() - call s:UpdateErrors(1) - - echo "Syntastic: " . g:syntastic_mode_map['mode'] . " mode enabled" -endfunction - -"check the current filetypes against g:syntastic_mode_map to determine whether -"active mode syntax checking should be done -function! s:ModeMapAllowsAutoChecking() - let fts = split(&ft, '\.') - - if g:syntastic_mode_map['mode'] == 'passive' - "check at least one filetype is active - let actives = g:syntastic_mode_map["active_filetypes"] - return !empty(filter(fts, 'index(actives, v:val) != -1')) - else - "check no filetypes are passive - let passives = g:syntastic_mode_map["passive_filetypes"] - return empty(filter(fts, 'index(passives, v:val) != -1')) - endif -endfunction - -"return true if there are cached errors/warnings for this buf -function! s:BufHasErrorsOrWarnings() - return !empty(s:LocList()) -endfunction - -"return true if there are cached errors for this buf -function! s:BufHasErrors() - return len(s:ErrorsForType('E')) > 0 -endfunction - -function! s:BufHasErrorsOrWarningsToDisplay() - return s:BufHasErrors() || (!g:syntastic_quiet_warnings && s:BufHasErrorsOrWarnings()) -endfunction - -function! s:ErrorsForType(type) - return s:FilterLocList({'type': a:type}) -endfunction - -function! s:Errors() - return s:ErrorsForType("E") -endfunction - -function! s:Warnings() - return s:ErrorsForType("W") -endfunction - -"Filter a loc list (defaults to s:LocList()) by a:filters -"e.g. -" s:FilterLocList({'bufnr': 10, 'type': 'e'}) -" -"would return all errors in s:LocList() for buffer 10. -" -"Note that all comparisons are done with ==? -function! s:FilterLocList(filters, ...) - let llist = a:0 ? a:1 : s:LocList() - - let rv = deepcopy(llist) - for error in llist - for key in keys(a:filters) - let rhs = a:filters[key] - if type(rhs) == 1 "string - let rhs = '"' . rhs . '"' - endif - - call filter(rv, "v:val['".key."'] ==? " . rhs) - endfor - endfor - return rv -endfunction - -if g:syntastic_enable_signs - "define the signs used to display syntax and style errors/warns - sign define SyntasticError text=>> texthl=error - sign define SyntasticWarning text=>> texthl=todo - sign define SyntasticStyleError text=S> texthl=error - sign define SyntasticStyleWarning text=S> texthl=todo -endif - -"start counting sign ids at 5000, start here to hopefully avoid conflicting -"with any other code that places signs (not sure if this precaution is -"actually needed) -let s:first_sign_id = 5000 -let s:next_sign_id = s:first_sign_id - -"place signs by all syntax errs in the buffer -function! s:SignErrors() - if s:BufHasErrorsOrWarningsToDisplay() - - let errors = s:FilterLocList({'bufnr': bufnr('')}) - for i in errors - let sign_severity = 'Error' - let sign_subtype = '' - if has_key(i,'subtype') - let sign_subtype = i['subtype'] - endif - if i['type'] ==? 'w' - let sign_severity = 'Warning' - endif - let sign_type = 'Syntastic' . sign_subtype . sign_severity - - if !s:WarningMasksError(i, errors) - exec "sign place ". s:next_sign_id ." line=". i['lnum'] ." name=". sign_type ." file=". expand("%:p") - call add(s:BufSignIds(), s:next_sign_id) - let s:next_sign_id += 1 - endif - endfor - endif -endfunction - -"return true if the given error item is a warning that, if signed, would -"potentially mask an error if displayed at the same time -function! s:WarningMasksError(error, llist) - if a:error['type'] !=? 'w' - return 0 - endif - - return len(s:FilterLocList({ 'type': "E", 'lnum': a:error['lnum'] }, a:llist)) > 0 -endfunction - -"remove the signs with the given ids from this buffer -function! s:RemoveSigns(ids) - for i in a:ids - exec "sign unplace " . i - call remove(s:BufSignIds(), index(s:BufSignIds(), i)) - endfor -endfunction - -"get all the ids of the SyntaxError signs in the buffer -function! s:BufSignIds() - if !exists("b:syntastic_sign_ids") - let b:syntastic_sign_ids = [] - endif - return b:syntastic_sign_ids -endfunction - -"update the error signs -function! s:RefreshSigns() - let old_signs = copy(s:BufSignIds()) - call s:SignErrors() - call s:RemoveSigns(old_signs) - let s:first_sign_id = s:next_sign_id -endfunction - -"display the cached errors for this buf in the location list -function! s:ShowLocList() - if !empty(s:LocList()) - let num = winnr() - exec "lopen " . g:syntastic_loc_list_height - if num != winnr() - wincmd p - endif - endif -endfunction - -"remove all error highlights from the window -function! s:ClearErrorHighlights() - for match in getmatches() - if stridx(match['group'], 'Syntastic') == 0 - call matchdelete(match['id']) - endif - endfor -endfunction - -"check if a syntax checker exists for the given filetype - and attempt to -"load one -function! s:Checkable(ft) - if !exists("g:loaded_" . a:ft . "_syntax_checker") - exec "runtime syntax_checkers/" . a:ft . ".vim" - endif - - return exists("*SyntaxCheckers_". a:ft ."_GetLocList") -endfunction - -"set up error ballons for the current set of errors -function! s:RefreshBalloons() - let b:syntastic_balloons = {} - if s:BufHasErrorsOrWarningsToDisplay() - for i in s:LocList() - let b:syntastic_balloons[i['lnum']] = i['text'] - endfor - set beval bexpr=SyntasticErrorBalloonExpr() - endif -endfunction - -"print as much of a:msg as possible without "Press Enter" prompt appearing -function! s:WideMsg(msg) - let old_ruler = &ruler - let old_showcmd = &showcmd - - let msg = strpart(a:msg, 0, winwidth(0)-1) - - "This is here because it is possible for some error messages to begin with - "\n which will cause a "press enter" prompt. I have noticed this in the - "javascript:jshint checker and have been unable to figure out why it - "happens - let msg = substitute(msg, "\n", "", "g") - - set noruler noshowcmd - redraw - - echo msg - - let &ruler=old_ruler - let &showcmd=old_showcmd -endfunction - -"echo out the first error we find for the current line in the cmd window -function! s:EchoCurrentError() - "If we have an error or warning at the current line, show it - let errors = s:FilterLocList({'lnum': line("."), "type": 'e'}) - let warnings = s:FilterLocList({'lnum': line("."), "type": 'w'}) - - let b:syntastic_echoing_error = len(errors) || len(warnings) - if len(errors) - return s:WideMsg(errors[0]['text']) - endif - if len(warnings) - return s:WideMsg(warnings[0]['text']) - endif - - "Otherwise, clear the status line - if b:syntastic_echoing_error - echo - let b:syntastic_echoing_error = 0 - endif -endfunction - -"load the chosen checker for the current filetype - useful for filetypes like -"javascript that have more than one syntax checker -function! s:LoadChecker(checker) - exec "runtime syntax_checkers/" . &ft . "/" . a:checker . ".vim" -endfunction - -"return a string representing the state of buffer according to -"g:syntastic_stl_format -" -"return '' if no errors are cached for the buffer -function! SyntasticStatuslineFlag() - if s:BufHasErrorsOrWarningsToDisplay() - let errors = s:Errors() - let warnings = s:Warnings() - - let output = g:syntastic_stl_format - - "hide stuff wrapped in %E(...) unless there are errors - let output = substitute(output, '\C%E{\([^}]*\)}', len(errors) ? '\1' : '' , 'g') - - "hide stuff wrapped in %W(...) unless there are warnings - let output = substitute(output, '\C%W{\([^}]*\)}', len(warnings) ? '\1' : '' , 'g') - - "hide stuff wrapped in %B(...) unless there are both errors and warnings - let output = substitute(output, '\C%B{\([^}]*\)}', (len(warnings) && len(errors)) ? '\1' : '' , 'g') - - "sub in the total errors/warnings/both - let output = substitute(output, '\C%w', len(warnings), 'g') - let output = substitute(output, '\C%e', len(errors), 'g') - let output = substitute(output, '\C%t', len(s:LocList()), 'g') - - "first error/warning line num - let output = substitute(output, '\C%F', s:LocList()[0]['lnum'], 'g') - - "first error line num - let output = substitute(output, '\C%fe', len(errors) ? errors[0]['lnum'] : '', 'g') - - "first warning line num - let output = substitute(output, '\C%fw', len(warnings) ? warnings[0]['lnum'] : '', 'g') - - return output - else - return '' - endif -endfunction - -"A wrapper for the :lmake command. Sets up the make environment according to -"the options given, runs make, resets the environment, returns the location -"list -" -"a:options can contain the following keys: -" 'makeprg' -" 'errorformat' -" -"The corresponding options are set for the duration of the function call. They -"are set with :let, so dont escape spaces. -" -"a:options may also contain: -" 'defaults' - a dict containing default values for the returned errors -" 'subtype' - all errors will be assigned the given subtype -function! SyntasticMake(options) - let old_loclist = getloclist(0) - let old_makeprg = &makeprg - let old_shellpipe = &shellpipe - let old_shell = &shell - let old_errorformat = &errorformat - - if !s:running_windows && (s:uname !~ "FreeBSD") - "this is a hack to stop the screen needing to be ':redraw'n when - "when :lmake is run. Otherwise the screen flickers annoyingly - let &shellpipe='&>' - let &shell = '/bin/bash' - endif - - if has_key(a:options, 'makeprg') - let &makeprg = a:options['makeprg'] - endif - - if has_key(a:options, 'errorformat') - let &errorformat = a:options['errorformat'] - endif - - silent lmake! - let errors = getloclist(0) - - call setloclist(0, old_loclist) - let &makeprg = old_makeprg - let &errorformat = old_errorformat - let &shellpipe=old_shellpipe - let &shell=old_shell - - if !s:running_windows && s:uname =~ "FreeBSD" - redraw! - endif - - if has_key(a:options, 'defaults') - call SyntasticAddToErrors(errors, a:options['defaults']) - endif - - " Add subtype info if present. - if has_key(a:options, 'subtype') - call SyntasticAddToErrors(errors, {'subtype': a:options['subtype']}) - endif - - return errors -endfunction - -"get the error balloon for the current mouse position -function! SyntasticErrorBalloonExpr() - if !exists('b:syntastic_balloons') - return '' - endif - return get(b:syntastic_balloons, v:beval_lnum, '') -endfunction - -"highlight the list of errors (a:errors) using matchadd() -" -"a:termfunc is provided to highlight errors that do not have a 'col' key (and -"hence cant be done automatically). This function must take one arg (an error -"item) and return a regex to match that item in the buffer. -" -"an optional boolean third argument can be provided to force a:termfunc to be -"used regardless of whether a 'col' key is present for the error -function! SyntasticHighlightErrors(errors, termfunc, ...) - if !g:syntastic_enable_highlighting - return - endif - - call s:ClearErrorHighlights() - - let force_callback = a:0 && a:1 - for item in a:errors - let group = item['type'] == 'E' ? 'SyntasticError' : 'SyntasticWarning' - if item['col'] && !force_callback - let lastcol = col([item['lnum'], '$']) - let lcol = min([lastcol, item['col']]) - call matchadd(group, '\%'.item['lnum'].'l\%'.lcol.'c') - else - let term = a:termfunc(item) - if len(term) > 0 - call matchadd(group, '\%' . item['lnum'] . 'l' . term) - endif - endif - endfor -endfunction - -"take a list of errors and add default values to them from a:options -function! SyntasticAddToErrors(errors, options) - for i in range(0, len(a:errors)-1) - for key in keys(a:options) - if !has_key(a:errors[i], key) || empty(a:errors[i][key]) - let a:errors[i][key] = a:options[key] - endif - endfor - endfor - return a:errors -endfunction - -"take a list of syntax checkers for the current filetype and load the right -"one based on the global settings and checker executable availabity -" -"a:checkers should be a list of syntax checker names. These names are assumed -"to be the names of the vim syntax checker files that should be sourced, as -"well as the names of the actual syntax checker executables. The checkers -"should be listed in order of default preference. -" -"if a option called 'g:syntastic_[filetype]_checker' exists then attempt to -"load the checker that it points to -function! SyntasticLoadChecker(checkers) - let opt_name = "g:syntastic_" . &ft . "_checker" - - if exists(opt_name) - let opt_val = {opt_name} - if index(a:checkers, opt_val) != -1 && executable(opt_val) - call s:LoadChecker(opt_val) - else - echoerr &ft . " syntax not supported or not installed." - endif - else - for checker in a:checkers - if executable(checker) - return s:LoadChecker(checker) - endif - endfor - endif -endfunction - -" vim: set et sts=4 sw=4: diff --git a/vim/plugin/tagbar.vim b/vim/plugin/tagbar.vim deleted file mode 100644 index a078a18..0000000 --- a/vim/plugin/tagbar.vim +++ /dev/null @@ -1,118 +0,0 @@ -" ============================================================================ -" File: tagbar.vim -" Description: List the current file's tags in a sidebar, ordered by class etc -" Author: Jan Larres <jan@majutsushi.net> -" Licence: Vim licence -" Website: http://majutsushi.github.com/tagbar/ -" Version: 2.3 -" Note: This plugin was heavily inspired by the 'Taglist' plugin by -" Yegappan Lakshmanan and uses a small amount of code from it. -" -" Original taglist copyright notice: -" Permission is hereby granted to use and distribute this code, -" with or without modifications, provided that this copyright -" notice is copied with it. Like anything else that's free, -" taglist.vim is provided *as is* and comes with no warranty of -" any kind, either expressed or implied. In no event will the -" copyright holder be liable for any damamges resulting from the -" use of this software. -" ============================================================================ - -scriptencoding utf-8 - -if &cp || exists('g:loaded_tagbar') - finish -endif - -" Basic init {{{1 - -if v:version < 700 - echohl WarningMsg - echomsg 'Tagbar: Vim version is too old, Tagbar requires at least 7.0' - echohl None - finish -endif - -if v:version == 700 && !has('patch167') - echohl WarningMsg - echomsg 'Tagbar: Vim versions lower than 7.0.167 have a bug' - \ 'that prevents this version of Tagbar from working.' - \ 'Please use the alternate version posted on the website.' - echohl None - finish -endif - -if !exists('g:tagbar_left') - let g:tagbar_left = 0 -endif - -if !exists('g:tagbar_width') - let g:tagbar_width = 40 -endif - -if !exists('g:tagbar_autoclose') - let g:tagbar_autoclose = 0 -endif - -if !exists('g:tagbar_autofocus') - let g:tagbar_autofocus = 0 -endif - -if !exists('g:tagbar_sort') - let g:tagbar_sort = 1 -endif - -if !exists('g:tagbar_compact') - let g:tagbar_compact = 0 -endif - -if !exists('g:tagbar_expand') - let g:tagbar_expand = 0 -endif - -if !exists('g:tagbar_singleclick') - let g:tagbar_singleclick = 0 -endif - -if !exists('g:tagbar_foldlevel') - let g:tagbar_foldlevel = 99 -endif - -if !exists('g:tagbar_iconchars') - if has('multi_byte') && has('unix') && &encoding == 'utf-8' && - \ (empty(&termencoding) || &termencoding == 'utf-8') - let g:tagbar_iconchars = ['▶', '▼'] - else - let g:tagbar_iconchars = ['+', '-'] - endif -endif - -if !exists('g:tagbar_autoshowtag') - let g:tagbar_autoshowtag = 0 -endif - -if !exists('g:tagbar_updateonsave_maxlines') - let g:tagbar_updateonsave_maxlines = 5000 -endif - -if !exists('g:tagbar_systemenc') - let g:tagbar_systemenc = &encoding -endif - -augroup TagbarSession - autocmd! - autocmd SessionLoadPost * nested call tagbar#RestoreSession() -augroup END - -" Commands {{{1 -command! -nargs=0 TagbarToggle call tagbar#ToggleWindow() -command! -nargs=? TagbarOpen call tagbar#OpenWindow(<f-args>) -command! -nargs=0 TagbarOpenAutoClose call tagbar#OpenWindow('fc') -command! -nargs=0 TagbarClose call tagbar#CloseWindow() -command! -nargs=1 TagbarSetFoldlevel call tagbar#SetFoldLevel(<args>) -command! -nargs=0 TagbarShowTag call tagbar#OpenParents() -command! -nargs=? TagbarDebug call tagbar#StartDebug(<f-args>) -command! -nargs=0 TagbarDebugEnd call tagbar#StopDebug() - -" Modeline {{{1 -" vim: ts=8 sw=4 sts=4 et foldenable foldmethod=marker foldcolumn=1 diff --git a/vim/plugin/taglist.vim b/vim/plugin/taglist.vim deleted file mode 100644 index 59901f6..0000000 --- a/vim/plugin/taglist.vim +++ /dev/null @@ -1,4546 +0,0 @@ -" File: taglist.vim -" Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com) -" Version: 4.5 -" Last Modified: September 21, 2007 -" Copyright: Copyright (C) 2002-2007 Yegappan Lakshmanan -" Permission is hereby granted to use and distribute this code, -" with or without modifications, provided that this copyright -" notice is copied with it. Like anything else that's free, -" taglist.vim is provided *as is* and comes with no warranty of any -" kind, either expressed or implied. In no event will the copyright -" holder be liable for any damamges resulting from the use of this -" software. -" -" The "Tag List" plugin is a source code browser plugin for Vim and provides -" an overview of the structure of the programming language files and allows -" you to efficiently browse through source code files for different -" programming languages. You can visit the taglist plugin home page for more -" information: -" -" http://vim-taglist.sourceforge.net -" -" You can subscribe to the taglist mailing list to post your questions -" or suggestions for improvement or to report bugs. Visit the following -" page for subscribing to the mailing list: -" -" http://groups.yahoo.com/group/taglist/ -" -" For more information about using this plugin, after installing the -" taglist plugin, use the ":help taglist" command. -" -" Installation -" ------------ -" 1. Download the taglist.zip file and unzip the files to the $HOME/.vim -" or the $HOME/vimfiles or the $VIM/vimfiles directory. This should -" unzip the following two files (the directory structure should be -" preserved): -" -" plugin/taglist.vim - main taglist plugin file -" doc/taglist.txt - documentation (help) file -" -" Refer to the 'add-plugin', 'add-global-plugin' and 'runtimepath' -" Vim help pages for more details about installing Vim plugins. -" 2. Change to the $HOME/.vim/doc or $HOME/vimfiles/doc or -" $VIM/vimfiles/doc directory, start Vim and run the ":helptags ." -" command to process the taglist help file. -" 3. If the exuberant ctags utility is not present in your PATH, then set the -" Tlist_Ctags_Cmd variable to point to the location of the exuberant ctags -" utility (not to the directory) in the .vimrc file. -" 4. If you are running a terminal/console version of Vim and the -" terminal doesn't support changing the window width then set the -" 'Tlist_Inc_Winwidth' variable to 0 in the .vimrc file. -" 5. Restart Vim. -" 6. You can now use the ":TlistToggle" command to open/close the taglist -" window. You can use the ":help taglist" command to get more -" information about using the taglist plugin. -" -" ****************** Do not modify after this line ************************ - -" Line continuation used here -let s:cpo_save = &cpo -set cpo&vim - -if !exists('loaded_taglist') - " First time loading the taglist plugin - " - " To speed up the loading of Vim, the taglist plugin uses autoload - " mechanism to load the taglist functions. - " Only define the configuration variables, user commands and some - " auto-commands and finish sourcing the file - - " The taglist plugin requires the built-in Vim system() function. If this - " function is not available, then don't load the plugin. - if !exists('*system') - echomsg 'Taglist: Vim system() built-in function is not available. ' . - \ 'Plugin is not loaded.' - let loaded_taglist = 'no' - let &cpo = s:cpo_save - finish - endif - - " Location of the exuberant ctags tool - if !exists('Tlist_Ctags_Cmd') - if executable('exuberant-ctags') - " On Debian Linux, exuberant ctags is installed - " as exuberant-ctags - let Tlist_Ctags_Cmd = 'exuberant-ctags' - elseif executable('exctags') - " On Free-BSD, exuberant ctags is installed as exctags - let Tlist_Ctags_Cmd = 'exctags' - elseif executable('ctags') - let Tlist_Ctags_Cmd = 'ctags' - elseif executable('ctags.exe') - let Tlist_Ctags_Cmd = 'ctags.exe' - elseif executable('tags') - let Tlist_Ctags_Cmd = 'tags' - else - echomsg 'Taglist: Exuberant ctags (http://ctags.sf.net) ' . - \ 'not found in PATH. Plugin is not loaded.' - " Skip loading the plugin - let loaded_taglist = 'no' - let &cpo = s:cpo_save - finish - endif - endif - - - " Automatically open the taglist window on Vim startup - if !exists('Tlist_Auto_Open') - let Tlist_Auto_Open = 0 - endif - - " When the taglist window is toggle opened, move the cursor to the - " taglist window - if !exists('Tlist_GainFocus_On_ToggleOpen') - let Tlist_GainFocus_On_ToggleOpen = 0 - endif - - " Process files even when the taglist window is not open - if !exists('Tlist_Process_File_Always') - let Tlist_Process_File_Always = 0 - endif - - if !exists('Tlist_Show_Menu') - let Tlist_Show_Menu = 0 - endif - - " Tag listing sort type - 'name' or 'order' - if !exists('Tlist_Sort_Type') - let Tlist_Sort_Type = 'order' - endif - - " Tag listing window split (horizontal/vertical) control - if !exists('Tlist_Use_Horiz_Window') - let Tlist_Use_Horiz_Window = 0 - endif - - " Open the vertically split taglist window on the left or on the right - " side. This setting is relevant only if Tlist_Use_Horiz_Window is set to - " zero (i.e. only for vertically split windows) - if !exists('Tlist_Use_Right_Window') - let Tlist_Use_Right_Window = 0 - endif - - " Increase Vim window width to display vertically split taglist window. - " For MS-Windows version of Vim running in a MS-DOS window, this must be - " set to 0 otherwise the system may hang due to a Vim limitation. - if !exists('Tlist_Inc_Winwidth') - if (has('win16') || has('win95')) && !has('gui_running') - let Tlist_Inc_Winwidth = 0 - else - let Tlist_Inc_Winwidth = 1 - endif - endif - - " Vertically split taglist window width setting - if !exists('Tlist_WinWidth') - let Tlist_WinWidth = 30 - endif - - " Horizontally split taglist window height setting - if !exists('Tlist_WinHeight') - let Tlist_WinHeight = 10 - endif - - " Display tag prototypes or tag names in the taglist window - if !exists('Tlist_Display_Prototype') - let Tlist_Display_Prototype = 0 - endif - - " Display tag scopes in the taglist window - if !exists('Tlist_Display_Tag_Scope') - let Tlist_Display_Tag_Scope = 1 - endif - - " Use single left mouse click to jump to a tag. By default this is disabled. - " Only double click using the mouse will be processed. - if !exists('Tlist_Use_SingleClick') - let Tlist_Use_SingleClick = 0 - endif - - " Control whether additional help is displayed as part of the taglist or - " not. Also, controls whether empty lines are used to separate the tag - " tree. - if !exists('Tlist_Compact_Format') - let Tlist_Compact_Format = 0 - endif - - " Exit Vim if only the taglist window is currently open. By default, this is - " set to zero. - if !exists('Tlist_Exit_OnlyWindow') - let Tlist_Exit_OnlyWindow = 0 - endif - - " Automatically close the folds for the non-active files in the taglist - " window - if !exists('Tlist_File_Fold_Auto_Close') - let Tlist_File_Fold_Auto_Close = 0 - endif - - " Close the taglist window when a tag is selected - if !exists('Tlist_Close_On_Select') - let Tlist_Close_On_Select = 0 - endif - - " Automatically update the taglist window to display tags for newly - " edited files - if !exists('Tlist_Auto_Update') - let Tlist_Auto_Update = 1 - endif - - " Automatically highlight the current tag - if !exists('Tlist_Auto_Highlight_Tag') - let Tlist_Auto_Highlight_Tag = 1 - endif - - " Automatically highlight the current tag on entering a buffer - if !exists('Tlist_Highlight_Tag_On_BufEnter') - let Tlist_Highlight_Tag_On_BufEnter = 1 - endif - - " Enable fold column to display the folding for the tag tree - if !exists('Tlist_Enable_Fold_Column') - let Tlist_Enable_Fold_Column = 1 - endif - - " Display the tags for only one file in the taglist window - if !exists('Tlist_Show_One_File') - let Tlist_Show_One_File = 0 - endif - - if !exists('Tlist_Max_Submenu_Items') - let Tlist_Max_Submenu_Items = 20 - endif - - if !exists('Tlist_Max_Tag_Length') - let Tlist_Max_Tag_Length = 10 - endif - - " Do not change the name of the taglist title variable. The winmanager - " plugin relies on this name to determine the title for the taglist - " plugin. - let TagList_title = "__Tag_List__" - - " Taglist debug messages - let s:tlist_msg = '' - - " Define the taglist autocommand to automatically open the taglist window - " on Vim startup - if g:Tlist_Auto_Open - autocmd VimEnter * nested call s:Tlist_Window_Check_Auto_Open() - endif - - " Refresh the taglist - if g:Tlist_Process_File_Always - autocmd BufEnter * call s:Tlist_Refresh() - endif - - if g:Tlist_Show_Menu - autocmd GUIEnter * call s:Tlist_Menu_Init() - endif - - " When the taglist buffer is created when loading a Vim session file, - " the taglist buffer needs to be initialized. The BufFilePost event - " is used to handle this case. - autocmd BufFilePost __Tag_List__ call s:Tlist_Vim_Session_Load() - - " Define the user commands to manage the taglist window - command! -nargs=0 -bar TlistToggle call s:Tlist_Window_Toggle() - command! -nargs=0 -bar TlistOpen call s:Tlist_Window_Open() - " For backwards compatiblity define the Tlist command - command! -nargs=0 -bar Tlist TlistToggle - command! -nargs=+ -complete=file TlistAddFiles - \ call s:Tlist_Add_Files(<f-args>) - command! -nargs=+ -complete=dir TlistAddFilesRecursive - \ call s:Tlist_Add_Files_Recursive(<f-args>) - command! -nargs=0 -bar TlistClose call s:Tlist_Window_Close() - command! -nargs=0 -bar TlistUpdate call s:Tlist_Update_Current_File() - command! -nargs=0 -bar TlistHighlightTag call s:Tlist_Window_Highlight_Tag( - \ fnamemodify(bufname('%'), ':p'), line('.'), 2, 1) - " For backwards compatiblity define the TlistSync command - command! -nargs=0 -bar TlistSync TlistHighlightTag - command! -nargs=* -complete=buffer TlistShowPrototype - \ echo Tlist_Get_Tag_Prototype_By_Line(<f-args>) - command! -nargs=* -complete=buffer TlistShowTag - \ echo Tlist_Get_Tagname_By_Line(<f-args>) - command! -nargs=* -complete=file TlistSessionLoad - \ call s:Tlist_Session_Load(<q-args>) - command! -nargs=* -complete=file TlistSessionSave - \ call s:Tlist_Session_Save(<q-args>) - command! -bar TlistLock let Tlist_Auto_Update=0 - command! -bar TlistUnlock let Tlist_Auto_Update=1 - - " Commands for enabling/disabling debug and to display debug messages - command! -nargs=? -complete=file -bar TlistDebug - \ call s:Tlist_Debug_Enable(<q-args>) - command! -nargs=0 -bar TlistUndebug call s:Tlist_Debug_Disable() - command! -nargs=0 -bar TlistMessages call s:Tlist_Debug_Show() - - " Define autocommands to autoload the taglist plugin when needed. - - " Trick to get the current script ID - map <SID>xx <SID>xx - let s:tlist_sid = substitute(maparg('<SID>xx'), '<SNR>\(\d\+_\)xx$', - \ '\1', '') - unmap <SID>xx - - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_Window_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined *' . s:tlist_sid . 'Tlist_Menu_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined Tlist_* source ' . - \ escape(expand('<sfile>'), ' ') - exe 'autocmd FuncUndefined TagList_* source ' . - \ escape(expand('<sfile>'), ' ') - - let loaded_taglist = 'fast_load_done' - - if g:Tlist_Show_Menu && has('gui_running') - call s:Tlist_Menu_Init() - endif - - " restore 'cpo' - let &cpo = s:cpo_save - finish -endif - -if !exists('s:tlist_sid') - " Two or more versions of taglist plugin are installed. Don't - " load this version of the plugin. - finish -endif - -unlet! s:tlist_sid - -if loaded_taglist != 'fast_load_done' - " restore 'cpo' - let &cpo = s:cpo_save - finish -endif - -" Taglist plugin functionality is available -let loaded_taglist = 'available' - -"------------------- end of user configurable options -------------------- - -" Default language specific settings for supported file types and tag types -" -" Variable name format: -" -" s:tlist_def_{vim_ftype}_settings -" -" vim_ftype - Filetype detected by Vim -" -" Value format: -" -" <ctags_ftype>;<flag>:<name>;<flag>:<name>;... -" -" ctags_ftype - File type supported by exuberant ctags -" flag - Flag supported by exuberant ctags to generate a tag type -" name - Name of the tag type used in the taglist window to display the -" tags of this type -" - -" assembly language -let s:tlist_def_asm_settings = 'asm;d:define;l:label;m:macro;t:type' - -" aspperl language -let s:tlist_def_aspperl_settings = 'asp;f:function;s:sub;v:variable' - -" aspvbs language -let s:tlist_def_aspvbs_settings = 'asp;f:function;s:sub;v:variable' - -" awk language -let s:tlist_def_awk_settings = 'awk;f:function' - -" beta language -let s:tlist_def_beta_settings = 'beta;f:fragment;s:slot;v:pattern' - -" c language -let s:tlist_def_c_settings = 'c;d:macro;g:enum;s:struct;u:union;t:typedef;' . - \ 'v:variable;f:function' - -" c++ language -let s:tlist_def_cpp_settings = 'c++;n:namespace;v:variable;d:macro;t:typedef;' . - \ 'c:class;g:enum;s:struct;u:union;f:function' - -" c# language -let s:tlist_def_cs_settings = 'c#;d:macro;t:typedef;n:namespace;c:class;' . - \ 'E:event;g:enum;s:struct;i:interface;' . - \ 'p:properties;m:method' - -" cobol language -let s:tlist_def_cobol_settings = 'cobol;d:data;f:file;g:group;p:paragraph;' . - \ 'P:program;s:section' - -" eiffel language -let s:tlist_def_eiffel_settings = 'eiffel;c:class;f:feature' - -" erlang language -let s:tlist_def_erlang_settings = 'erlang;d:macro;r:record;m:module;f:function' - -" expect (same as tcl) language -let s:tlist_def_expect_settings = 'tcl;c:class;f:method;p:procedure' - -" fortran language -let s:tlist_def_fortran_settings = 'fortran;p:program;b:block data;' . - \ 'c:common;e:entry;i:interface;k:type;l:label;m:module;' . - \ 'n:namelist;t:derived;v:variable;f:function;s:subroutine' - -" HTML language -let s:tlist_def_html_settings = 'html;a:anchor;f:javascript function' - -" java language -let s:tlist_def_java_settings = 'java;p:package;c:class;i:interface;' . - \ 'f:field;m:method' - -" javascript language -let s:tlist_def_javascript_settings = 'javascript;f:function' - -" lisp language -let s:tlist_def_lisp_settings = 'lisp;f:function' - -" lua language -let s:tlist_def_lua_settings = 'lua;f:function' - -" makefiles -let s:tlist_def_make_settings = 'make;m:macro' - -" pascal language -let s:tlist_def_pascal_settings = 'pascal;f:function;p:procedure' - -" perl language -let s:tlist_def_perl_settings = 'perl;c:constant;l:label;p:package;s:subroutine' - -" php language -let s:tlist_def_php_settings = 'php;c:class;d:constant;v:variable;f:function' - -" python language -let s:tlist_def_python_settings = 'python;c:class;m:member;f:function' - -" rexx language -let s:tlist_def_rexx_settings = 'rexx;s:subroutine' - -" ruby language -let s:tlist_def_ruby_settings = 'ruby;c:class;f:method;F:function;' . - \ 'm:singleton method' - -" scheme language -let s:tlist_def_scheme_settings = 'scheme;s:set;f:function' - -" shell language -let s:tlist_def_sh_settings = 'sh;f:function' - -" C shell language -let s:tlist_def_csh_settings = 'sh;f:function' - -" Z shell language -let s:tlist_def_zsh_settings = 'sh;f:function' - -" slang language -let s:tlist_def_slang_settings = 'slang;n:namespace;f:function' - -" sml language -let s:tlist_def_sml_settings = 'sml;e:exception;c:functor;s:signature;' . - \ 'r:structure;t:type;v:value;f:function' - -" sql language -let s:tlist_def_sql_settings = 'sql;c:cursor;F:field;P:package;r:record;' . - \ 's:subtype;t:table;T:trigger;v:variable;f:function;p:procedure' - -" tcl language -let s:tlist_def_tcl_settings = 'tcl;c:class;f:method;m:method;p:procedure' - -" vera language -let s:tlist_def_vera_settings = 'vera;c:class;d:macro;e:enumerator;' . - \ 'f:function;g:enum;m:member;p:program;' . - \ 'P:prototype;t:task;T:typedef;v:variable;' . - \ 'x:externvar' - -"verilog language -let s:tlist_def_verilog_settings = 'verilog;m:module;c:constant;P:parameter;' . - \ 'e:event;r:register;t:task;w:write;p:port;v:variable;f:function' - -" vim language -let s:tlist_def_vim_settings = 'vim;a:autocmds;v:variable;f:function' - -" yacc language -let s:tlist_def_yacc_settings = 'yacc;l:label' - -"------------------- end of language specific options -------------------- - -" Vim window size is changed by the taglist plugin or not -let s:tlist_winsize_chgd = -1 -" Taglist window is maximized or not -let s:tlist_win_maximized = 0 -" Name of files in the taglist -let s:tlist_file_names='' -" Number of files in the taglist -let s:tlist_file_count = 0 -" Number of filetypes supported by taglist -let s:tlist_ftype_count = 0 -" Is taglist part of other plugins like winmanager or cream? -let s:tlist_app_name = "none" -" Are we displaying brief help text -let s:tlist_brief_help = 1 -" List of files removed on user request -let s:tlist_removed_flist = "" -" Index of current file displayed in the taglist window -let s:tlist_cur_file_idx = -1 -" Taglist menu is empty or not -let s:tlist_menu_empty = 1 - -" An autocommand is used to refresh the taglist window when entering any -" buffer. We don't want to refresh the taglist window if we are entering the -" file window from one of the taglist functions. The 'Tlist_Skip_Refresh' -" variable is used to skip the refresh of the taglist window and is set -" and cleared appropriately. -let s:Tlist_Skip_Refresh = 0 - -" Tlist_Window_Display_Help() -function! s:Tlist_Window_Display_Help() - if s:tlist_app_name == "winmanager" - " To handle a bug in the winmanager plugin, add a space at the - " last line - call setline('$', ' ') - endif - - if s:tlist_brief_help - " Add the brief help - call append(0, '" Press <F1> to display help text') - else - " Add the extensive help - call append(0, '" <enter> : Jump to tag definition') - call append(1, '" o : Jump to tag definition in new window') - call append(2, '" p : Preview the tag definition') - call append(3, '" <space> : Display tag prototype') - call append(4, '" u : Update tag list') - call append(5, '" s : Select sort field') - call append(6, '" d : Remove file from taglist') - call append(7, '" x : Zoom-out/Zoom-in taglist window') - call append(8, '" + : Open a fold') - call append(9, '" - : Close a fold') - call append(10, '" * : Open all folds') - call append(11, '" = : Close all folds') - call append(12, '" [[ : Move to the start of previous file') - call append(13, '" ]] : Move to the start of next file') - call append(14, '" q : Close the taglist window') - call append(15, '" <F1> : Remove help text') - endif -endfunction - -" Tlist_Window_Toggle_Help_Text() -" Toggle taglist plugin help text between the full version and the brief -" version -function! s:Tlist_Window_Toggle_Help_Text() - if g:Tlist_Compact_Format - " In compact display mode, do not display help - return - endif - - " Include the empty line displayed after the help text - let brief_help_size = 1 - let full_help_size = 16 - - setlocal modifiable - - " Set report option to a huge value to prevent informational messages - " while deleting the lines - let old_report = &report - set report=99999 - - " Remove the currently highlighted tag. Otherwise, the help text - " might be highlighted by mistake - match none - - " Toggle between brief and full help text - if s:tlist_brief_help - let s:tlist_brief_help = 0 - - " Remove the previous help - exe '1,' . brief_help_size . ' delete _' - - " Adjust the start/end line numbers for the files - call s:Tlist_Window_Update_Line_Offsets(0, 1, full_help_size - brief_help_size) - else - let s:tlist_brief_help = 1 - - " Remove the previous help - exe '1,' . full_help_size . ' delete _' - - " Adjust the start/end line numbers for the files - call s:Tlist_Window_Update_Line_Offsets(0, 0, full_help_size - brief_help_size) - endif - - call s:Tlist_Window_Display_Help() - - " Restore the report option - let &report = old_report - - setlocal nomodifiable -endfunction - -" Taglist debug support -let s:tlist_debug = 0 - -" File for storing the debug messages -let s:tlist_debug_file = '' - -" Tlist_Debug_Enable -" Enable logging of taglist debug messages. -function! s:Tlist_Debug_Enable(...) - let s:tlist_debug = 1 - - " Check whether a valid file name is supplied. - if a:1 != '' - let s:tlist_debug_file = fnamemodify(a:1, ':p') - - " Empty the log file - exe 'redir! > ' . s:tlist_debug_file - redir END - - " Check whether the log file is present/created - if !filewritable(s:tlist_debug_file) - call s:Tlist_Warning_Msg('Taglist: Unable to create log file ' - \ . s:tlist_debug_file) - let s:tlist_debug_file = '' - endif - endif -endfunction - -" Tlist_Debug_Disable -" Disable logging of taglist debug messages. -function! s:Tlist_Debug_Disable(...) - let s:tlist_debug = 0 - let s:tlist_debug_file = '' -endfunction - -" Tlist_Debug_Show -" Display the taglist debug messages in a new window -function! s:Tlist_Debug_Show() - if s:tlist_msg == '' - call s:Tlist_Warning_Msg('Taglist: No debug messages') - return - endif - - " Open a new window to display the taglist debug messages - new taglist_debug.txt - " Delete all the lines (if the buffer already exists) - silent! %delete _ - " Add the messages - silent! put =s:tlist_msg - " Move the cursor to the first line - normal! gg -endfunction - -" Tlist_Log_Msg -" Log the supplied debug message along with the time -function! s:Tlist_Log_Msg(msg) - if s:tlist_debug - if s:tlist_debug_file != '' - exe 'redir >> ' . s:tlist_debug_file - silent echon strftime('%H:%M:%S') . ': ' . a:msg . "\n" - redir END - else - " Log the message into a variable - " Retain only the last 3000 characters - let len = strlen(s:tlist_msg) - if len > 3000 - let s:tlist_msg = strpart(s:tlist_msg, len - 3000) - endif - let s:tlist_msg = s:tlist_msg . strftime('%H:%M:%S') . ': ' . - \ a:msg . "\n" - endif - endif -endfunction - -" Tlist_Warning_Msg() -" Display a message using WarningMsg highlight group -function! s:Tlist_Warning_Msg(msg) - echohl WarningMsg - echomsg a:msg - echohl None -endfunction - -" Last returned file index for file name lookup. -" Used to speed up file lookup -let s:tlist_file_name_idx_cache = -1 - -" Tlist_Get_File_Index() -" Return the index of the specified filename -function! s:Tlist_Get_File_Index(fname) - if s:tlist_file_count == 0 || a:fname == '' - return -1 - endif - - " If the new filename is same as the last accessed filename, then - " return that index - if s:tlist_file_name_idx_cache != -1 && - \ s:tlist_file_name_idx_cache < s:tlist_file_count - if s:tlist_{s:tlist_file_name_idx_cache}_filename == a:fname - " Same as the last accessed file - return s:tlist_file_name_idx_cache - endif - endif - - " First, check whether the filename is present - let s_fname = a:fname . "\n" - let i = stridx(s:tlist_file_names, s_fname) - if i == -1 - let s:tlist_file_name_idx_cache = -1 - return -1 - endif - - " Second, compute the file name index - let nl_txt = substitute(strpart(s:tlist_file_names, 0, i), "[^\n]", '', 'g') - let s:tlist_file_name_idx_cache = strlen(nl_txt) - return s:tlist_file_name_idx_cache -endfunction - -" Last returned file index for line number lookup. -" Used to speed up file lookup -let s:tlist_file_lnum_idx_cache = -1 - -" Tlist_Window_Get_File_Index_By_Linenum() -" Return the index of the filename present in the specified line number -" Line number refers to the line number in the taglist window -function! s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - call s:Tlist_Log_Msg('Tlist_Window_Get_File_Index_By_Linenum (' . a:lnum . ')') - - " First try to see whether the new line number is within the range - " of the last returned file - if s:tlist_file_lnum_idx_cache != -1 && - \ s:tlist_file_lnum_idx_cache < s:tlist_file_count - if a:lnum >= s:tlist_{s:tlist_file_lnum_idx_cache}_start && - \ a:lnum <= s:tlist_{s:tlist_file_lnum_idx_cache}_end - return s:tlist_file_lnum_idx_cache - endif - endif - - let fidx = -1 - - if g:Tlist_Show_One_File - " Displaying only one file in the taglist window. Check whether - " the line is within the tags displayed for that file - if s:tlist_cur_file_idx != -1 - if a:lnum >= s:tlist_{s:tlist_cur_file_idx}_start - \ && a:lnum <= s:tlist_{s:tlist_cur_file_idx}_end - let fidx = s:tlist_cur_file_idx - endif - - endif - else - " Do a binary search in the taglist - let left = 0 - let right = s:tlist_file_count - 1 - - while left < right - let mid = (left + right) / 2 - - if a:lnum >= s:tlist_{mid}_start && a:lnum <= s:tlist_{mid}_end - let s:tlist_file_lnum_idx_cache = mid - return mid - endif - - if a:lnum < s:tlist_{mid}_start - let right = mid - 1 - else - let left = mid + 1 - endif - endwhile - - if left >= 0 && left < s:tlist_file_count - \ && a:lnum >= s:tlist_{left}_start - \ && a:lnum <= s:tlist_{left}_end - let fidx = left - endif - endif - - let s:tlist_file_lnum_idx_cache = fidx - - return fidx -endfunction - -" Tlist_Exe_Cmd_No_Acmds -" Execute the specified Ex command after disabling autocommands -function! s:Tlist_Exe_Cmd_No_Acmds(cmd) - let old_eventignore = &eventignore - set eventignore=all - exe a:cmd - let &eventignore = old_eventignore -endfunction - -" Tlist_Skip_File() -" Check whether tag listing is supported for the specified file -function! s:Tlist_Skip_File(filename, ftype) - " Skip buffers with no names and buffers with filetype not set - if a:filename == '' || a:ftype == '' - return 1 - endif - - " Skip files which are not supported by exuberant ctags - " First check whether default settings for this filetype are available. - " If it is not available, then check whether user specified settings are - " available. If both are not available, then don't list the tags for this - " filetype - let var = 's:tlist_def_' . a:ftype . '_settings' - if !exists(var) - let var = 'g:tlist_' . a:ftype . '_settings' - if !exists(var) - return 1 - endif - endif - - " Skip files which are not readable or files which are not yet stored - " to the disk - if !filereadable(a:filename) - return 1 - endif - - return 0 -endfunction - -" Tlist_User_Removed_File -" Returns 1 if a file is removed by a user from the taglist -function! s:Tlist_User_Removed_File(filename) - return stridx(s:tlist_removed_flist, a:filename . "\n") != -1 -endfunction - -" Tlist_Update_Remove_List -" Update the list of user removed files from the taglist -" add == 1, add the file to the removed list -" add == 0, delete the file from the removed list -function! s:Tlist_Update_Remove_List(filename, add) - if a:add - let s:tlist_removed_flist = s:tlist_removed_flist . a:filename . "\n" - else - let idx = stridx(s:tlist_removed_flist, a:filename . "\n") - let text_before = strpart(s:tlist_removed_flist, 0, idx) - let rem_text = strpart(s:tlist_removed_flist, idx) - let next_idx = stridx(rem_text, "\n") - let text_after = strpart(rem_text, next_idx + 1) - - let s:tlist_removed_flist = text_before . text_after - endif -endfunction - -" Tlist_FileType_Init -" Initialize the ctags arguments and tag variable for the specified -" file type -function! s:Tlist_FileType_Init(ftype) - call s:Tlist_Log_Msg('Tlist_FileType_Init (' . a:ftype . ')') - " If the user didn't specify any settings, then use the default - " ctags args. Otherwise, use the settings specified by the user - let var = 'g:tlist_' . a:ftype . '_settings' - if exists(var) - " User specified ctags arguments - let settings = {var} . ';' - else - " Default ctags arguments - let var = 's:tlist_def_' . a:ftype . '_settings' - if !exists(var) - " No default settings for this file type. This filetype is - " not supported - return 0 - endif - let settings = s:tlist_def_{a:ftype}_settings . ';' - endif - - let msg = 'Taglist: Invalid ctags option setting - ' . settings - - " Format of the option that specifies the filetype and ctags arugments: - " - " <language_name>;flag1:name1;flag2:name2;flag3:name3 - " - - " Extract the file type to pass to ctags. This may be different from the - " file type detected by Vim - let pos = stridx(settings, ';') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let ctags_ftype = strpart(settings, 0, pos) - if ctags_ftype == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - " Make sure a valid filetype is supplied. If the user didn't specify a - " valid filetype, then the ctags option settings may be treated as the - " filetype - if ctags_ftype =~ ':' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - - " Remove the file type from settings - let settings = strpart(settings, pos + 1) - if settings == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - - " Process all the specified ctags flags. The format is - " flag1:name1;flag2:name2;flag3:name3 - let ctags_flags = '' - let cnt = 0 - while settings != '' - " Extract the flag - let pos = stridx(settings, ':') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let flag = strpart(settings, 0, pos) - if flag == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - " Remove the flag from settings - let settings = strpart(settings, pos + 1) - - " Extract the tag type name - let pos = stridx(settings, ';') - if pos == -1 - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let name = strpart(settings, 0, pos) - if name == '' - call s:Tlist_Warning_Msg(msg) - return 0 - endif - let settings = strpart(settings, pos + 1) - - let cnt = cnt + 1 - - let s:tlist_{a:ftype}_{cnt}_name = flag - let s:tlist_{a:ftype}_{cnt}_fullname = name - let ctags_flags = ctags_flags . flag - endwhile - - let s:tlist_{a:ftype}_ctags_args = '--language-force=' . ctags_ftype . - \ ' --' . ctags_ftype . '-types=' . ctags_flags - let s:tlist_{a:ftype}_count = cnt - let s:tlist_{a:ftype}_ctags_flags = ctags_flags - - " Save the filetype name - let s:tlist_ftype_{s:tlist_ftype_count}_name = a:ftype - let s:tlist_ftype_count = s:tlist_ftype_count + 1 - - return 1 -endfunction - -" Tlist_Detect_Filetype -" Determine the filetype for the specified file using the filetypedetect -" autocmd. -function! s:Tlist_Detect_Filetype(fname) - " Ignore the filetype autocommands - let old_eventignore = &eventignore - set eventignore=FileType - - " Save the 'filetype', as this will be changed temporarily - let old_filetype = &filetype - - " Run the filetypedetect group of autocommands to determine - " the filetype - exe 'doautocmd filetypedetect BufRead ' . a:fname - - " Save the detected filetype - let ftype = &filetype - - " Restore the previous state - let &filetype = old_filetype - let &eventignore = old_eventignore - - return ftype -endfunction - -" Tlist_Get_Buffer_Filetype -" Get the filetype for the specified buffer -function! s:Tlist_Get_Buffer_Filetype(bnum) - let buf_ft = getbufvar(a:bnum, '&filetype') - - if bufloaded(a:bnum) - " For loaded buffers, the 'filetype' is already determined - return buf_ft - endif - - " For unloaded buffers, if the 'filetype' option is set, return it - if buf_ft != '' - return buf_ft - endif - - " Skip non-existent buffers - if !bufexists(a:bnum) - return '' - endif - - " For buffers whose filetype is not yet determined, try to determine - " the filetype - let bname = bufname(a:bnum) - - return s:Tlist_Detect_Filetype(bname) -endfunction - -" Tlist_Discard_TagInfo -" Discard the stored tag information for a file -function! s:Tlist_Discard_TagInfo(fidx) - call s:Tlist_Log_Msg('Tlist_Discard_TagInfo (' . - \ s:tlist_{a:fidx}_filename . ')') - let ftype = s:tlist_{a:fidx}_filetype - - " Discard information about the tags defined in the file - let i = 1 - while i <= s:tlist_{a:fidx}_tag_count - let fidx_i = 's:tlist_' . a:fidx . '_' . i - unlet! {fidx_i}_tag - unlet! {fidx_i}_tag_name - unlet! {fidx_i}_tag_type - unlet! {fidx_i}_ttype_idx - unlet! {fidx_i}_tag_proto - unlet! {fidx_i}_tag_searchpat - unlet! {fidx_i}_tag_linenum - let i = i + 1 - endwhile - - let s:tlist_{a:fidx}_tag_count = 0 - - " Discard information about tag type groups - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - if s:tlist_{a:fidx}_{ttype} != '' - let fidx_ttype = 's:tlist_' . a:fidx . '_' . ttype - let {fidx_ttype} = '' - let {fidx_ttype}_offset = 0 - let cnt = {fidx_ttype}_count - let {fidx_ttype}_count = 0 - let j = 1 - while j <= cnt - unlet! {fidx_ttype}_{j} - let j = j + 1 - endwhile - endif - let i = i + 1 - endwhile - - " Discard the stored menu command also - let s:tlist_{a:fidx}_menu_cmd = '' -endfunction - -" Tlist_Window_Update_Line_Offsets -" Update the line offsets for tags for files starting from start_idx -" and displayed in the taglist window by the specified offset -function! s:Tlist_Window_Update_Line_Offsets(start_idx, increment, offset) - let i = a:start_idx - - while i < s:tlist_file_count - if s:tlist_{i}_visible - " Update the start/end line number only if the file is visible - if a:increment - let s:tlist_{i}_start = s:tlist_{i}_start + a:offset - let s:tlist_{i}_end = s:tlist_{i}_end + a:offset - else - let s:tlist_{i}_start = s:tlist_{i}_start - a:offset - let s:tlist_{i}_end = s:tlist_{i}_end - a:offset - endif - endif - let i = i + 1 - endwhile -endfunction - -" Tlist_Discard_FileInfo -" Discard the stored information for a file -function! s:Tlist_Discard_FileInfo(fidx) - call s:Tlist_Log_Msg('Tlist_Discard_FileInfo (' . - \ s:tlist_{a:fidx}_filename . ')') - call s:Tlist_Discard_TagInfo(a:fidx) - - let ftype = s:tlist_{a:fidx}_filetype - - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - unlet! s:tlist_{a:fidx}_{ttype} - unlet! s:tlist_{a:fidx}_{ttype}_offset - unlet! s:tlist_{a:fidx}_{ttype}_count - let i = i + 1 - endwhile - - unlet! s:tlist_{a:fidx}_filename - unlet! s:tlist_{a:fidx}_sort_type - unlet! s:tlist_{a:fidx}_filetype - unlet! s:tlist_{a:fidx}_mtime - unlet! s:tlist_{a:fidx}_start - unlet! s:tlist_{a:fidx}_end - unlet! s:tlist_{a:fidx}_valid - unlet! s:tlist_{a:fidx}_visible - unlet! s:tlist_{a:fidx}_tag_count - unlet! s:tlist_{a:fidx}_menu_cmd -endfunction - -" Tlist_Window_Remove_File_From_Display -" Remove the specified file from display -function! s:Tlist_Window_Remove_File_From_Display(fidx) - call s:Tlist_Log_Msg('Tlist_Window_Remove_File_From_Display (' . - \ s:tlist_{a:fidx}_filename . ')') - " If the file is not visible then no need to remove it - if !s:tlist_{a:fidx}_visible - return - endif - - " Remove the tags displayed for the specified file from the window - let start = s:tlist_{a:fidx}_start - " Include the empty line after the last line also - if g:Tlist_Compact_Format - let end = s:tlist_{a:fidx}_end - else - let end = s:tlist_{a:fidx}_end + 1 - endif - - setlocal modifiable - exe 'silent! ' . start . ',' . end . 'delete _' - setlocal nomodifiable - - " Correct the start and end line offsets for all the files following - " this file, as the tags for this file are removed - call s:Tlist_Window_Update_Line_Offsets(a:fidx + 1, 0, end - start + 1) -endfunction - -" Tlist_Remove_File -" Remove the file under the cursor or the specified file index -" user_request - User requested to remove the file from taglist -function! s:Tlist_Remove_File(file_idx, user_request) - let fidx = a:file_idx - - if fidx == -1 - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - endif - call s:Tlist_Log_Msg('Tlist_Remove_File (' . - \ s:tlist_{fidx}_filename . ', ' . a:user_request . ')') - - let save_winnr = winnr() - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Taglist window is open, remove the file from display - - if save_winnr != winnum - let old_eventignore = &eventignore - set eventignore=all - exe winnum . 'wincmd w' - endif - - call s:Tlist_Window_Remove_File_From_Display(fidx) - - if save_winnr != winnum - exe save_winnr . 'wincmd w' - let &eventignore = old_eventignore - endif - endif - - let fname = s:tlist_{fidx}_filename - - if a:user_request - " As the user requested to remove the file from taglist, - " add it to the removed list - call s:Tlist_Update_Remove_List(fname, 1) - endif - - " Remove the file name from the taglist list of filenames - let idx = stridx(s:tlist_file_names, fname . "\n") - let text_before = strpart(s:tlist_file_names, 0, idx) - let rem_text = strpart(s:tlist_file_names, idx) - let next_idx = stridx(rem_text, "\n") - let text_after = strpart(rem_text, next_idx + 1) - let s:tlist_file_names = text_before . text_after - - call s:Tlist_Discard_FileInfo(fidx) - - " Shift all the file variables by one index - let i = fidx + 1 - - while i < s:tlist_file_count - let j = i - 1 - - let s:tlist_{j}_filename = s:tlist_{i}_filename - let s:tlist_{j}_sort_type = s:tlist_{i}_sort_type - let s:tlist_{j}_filetype = s:tlist_{i}_filetype - let s:tlist_{j}_mtime = s:tlist_{i}_mtime - let s:tlist_{j}_start = s:tlist_{i}_start - let s:tlist_{j}_end = s:tlist_{i}_end - let s:tlist_{j}_valid = s:tlist_{i}_valid - let s:tlist_{j}_visible = s:tlist_{i}_visible - let s:tlist_{j}_tag_count = s:tlist_{i}_tag_count - let s:tlist_{j}_menu_cmd = s:tlist_{i}_menu_cmd - - let k = 1 - while k <= s:tlist_{j}_tag_count - let s:tlist_{j}_{k}_tag = s:tlist_{i}_{k}_tag - let s:tlist_{j}_{k}_tag_name = s:tlist_{i}_{k}_tag_name - let s:tlist_{j}_{k}_tag_type = s:Tlist_Get_Tag_Type_By_Tag(i, k) - let s:tlist_{j}_{k}_ttype_idx = s:tlist_{i}_{k}_ttype_idx - let s:tlist_{j}_{k}_tag_proto = s:Tlist_Get_Tag_Prototype(i, k) - let s:tlist_{j}_{k}_tag_searchpat = s:Tlist_Get_Tag_SearchPat(i, k) - let s:tlist_{j}_{k}_tag_linenum = s:Tlist_Get_Tag_Linenum(i, k) - let k = k + 1 - endwhile - - let ftype = s:tlist_{i}_filetype - - let k = 1 - while k <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{k}_name - let s:tlist_{j}_{ttype} = s:tlist_{i}_{ttype} - let s:tlist_{j}_{ttype}_offset = s:tlist_{i}_{ttype}_offset - let s:tlist_{j}_{ttype}_count = s:tlist_{i}_{ttype}_count - if s:tlist_{j}_{ttype} != '' - let l = 1 - while l <= s:tlist_{j}_{ttype}_count - let s:tlist_{j}_{ttype}_{l} = s:tlist_{i}_{ttype}_{l} - let l = l + 1 - endwhile - endif - let k = k + 1 - endwhile - - " As the file and tag information is copied to the new index, - " discard the previous information - call s:Tlist_Discard_FileInfo(i) - - let i = i + 1 - endwhile - - " Reduce the number of files displayed - let s:tlist_file_count = s:tlist_file_count - 1 - - if g:Tlist_Show_One_File - " If the tags for only one file is displayed and if we just - " now removed that file, then invalidate the current file idx - if s:tlist_cur_file_idx == fidx - let s:tlist_cur_file_idx = -1 - endif - endif -endfunction - -" Tlist_Window_Goto_Window -" Goto the taglist window -function! s:Tlist_Window_Goto_Window() - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - if winnr() != winnum - call s:Tlist_Exe_Cmd_No_Acmds(winnum . 'wincmd w') - endif - endif -endfunction - -" Tlist_Window_Create -" Create a new taglist window. If it is already open, jump to it -function! s:Tlist_Window_Create() - call s:Tlist_Log_Msg('Tlist_Window_Create()') - " If the window is open, jump to it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Jump to the existing window - if winnr() != winnum - exe winnum . 'wincmd w' - endif - return - endif - - " If used with winmanager don't open windows. Winmanager will handle - " the window/buffer management - if s:tlist_app_name == "winmanager" - return - endif - - " Create a new window. If user prefers a horizontal window, then open - " a horizontally split window. Otherwise open a vertically split - " window - if g:Tlist_Use_Horiz_Window - " Open a horizontally split window - let win_dir = 'botright' - " Horizontal window height - let win_size = g:Tlist_WinHeight - else - if s:tlist_winsize_chgd == -1 - " Open a vertically split window. Increase the window size, if - " needed, to accomodate the new window - if g:Tlist_Inc_Winwidth && - \ &columns < (80 + g:Tlist_WinWidth) - " Save the original window position - let s:tlist_pre_winx = getwinposx() - let s:tlist_pre_winy = getwinposy() - - " one extra column is needed to include the vertical split - let &columns= &columns + g:Tlist_WinWidth + 1 - - let s:tlist_winsize_chgd = 1 - else - let s:tlist_winsize_chgd = 0 - endif - endif - - if g:Tlist_Use_Right_Window - " Open the window at the rightmost place - let win_dir = 'botright vertical' - else - " Open the window at the leftmost place - let win_dir = 'topleft vertical' - endif - let win_size = g:Tlist_WinWidth - endif - - " If the tag listing temporary buffer already exists, then reuse it. - " Otherwise create a new buffer - let bufnum = bufnr(g:TagList_title) - if bufnum == -1 - " Create a new buffer - let wcmd = g:TagList_title - else - " Edit the existing buffer - let wcmd = '+buffer' . bufnum - endif - - " Create the taglist window - exe 'silent! ' . win_dir . ' ' . win_size . 'split ' . wcmd - - " Save the new window position - let s:tlist_winx = getwinposx() - let s:tlist_winy = getwinposy() - - " Initialize the taglist window - call s:Tlist_Window_Init() -endfunction - -" Tlist_Window_Zoom -" Zoom (maximize/minimize) the taglist window -function! s:Tlist_Window_Zoom() - if s:tlist_win_maximized - " Restore the window back to the previous size - if g:Tlist_Use_Horiz_Window - exe 'resize ' . g:Tlist_WinHeight - else - exe 'vert resize ' . g:Tlist_WinWidth - endif - let s:tlist_win_maximized = 0 - else - " Set the window size to the maximum possible without closing other - " windows - if g:Tlist_Use_Horiz_Window - resize - else - vert resize - endif - let s:tlist_win_maximized = 1 - endif -endfunction - -" Tlist_Ballon_Expr -" When the mouse cursor is over a tag in the taglist window, display the -" tag prototype (balloon) -function! Tlist_Ballon_Expr() - " Get the file index - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(v:beval_lnum) - if fidx == -1 - return '' - endif - - " Get the tag output line for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, v:beval_lnum) - if tidx == 0 - return '' - endif - - " Get the tag search pattern and display it - return s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Window_Check_Width -" Check the width of the taglist window. For horizontally split windows, the -" 'winfixheight' option is used to fix the height of the window. For -" vertically split windows, Vim doesn't support the 'winfixwidth' option. So -" need to handle window width changes from this function. -function! s:Tlist_Window_Check_Width() - let tlist_winnr = bufwinnr(g:TagList_title) - if tlist_winnr == -1 - return - endif - - let width = winwidth(tlist_winnr) - if width != g:Tlist_WinWidth - call s:Tlist_Log_Msg("Tlist_Window_Check_Width: Changing window " . - \ "width from " . width . " to " . g:Tlist_WinWidth) - let save_winnr = winnr() - if save_winnr != tlist_winnr - call s:Tlist_Exe_Cmd_No_Acmds(tlist_winnr . 'wincmd w') - endif - exe 'vert resize ' . g:Tlist_WinWidth - if save_winnr != tlist_winnr - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - endif -endfunction - -" Tlist_Window_Exit_Only_Window -" If the 'Tlist_Exit_OnlyWindow' option is set, then exit Vim if only the -" taglist window is present. -function! s:Tlist_Window_Exit_Only_Window() - " Before quitting Vim, delete the taglist buffer so that - " the '0 mark is correctly set to the previous buffer. - if v:version < 700 - if winbufnr(2) == -1 - bdelete - quit - endif - else - if winbufnr(2) == -1 - if tabpagenr('$') == 1 - " Only one tag page is present - bdelete - quit - else - " More than one tab page is present. Close only the current - " tab page - close - endif - endif - endif -endfunction - -" Tlist_Window_Init -" Set the default options for the taglist window -function! s:Tlist_Window_Init() - call s:Tlist_Log_Msg('Tlist_Window_Init()') - - " The 'readonly' option should not be set for the taglist buffer. - " If Vim is started as "view/gview" or if the ":view" command is - " used, then the 'readonly' option is set for all the buffers. - " Unset it for the taglist buffer - setlocal noreadonly - - " Set the taglist buffer filetype to taglist - setlocal filetype=taglist - - " Define taglist window element highlighting - syntax match TagListComment '^" .*' - syntax match TagListFileName '^[^" ].*$' - syntax match TagListTitle '^ \S.*$' - syntax match TagListTagScope '\s\[.\{-\}\]$' - - " Define the highlighting only if colors are supported - if has('gui_running') || &t_Co > 2 - " Colors to highlight various taglist window elements - " If user defined highlighting group exists, then use them. - " Otherwise, use default highlight groups. - if hlexists('MyTagListTagName') - highlight link TagListTagName MyTagListTagName - else - highlight default link TagListTagName Search - endif - " Colors to highlight comments and titles - if hlexists('MyTagListComment') - highlight link TagListComment MyTagListComment - else - highlight clear TagListComment - highlight default link TagListComment Comment - endif - if hlexists('MyTagListTitle') - highlight link TagListTitle MyTagListTitle - else - highlight clear TagListTitle - highlight default link TagListTitle Title - endif - if hlexists('MyTagListFileName') - highlight link TagListFileName MyTagListFileName - else - highlight clear TagListFileName - highlight default TagListFileName guibg=Grey ctermbg=darkgray - \ guifg=white ctermfg=white - endif - if hlexists('MyTagListTagScope') - highlight link TagListTagScope MyTagListTagScope - else - highlight clear TagListTagScope - highlight default link TagListTagScope Identifier - endif - else - highlight default TagListTagName term=reverse cterm=reverse - endif - - " Folding related settings - setlocal foldenable - setlocal foldminlines=0 - setlocal foldmethod=manual - setlocal foldlevel=9999 - if g:Tlist_Enable_Fold_Column - setlocal foldcolumn=3 - else - setlocal foldcolumn=0 - endif - setlocal foldtext=v:folddashes.getline(v:foldstart) - - if s:tlist_app_name != "winmanager" - " Mark buffer as scratch - silent! setlocal buftype=nofile - if s:tlist_app_name == "none" - silent! setlocal bufhidden=delete - endif - silent! setlocal noswapfile - " Due to a bug in Vim 6.0, the winbufnr() function fails for unlisted - " buffers. So if the taglist buffer is unlisted, multiple taglist - " windows will be opened. This bug is fixed in Vim 6.1 and above - if v:version >= 601 - silent! setlocal nobuflisted - endif - endif - - silent! setlocal nowrap - - " If the 'number' option is set in the source window, it will affect the - " taglist window. So forcefully disable 'number' option for the taglist - " window - silent! setlocal nonumber - - " Use fixed height when horizontally split window is used - if g:Tlist_Use_Horiz_Window - if v:version >= 602 - set winfixheight - endif - endif - if !g:Tlist_Use_Horiz_Window && v:version >= 700 - set winfixwidth - endif - - " Setup balloon evaluation to display tag prototype - if v:version >= 700 && has('balloon_eval') - setlocal balloonexpr=Tlist_Ballon_Expr() - set ballooneval - endif - - " Setup the cpoptions properly for the maps to work - let old_cpoptions = &cpoptions - set cpoptions&vim - - " Create buffer local mappings for jumping to the tags and sorting the list - nnoremap <buffer> <silent> <CR> - \ :call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - nnoremap <buffer> <silent> o - \ :call <SID>Tlist_Window_Jump_To_Tag('newwin')<CR> - nnoremap <buffer> <silent> p - \ :call <SID>Tlist_Window_Jump_To_Tag('preview')<CR> - nnoremap <buffer> <silent> P - \ :call <SID>Tlist_Window_Jump_To_Tag('prevwin')<CR> - if v:version >= 700 - nnoremap <buffer> <silent> t - \ :call <SID>Tlist_Window_Jump_To_Tag('checktab')<CR> - nnoremap <buffer> <silent> <C-t> - \ :call <SID>Tlist_Window_Jump_To_Tag('newtab')<CR> - endif - nnoremap <buffer> <silent> <2-LeftMouse> - \ :call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - nnoremap <buffer> <silent> s - \ :call <SID>Tlist_Change_Sort('cmd', 'toggle', '')<CR> - nnoremap <buffer> <silent> + :silent! foldopen<CR> - nnoremap <buffer> <silent> - :silent! foldclose<CR> - nnoremap <buffer> <silent> * :silent! %foldopen!<CR> - nnoremap <buffer> <silent> = :silent! %foldclose<CR> - nnoremap <buffer> <silent> <kPlus> :silent! foldopen<CR> - nnoremap <buffer> <silent> <kMinus> :silent! foldclose<CR> - nnoremap <buffer> <silent> <kMultiply> :silent! %foldopen!<CR> - nnoremap <buffer> <silent> <Space> :call <SID>Tlist_Window_Show_Info()<CR> - nnoremap <buffer> <silent> u :call <SID>Tlist_Window_Update_File()<CR> - nnoremap <buffer> <silent> d :call <SID>Tlist_Remove_File(-1, 1)<CR> - nnoremap <buffer> <silent> x :call <SID>Tlist_Window_Zoom()<CR> - nnoremap <buffer> <silent> [[ :call <SID>Tlist_Window_Move_To_File(-1)<CR> - nnoremap <buffer> <silent> <BS> :call <SID>Tlist_Window_Move_To_File(-1)<CR> - nnoremap <buffer> <silent> ]] :call <SID>Tlist_Window_Move_To_File(1)<CR> - nnoremap <buffer> <silent> <Tab> :call <SID>Tlist_Window_Move_To_File(1)<CR> - nnoremap <buffer> <silent> <F1> :call <SID>Tlist_Window_Toggle_Help_Text()<CR> - nnoremap <buffer> <silent> q :close<CR> - - " Insert mode mappings - inoremap <buffer> <silent> <CR> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - " Windows needs return - inoremap <buffer> <silent> <Return> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - inoremap <buffer> <silent> o - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('newwin')<CR> - inoremap <buffer> <silent> p - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('preview')<CR> - inoremap <buffer> <silent> P - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('prevwin')<CR> - if v:version >= 700 - inoremap <buffer> <silent> t - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('checktab')<CR> - inoremap <buffer> <silent> <C-t> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('newtab')<CR> - endif - inoremap <buffer> <silent> <2-LeftMouse> - \ <C-o>:call <SID>Tlist_Window_Jump_To_Tag('useopen')<CR> - inoremap <buffer> <silent> s - \ <C-o>:call <SID>Tlist_Change_Sort('cmd', 'toggle', '')<CR> - inoremap <buffer> <silent> + <C-o>:silent! foldopen<CR> - inoremap <buffer> <silent> - <C-o>:silent! foldclose<CR> - inoremap <buffer> <silent> * <C-o>:silent! %foldopen!<CR> - inoremap <buffer> <silent> = <C-o>:silent! %foldclose<CR> - inoremap <buffer> <silent> <kPlus> <C-o>:silent! foldopen<CR> - inoremap <buffer> <silent> <kMinus> <C-o>:silent! foldclose<CR> - inoremap <buffer> <silent> <kMultiply> <C-o>:silent! %foldopen!<CR> - inoremap <buffer> <silent> <Space> <C-o>:call - \ <SID>Tlist_Window_Show_Info()<CR> - inoremap <buffer> <silent> u - \ <C-o>:call <SID>Tlist_Window_Update_File()<CR> - inoremap <buffer> <silent> d <C-o>:call <SID>Tlist_Remove_File(-1, 1)<CR> - inoremap <buffer> <silent> x <C-o>:call <SID>Tlist_Window_Zoom()<CR> - inoremap <buffer> <silent> [[ <C-o>:call <SID>Tlist_Window_Move_To_File(-1)<CR> - inoremap <buffer> <silent> <BS> <C-o>:call <SID>Tlist_Window_Move_To_File(-1)<CR> - inoremap <buffer> <silent> ]] <C-o>:call <SID>Tlist_Window_Move_To_File(1)<CR> - inoremap <buffer> <silent> <Tab> <C-o>:call <SID>Tlist_Window_Move_To_File(1)<CR> - inoremap <buffer> <silent> <F1> <C-o>:call <SID>Tlist_Window_Toggle_Help_Text()<CR> - inoremap <buffer> <silent> q <C-o>:close<CR> - - " Map single left mouse click if the user wants this functionality - if g:Tlist_Use_SingleClick == 1 - " Contributed by Bindu Wavell - " attempt to perform single click mapping, it would be much - " nicer if we could nnoremap <buffer> ... however vim does - " not fire the <buffer> <leftmouse> when you use the mouse - " to enter a buffer. - let clickmap = ':if bufname("%") =~ "__Tag_List__" <bar> ' . - \ 'call <SID>Tlist_Window_Jump_To_Tag("useopen") ' . - \ '<bar> endif <CR>' - if maparg('<leftmouse>', 'n') == '' - " no mapping for leftmouse - exe ':nnoremap <silent> <leftmouse> <leftmouse>' . clickmap - else - " we have a mapping - let mapcmd = ':nnoremap <silent> <leftmouse> <leftmouse>' - let mapcmd = mapcmd . substitute(substitute( - \ maparg('<leftmouse>', 'n'), '|', '<bar>', 'g'), - \ '\c^<leftmouse>', '', '') - let mapcmd = mapcmd . clickmap - exe mapcmd - endif - endif - - " Define the taglist autocommands - augroup TagListAutoCmds - autocmd! - " Display the tag prototype for the tag under the cursor. - autocmd CursorHold __Tag_List__ call s:Tlist_Window_Show_Info() - " Highlight the current tag periodically - autocmd CursorHold * silent call s:Tlist_Window_Highlight_Tag( - \ fnamemodify(bufname('%'), ':p'), line('.'), 1, 0) - - " Adjust the Vim window width when taglist window is closed - autocmd BufUnload __Tag_List__ call s:Tlist_Post_Close_Cleanup() - " Close the fold for this buffer when leaving the buffer - if g:Tlist_File_Fold_Auto_Close - autocmd BufEnter * silent - \ call s:Tlist_Window_Open_File_Fold(expand('<abuf>')) - endif - " Exit Vim itself if only the taglist window is present (optional) - if g:Tlist_Exit_OnlyWindow - autocmd BufEnter __Tag_List__ nested - \ call s:Tlist_Window_Exit_Only_Window() - endif - if s:tlist_app_name != "winmanager" && - \ !g:Tlist_Process_File_Always && - \ (!has('gui_running') || !g:Tlist_Show_Menu) - " Auto refresh the taglist window - autocmd BufEnter * call s:Tlist_Refresh() - endif - - if !g:Tlist_Use_Horiz_Window - if v:version < 700 - autocmd WinEnter * call s:Tlist_Window_Check_Width() - endif - endif - if v:version >= 700 - autocmd TabEnter * silent call s:Tlist_Refresh_Folds() - endif - augroup end - - " Restore the previous cpoptions settings - let &cpoptions = old_cpoptions -endfunction - -" Tlist_Window_Refresh -" Display the tags for all the files in the taglist window -function! s:Tlist_Window_Refresh() - call s:Tlist_Log_Msg('Tlist_Window_Refresh()') - " Set report option to a huge value to prevent informational messages - " while deleting the lines - let old_report = &report - set report=99999 - - " Mark the buffer as modifiable - setlocal modifiable - - " Delete the contents of the buffer to the black-hole register - silent! %delete _ - - " As we have cleared the taglist window, mark all the files - " as not visible - let i = 0 - while i < s:tlist_file_count - let s:tlist_{i}_visible = 0 - let i = i + 1 - endwhile - - if g:Tlist_Compact_Format == 0 - " Display help in non-compact mode - call s:Tlist_Window_Display_Help() - endif - - " Mark the buffer as not modifiable - setlocal nomodifiable - - " Restore the report option - let &report = old_report - - " If the tags for only one file should be displayed in the taglist - " window, then no need to add the tags here. The bufenter autocommand - " will add the tags for that file. - if g:Tlist_Show_One_File - return - endif - - " List all the tags for the previously processed files - " Do this only if taglist is configured to display tags for more than - " one file. Otherwise, when Tlist_Show_One_File is configured, - " tags for the wrong file will be displayed. - let i = 0 - while i < s:tlist_file_count - call s:Tlist_Window_Refresh_File(s:tlist_{i}_filename, - \ s:tlist_{i}_filetype) - let i = i + 1 - endwhile - - if g:Tlist_Auto_Update - " Add and list the tags for all buffers in the Vim buffer list - let i = 1 - let last_bufnum = bufnr('$') - while i <= last_bufnum - if buflisted(i) - let fname = fnamemodify(bufname(i), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype(i) - " If the file doesn't support tag listing, skip it - if !s:Tlist_Skip_File(fname, ftype) - call s:Tlist_Window_Refresh_File(fname, ftype) - endif - endif - let i = i + 1 - endwhile - endif - - " If Tlist_File_Fold_Auto_Close option is set, then close all the folds - if g:Tlist_File_Fold_Auto_Close - " Close all the folds - silent! %foldclose - endif - - " Move the cursor to the top of the taglist window - normal! gg -endfunction - -" Tlist_Post_Close_Cleanup() -" Close the taglist window and adjust the Vim window width -function! s:Tlist_Post_Close_Cleanup() - call s:Tlist_Log_Msg('Tlist_Post_Close_Cleanup()') - " Mark all the files as not visible - let i = 0 - while i < s:tlist_file_count - let s:tlist_{i}_visible = 0 - let i = i + 1 - endwhile - - " Remove the taglist autocommands - silent! autocmd! TagListAutoCmds - - " Clear all the highlights - match none - - silent! syntax clear TagListTitle - silent! syntax clear TagListComment - silent! syntax clear TagListTagScope - - " Remove the left mouse click mapping if it was setup initially - if g:Tlist_Use_SingleClick - if hasmapto('<LeftMouse>') - nunmap <LeftMouse> - endif - endif - - if s:tlist_app_name != "winmanager" - if g:Tlist_Use_Horiz_Window || g:Tlist_Inc_Winwidth == 0 || - \ s:tlist_winsize_chgd != 1 || - \ &columns < (80 + g:Tlist_WinWidth) - " No need to adjust window width if using horizontally split taglist - " window or if columns is less than 101 or if the user chose not to - " adjust the window width - else - " If the user didn't manually move the window, then restore the window - " position to the pre-taglist position - if s:tlist_pre_winx != -1 && s:tlist_pre_winy != -1 && - \ getwinposx() == s:tlist_winx && - \ getwinposy() == s:tlist_winy - exe 'winpos ' . s:tlist_pre_winx . ' ' . s:tlist_pre_winy - endif - - " Adjust the Vim window width - let &columns= &columns - (g:Tlist_WinWidth + 1) - endif - endif - - let s:tlist_winsize_chgd = -1 - - " Reset taglist state variables - if s:tlist_app_name == "winmanager" - let s:tlist_app_name = "none" - endif - let s:tlist_window_initialized = 0 -endfunction - -" Tlist_Window_Refresh_File() -" List the tags defined in the specified file in a Vim window -function! s:Tlist_Window_Refresh_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Window_Refresh_File (' . a:filename . ')') - " First check whether the file already exists - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx != -1 - let file_listed = 1 - else - let file_listed = 0 - endif - - if !file_listed - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(a:filename) - return - endif - endif - - if file_listed && s:tlist_{fidx}_visible - " Check whether the file tags are currently valid - if s:tlist_{fidx}_valid - " Goto the first line in the file - exe s:tlist_{fidx}_start - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - endif - return - endif - - " Discard and remove the tags for this file from display - call s:Tlist_Discard_TagInfo(fidx) - call s:Tlist_Window_Remove_File_From_Display(fidx) - endif - - " Process and generate a list of tags defined in the file - if !file_listed || !s:tlist_{fidx}_valid - let ret_fidx = s:Tlist_Process_File(a:filename, a:ftype) - if ret_fidx == -1 - return - endif - let fidx = ret_fidx - endif - - " Set report option to a huge value to prevent informational messages - " while adding lines to the taglist window - let old_report = &report - set report=99999 - - if g:Tlist_Show_One_File - " Remove the previous file - if s:tlist_cur_file_idx != -1 - call s:Tlist_Window_Remove_File_From_Display(s:tlist_cur_file_idx) - let s:tlist_{s:tlist_cur_file_idx}_visible = 0 - let s:tlist_{s:tlist_cur_file_idx}_start = 0 - let s:tlist_{s:tlist_cur_file_idx}_end = 0 - endif - let s:tlist_cur_file_idx = fidx - endif - - " Mark the buffer as modifiable - setlocal modifiable - - " Add new files to the end of the window. For existing files, add them at - " the same line where they were previously present. If the file is not - " visible, then add it at the end - if s:tlist_{fidx}_start == 0 || !s:tlist_{fidx}_visible - if g:Tlist_Compact_Format - let s:tlist_{fidx}_start = line('$') - else - let s:tlist_{fidx}_start = line('$') + 1 - endif - endif - - let s:tlist_{fidx}_visible = 1 - - " Goto the line where this file should be placed - if g:Tlist_Compact_Format - exe s:tlist_{fidx}_start - else - exe s:tlist_{fidx}_start - 1 - endif - - let txt = fnamemodify(s:tlist_{fidx}_filename, ':t') . ' (' . - \ fnamemodify(s:tlist_{fidx}_filename, ':p:h') . ')' - if g:Tlist_Compact_Format == 0 - silent! put =txt - else - silent! put! =txt - " Move to the next line - exe line('.') + 1 - endif - let file_start = s:tlist_{fidx}_start - - " Add the tag names grouped by tag type to the buffer with a title - let i = 1 - let ttype_cnt = s:tlist_{a:ftype}_count - while i <= ttype_cnt - let ttype = s:tlist_{a:ftype}_{i}_name - " Add the tag type only if there are tags for that type - let fidx_ttype = 's:tlist_' . fidx . '_' . ttype - let ttype_txt = {fidx_ttype} - if ttype_txt != '' - let txt = ' ' . s:tlist_{a:ftype}_{i}_fullname - if g:Tlist_Compact_Format == 0 - let ttype_start_lnum = line('.') + 1 - silent! put =txt - else - let ttype_start_lnum = line('.') - silent! put! =txt - endif - silent! put =ttype_txt - - let {fidx_ttype}_offset = ttype_start_lnum - file_start - - " create a fold for this tag type - let fold_start = ttype_start_lnum - let fold_end = fold_start + {fidx_ttype}_count - exe fold_start . ',' . fold_end . 'fold' - - " Adjust the cursor position - if g:Tlist_Compact_Format == 0 - exe ttype_start_lnum + {fidx_ttype}_count - else - exe ttype_start_lnum + {fidx_ttype}_count + 1 - endif - - if g:Tlist_Compact_Format == 0 - " Separate the tag types by a empty line - silent! put ='' - endif - endif - let i = i + 1 - endwhile - - if s:tlist_{fidx}_tag_count == 0 - if g:Tlist_Compact_Format == 0 - silent! put ='' - endif - endif - - let s:tlist_{fidx}_end = line('.') - 1 - - " Create a fold for the entire file - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'fold' - exe 'silent! ' . s:tlist_{fidx}_start . ',' . - \ s:tlist_{fidx}_end . 'foldopen!' - - " Goto the starting line for this file, - exe s:tlist_{fidx}_start - - if s:tlist_app_name == "winmanager" - " To handle a bug in the winmanager plugin, add a space at the - " last line - call setline('$', ' ') - endif - - " Mark the buffer as not modifiable - setlocal nomodifiable - - " Restore the report option - let &report = old_report - - " Update the start and end line numbers for all the files following this - " file - let start = s:tlist_{fidx}_start - " include the empty line after the last line - if g:Tlist_Compact_Format - let end = s:tlist_{fidx}_end - else - let end = s:tlist_{fidx}_end + 1 - endif - call s:Tlist_Window_Update_Line_Offsets(fidx + 1, 1, end - start + 1) - - " Now that we have updated the taglist window, update the tags - " menu (if present) - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(1) - endif -endfunction - -" Tlist_Init_File -" Initialize the variables for a new file -function! s:Tlist_Init_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Init_File (' . a:filename . ')') - " Add new files at the end of the list - let fidx = s:tlist_file_count - let s:tlist_file_count = s:tlist_file_count + 1 - " Add the new file name to the taglist list of file names - let s:tlist_file_names = s:tlist_file_names . a:filename . "\n" - - " Initialize the file variables - let s:tlist_{fidx}_filename = a:filename - let s:tlist_{fidx}_sort_type = g:Tlist_Sort_Type - let s:tlist_{fidx}_filetype = a:ftype - let s:tlist_{fidx}_mtime = -1 - let s:tlist_{fidx}_start = 0 - let s:tlist_{fidx}_end = 0 - let s:tlist_{fidx}_valid = 0 - let s:tlist_{fidx}_visible = 0 - let s:tlist_{fidx}_tag_count = 0 - let s:tlist_{fidx}_menu_cmd = '' - - " Initialize the tag type variables - let i = 1 - while i <= s:tlist_{a:ftype}_count - let ttype = s:tlist_{a:ftype}_{i}_name - let s:tlist_{fidx}_{ttype} = '' - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = 0 - let i = i + 1 - endwhile - - return fidx -endfunction - -" Tlist_Get_Tag_Type_By_Tag -" Return the tag type for the specified tag index -function! s:Tlist_Get_Tag_Type_By_Tag(fidx, tidx) - let ttype_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_type' - - " Already parsed and have the tag name - if exists(ttype_var) - return {ttype_var} - endif - - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let {ttype_var} = s:Tlist_Extract_Tagtype(tag_line) - - return {ttype_var} -endfunction - -" Tlist_Get_Tag_Prototype -function! s:Tlist_Get_Tag_Prototype(fidx, tidx) - let tproto_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_proto' - - " Already parsed and have the tag prototype - if exists(tproto_var) - return {tproto_var} - endif - - " Parse and extract the tag prototype - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = stridx(tag_line, '/^') + 2 - let end = stridx(tag_line, '/;"' . "\t") - if tag_line[end - 1] == '$' - let end = end -1 - endif - let tag_proto = strpart(tag_line, start, end - start) - let {tproto_var} = substitute(tag_proto, '\s*', '', '') - - return {tproto_var} -endfunction - -" Tlist_Get_Tag_SearchPat -function! s:Tlist_Get_Tag_SearchPat(fidx, tidx) - let tpat_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_searchpat' - - " Already parsed and have the tag search pattern - if exists(tpat_var) - return {tpat_var} - endif - - " Parse and extract the tag search pattern - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = stridx(tag_line, '/^') + 2 - let end = stridx(tag_line, '/;"' . "\t") - if tag_line[end - 1] == '$' - let end = end -1 - endif - let {tpat_var} = '\V\^' . strpart(tag_line, start, end - start) . - \ (tag_line[end] == '$' ? '\$' : '') - - return {tpat_var} -endfunction - -" Tlist_Get_Tag_Linenum -" Return the tag line number, given the tag index -function! s:Tlist_Get_Tag_Linenum(fidx, tidx) - let tline_var = 's:tlist_' . a:fidx . '_' . a:tidx . '_tag_linenum' - - " Already parsed and have the tag line number - if exists(tline_var) - return {tline_var} - endif - - " Parse and extract the tag line number - let tag_line = s:tlist_{a:fidx}_{a:tidx}_tag - let start = strridx(tag_line, 'line:') + 5 - let end = strridx(tag_line, "\t") - if end < start - let {tline_var} = strpart(tag_line, start) + 0 - else - let {tline_var} = strpart(tag_line, start, end - start) + 0 - endif - - return {tline_var} -endfunction - -" Tlist_Parse_Tagline -" Parse a tag line from the ctags output. Separate the tag output based on the -" tag type and store it in the tag type variable. -" The format of each line in the ctags output is: -" -" tag_name<TAB>file_name<TAB>ex_cmd;"<TAB>extension_fields -" -function! s:Tlist_Parse_Tagline(tag_line) - if a:tag_line == '' - " Skip empty lines - return - endif - - " Extract the tag type - let ttype = s:Tlist_Extract_Tagtype(a:tag_line) - - " Make sure the tag type is a valid and supported one - if ttype == '' || stridx(s:ctags_flags, ttype) == -1 - " Line is not in proper tags format or Tag type is not supported - return - endif - - " Update the total tag count - let s:tidx = s:tidx + 1 - - " The following variables are used to optimize this code. Vim is slow in - " using curly brace names. To reduce the amount of processing needed, the - " curly brace variables are pre-processed here - let fidx_tidx = 's:tlist_' . s:fidx . '_' . s:tidx - let fidx_ttype = 's:tlist_' . s:fidx . '_' . ttype - - " Update the count of this tag type - let ttype_idx = {fidx_ttype}_count + 1 - let {fidx_ttype}_count = ttype_idx - - " Store the ctags output for this tag - let {fidx_tidx}_tag = a:tag_line - - " Store the tag index and the tag type index (back pointers) - let {fidx_ttype}_{ttype_idx} = s:tidx - let {fidx_tidx}_ttype_idx = ttype_idx - - " Extract the tag name - let tag_name = strpart(a:tag_line, 0, stridx(a:tag_line, "\t")) - - " Extract the tag scope/prototype - if g:Tlist_Display_Prototype - let ttxt = ' ' . s:Tlist_Get_Tag_Prototype(s:fidx, s:tidx) - else - let ttxt = ' ' . tag_name - - " Add the tag scope, if it is available and is configured. Tag - " scope is the last field after the 'line:<num>\t' field - if g:Tlist_Display_Tag_Scope - let tag_scope = s:Tlist_Extract_Tag_Scope(a:tag_line) - if tag_scope != '' - let ttxt = ttxt . ' [' . tag_scope . ']' - endif - endif - endif - - " Add this tag to the tag type variable - let {fidx_ttype} = {fidx_ttype} . ttxt . "\n" - - " Save the tag name - let {fidx_tidx}_tag_name = tag_name -endfunction - -" Tlist_Process_File -" Get the list of tags defined in the specified file and store them -" in Vim variables. Returns the file index where the tags are stored. -function! s:Tlist_Process_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Process_File (' . a:filename . ', ' . - \ a:ftype . ')') - " Check whether this file is supported - if s:Tlist_Skip_File(a:filename, a:ftype) - return -1 - endif - - " If the tag types for this filetype are not yet created, then create - " them now - let var = 's:tlist_' . a:ftype . '_count' - if !exists(var) - if s:Tlist_FileType_Init(a:ftype) == 0 - return -1 - endif - endif - - " If this file is already processed, then use the cached values - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - " First time, this file is loaded - let fidx = s:Tlist_Init_File(a:filename, a:ftype) - else - " File was previously processed. Discard the tag information - call s:Tlist_Discard_TagInfo(fidx) - endif - - let s:tlist_{fidx}_valid = 1 - - " Exuberant ctags arguments to generate a tag list - let ctags_args = ' -f - --format=2 --excmd=pattern --fields=nks ' - - " Form the ctags argument depending on the sort type - if s:tlist_{fidx}_sort_type == 'name' - let ctags_args = ctags_args . '--sort=yes' - else - let ctags_args = ctags_args . '--sort=no' - endif - - " Add the filetype specific arguments - let ctags_args = ctags_args . ' ' . s:tlist_{a:ftype}_ctags_args - - " Ctags command to produce output with regexp for locating the tags - let ctags_cmd = g:Tlist_Ctags_Cmd . ctags_args - let ctags_cmd = ctags_cmd . ' "' . a:filename . '"' - - if &shellxquote == '"' - " Double-quotes within double-quotes will not work in the - " command-line.If the 'shellxquote' option is set to double-quotes, - " then escape the double-quotes in the ctags command-line. - let ctags_cmd = escape(ctags_cmd, '"') - endif - - " In Windows 95, if not using cygwin, disable the 'shellslash' - " option. Otherwise, this will cause problems when running the - " ctags command. - if has('win95') && !has('win32unix') - let old_shellslash = &shellslash - set noshellslash - endif - - if has('win32') && !has('win32unix') && !has('win95') - \ && (&shell =~ 'cmd.exe') - " Windows does not correctly deal with commands that have more than 1 - " set of double quotes. It will strip them all resulting in: - " 'C:\Program' is not recognized as an internal or external command - " operable program or batch file. To work around this, place the - " command inside a batch file and call the batch file. - " Do this only on Win2K, WinXP and above. - " Contributed by: David Fishburn. - let s:taglist_tempfile = fnamemodify(tempname(), ':h') . - \ '\taglist.cmd' - exe 'redir! > ' . s:taglist_tempfile - silent echo ctags_cmd - redir END - - call s:Tlist_Log_Msg('Cmd inside batch file: ' . ctags_cmd) - let ctags_cmd = '"' . s:taglist_tempfile . '"' - endif - - call s:Tlist_Log_Msg('Cmd: ' . ctags_cmd) - - " Run ctags and get the tag list - let cmd_output = system(ctags_cmd) - - " Restore the value of the 'shellslash' option. - if has('win95') && !has('win32unix') - let &shellslash = old_shellslash - endif - - if exists('s:taglist_tempfile') - " Delete the temporary cmd file created on MS-Windows - call delete(s:taglist_tempfile) - endif - - " Handle errors - if v:shell_error - let msg = "Taglist: Failed to generate tags for " . a:filename - call s:Tlist_Warning_Msg(msg) - if cmd_output != '' - call s:Tlist_Warning_Msg(cmd_output) - endif - return fidx - endif - - " Store the modification time for the file - let s:tlist_{fidx}_mtime = getftime(a:filename) - - " No tags for current file - if cmd_output == '' - call s:Tlist_Log_Msg('No tags defined in ' . a:filename) - return fidx - endif - - call s:Tlist_Log_Msg('Generated tags information for ' . a:filename) - - if v:version > 601 - " The following script local variables are used by the - " Tlist_Parse_Tagline() function. - let s:ctags_flags = s:tlist_{a:ftype}_ctags_flags - let s:fidx = fidx - let s:tidx = 0 - - " Process the ctags output one line at a time. The substitute() - " command is used to parse the tag lines instead of using the - " matchstr()/stridx()/strpart() functions for performance reason - call substitute(cmd_output, "\\([^\n]\\+\\)\n", - \ '\=s:Tlist_Parse_Tagline(submatch(1))', 'g') - - " Save the number of tags for this file - let s:tlist_{fidx}_tag_count = s:tidx - - " The following script local variables are no longer needed - unlet! s:ctags_flags - unlet! s:tidx - unlet! s:fidx - else - " Due to a bug in Vim earlier than version 6.1, - " we cannot use substitute() to parse the ctags output. - " Instead the slow str*() functions are used - let ctags_flags = s:tlist_{a:ftype}_ctags_flags - let tidx = 0 - - while cmd_output != '' - " Extract one line at a time - let idx = stridx(cmd_output, "\n") - let one_line = strpart(cmd_output, 0, idx) - " Remove the line from the tags output - let cmd_output = strpart(cmd_output, idx + 1) - - if one_line == '' - " Line is not in proper tags format - continue - endif - - " Extract the tag type - let ttype = s:Tlist_Extract_Tagtype(one_line) - - " Make sure the tag type is a valid and supported one - if ttype == '' || stridx(ctags_flags, ttype) == -1 - " Line is not in proper tags format or Tag type is not - " supported - continue - endif - - " Update the total tag count - let tidx = tidx + 1 - - " The following variables are used to optimize this code. Vim is - " slow in using curly brace names. To reduce the amount of - " processing needed, the curly brace variables are pre-processed - " here - let fidx_tidx = 's:tlist_' . fidx . '_' . tidx - let fidx_ttype = 's:tlist_' . fidx . '_' . ttype - - " Update the count of this tag type - let ttype_idx = {fidx_ttype}_count + 1 - let {fidx_ttype}_count = ttype_idx - - " Store the ctags output for this tag - let {fidx_tidx}_tag = one_line - - " Store the tag index and the tag type index (back pointers) - let {fidx_ttype}_{ttype_idx} = tidx - let {fidx_tidx}_ttype_idx = ttype_idx - - " Extract the tag name - let tag_name = strpart(one_line, 0, stridx(one_line, "\t")) - - " Extract the tag scope/prototype - if g:Tlist_Display_Prototype - let ttxt = ' ' . s:Tlist_Get_Tag_Prototype(fidx, tidx) - else - let ttxt = ' ' . tag_name - - " Add the tag scope, if it is available and is configured. Tag - " scope is the last field after the 'line:<num>\t' field - if g:Tlist_Display_Tag_Scope - let tag_scope = s:Tlist_Extract_Tag_Scope(one_line) - if tag_scope != '' - let ttxt = ttxt . ' [' . tag_scope . ']' - endif - endif - endif - - " Add this tag to the tag type variable - let {fidx_ttype} = {fidx_ttype} . ttxt . "\n" - - " Save the tag name - let {fidx_tidx}_tag_name = tag_name - endwhile - - " Save the number of tags for this file - let s:tlist_{fidx}_tag_count = tidx - endif - - call s:Tlist_Log_Msg('Processed ' . s:tlist_{fidx}_tag_count . - \ ' tags in ' . a:filename) - - return fidx -endfunction - -" Tlist_Update_File -" Update the tags for a file (if needed) -function! Tlist_Update_File(filename, ftype) - call s:Tlist_Log_Msg('Tlist_Update_File (' . a:filename . ')') - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(a:filename, a:ftype) - return - endif - - " Convert the file name to a full path - let fname = fnamemodify(a:filename, ':p') - - " First check whether the file already exists - let fidx = s:Tlist_Get_File_Index(fname) - - if fidx != -1 && s:tlist_{fidx}_valid - " File exists and the tags are valid - " Check whether the file was modified after the last tags update - " If it is modified, then update the tags - if s:tlist_{fidx}_mtime == getftime(fname) - return - endif - else - " If the tags were removed previously based on a user request, - " as we are going to update the tags (based on the user request), - " remove the filename from the deleted list - call s:Tlist_Update_Remove_List(fname, 0) - endif - - " If the taglist window is opened, update it - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - " Taglist window is not present. Just update the taglist - " and return - call s:Tlist_Process_File(fname, a:ftype) - else - if g:Tlist_Show_One_File && s:tlist_cur_file_idx != -1 - " If tags for only one file are displayed and we are not - " updating the tags for that file, then no need to - " refresh the taglist window. Otherwise, the taglist - " window should be updated. - if s:tlist_{s:tlist_cur_file_idx}_filename != fname - call s:Tlist_Process_File(fname, a:ftype) - return - endif - endif - - " Save the current window number - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - " Save the cursor position - let save_line = line('.') - let save_col = col('.') - - " Update the taglist window - call s:Tlist_Window_Refresh_File(fname, a:ftype) - - " Restore the cursor position - if v:version >= 601 - call cursor(save_line, save_col) - else - exe save_line - exe 'normal! ' . save_col . '|' - endif - - if winnr() != save_winnr - " Go back to the original window - call s:Tlist_Exe_Cmd_No_Acmds(save_winnr . 'wincmd w') - endif - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(1) - endif -endfunction - -" Tlist_Window_Close -" Close the taglist window -function! s:Tlist_Window_Close() - call s:Tlist_Log_Msg('Tlist_Window_Close()') - " Make sure the taglist window exists - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Error: Taglist window is not open') - return - endif - - if winnr() == winnum - " Already in the taglist window. Close it and return - if winbufnr(2) != -1 - " If a window other than the taglist window is open, - " then only close the taglist window. - close - endif - else - " Goto the taglist window, close it and then come back to the - " original window - let curbufnr = bufnr('%') - exe winnum . 'wincmd w' - close - " Need to jump back to the original window only if we are not - " already in that window - let winnum = bufwinnr(curbufnr) - if winnr() != winnum - exe winnum . 'wincmd w' - endif - endif -endfunction - -" Tlist_Window_Mark_File_Window -" Mark the current window as the file window to use when jumping to a tag. -" Only if the current window is a non-plugin, non-preview and non-taglist -" window -function! s:Tlist_Window_Mark_File_Window() - if getbufvar('%', '&buftype') == '' && !&previewwindow - let w:tlist_file_window = "yes" - endif -endfunction - -" Tlist_Window_Open -" Open and refresh the taglist window -function! s:Tlist_Window_Open() - call s:Tlist_Log_Msg('Tlist_Window_Open()') - " If the window is open, jump to it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - " Jump to the existing window - if winnr() != winnum - exe winnum . 'wincmd w' - endif - return - endif - - if s:tlist_app_name == "winmanager" - " Taglist plugin is no longer part of the winmanager app - let s:tlist_app_name = "none" - endif - - " Get the filename and filetype for the specified buffer - let curbuf_name = fnamemodify(bufname('%'), ':p') - let curbuf_ftype = s:Tlist_Get_Buffer_Filetype('%') - let cur_lnum = line('.') - - " Mark the current window as the desired window to open a file when a tag - " is selected. - call s:Tlist_Window_Mark_File_Window() - - " Open the taglist window - call s:Tlist_Window_Create() - - call s:Tlist_Window_Refresh() - - if g:Tlist_Show_One_File - " Add only the current buffer and file - " - " If the file doesn't support tag listing, skip it - if !s:Tlist_Skip_File(curbuf_name, curbuf_ftype) - call s:Tlist_Window_Refresh_File(curbuf_name, curbuf_ftype) - endif - endif - - if g:Tlist_File_Fold_Auto_Close - " Open the fold for the current file, as all the folds in - " the taglist window are closed - let fidx = s:Tlist_Get_File_Index(curbuf_name) - if fidx != -1 - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - endif - endif - - " Highlight the current tag - call s:Tlist_Window_Highlight_Tag(curbuf_name, cur_lnum, 1, 1) -endfunction - -" Tlist_Window_Toggle() -" Open or close a taglist window -function! s:Tlist_Window_Toggle() - call s:Tlist_Log_Msg('Tlist_Window_Toggle()') - " If taglist window is open then close it. - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - call s:Tlist_Window_Close() - return - endif - - call s:Tlist_Window_Open() - - " Go back to the original window, if Tlist_GainFocus_On_ToggleOpen is not - " set - if !g:Tlist_GainFocus_On_ToggleOpen - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif -endfunction - -" Tlist_Process_Filelist -" Process multiple files. Each filename is separated by "\n" -" Returns the number of processed files -function! s:Tlist_Process_Filelist(file_names) - let flist = a:file_names - - " Enable lazy screen updates - let old_lazyredraw = &lazyredraw - set lazyredraw - - " Keep track of the number of processed files - let fcnt = 0 - - " Process one file at a time - while flist != '' - let nl_idx = stridx(flist, "\n") - let one_file = strpart(flist, 0, nl_idx) - - " Remove the filename from the list - let flist = strpart(flist, nl_idx + 1) - - if one_file == '' - continue - endif - - " Skip directories - if isdirectory(one_file) - continue - endif - - let ftype = s:Tlist_Detect_Filetype(one_file) - - echon "\r " - echon "\rProcessing tags for " . fnamemodify(one_file, ':p:t') - - let fcnt = fcnt + 1 - - call Tlist_Update_File(one_file, ftype) - endwhile - - " Clear the displayed informational messages - echon "\r " - - " Restore the previous state - let &lazyredraw = old_lazyredraw - - return fcnt -endfunction - -" Tlist_Process_Dir -" Process the files in a directory matching the specified pattern -function! s:Tlist_Process_Dir(dir_name, pat) - let flist = glob(a:dir_name . '/' . a:pat) . "\n" - - let fcnt = s:Tlist_Process_Filelist(flist) - - let len = strlen(a:dir_name) - if a:dir_name[len - 1] == '\' || a:dir_name[len - 1] == '/' - let glob_expr = a:dir_name . '*' - else - let glob_expr = a:dir_name . '/*' - endif - let all_files = glob(glob_expr) . "\n" - - while all_files != '' - let nl_idx = stridx(all_files, "\n") - let one_file = strpart(all_files, 0, nl_idx) - - let all_files = strpart(all_files, nl_idx + 1) - if one_file == '' - continue - endif - - " Skip non-directory names - if !isdirectory(one_file) - continue - endif - - echon "\r " - echon "\rProcessing files in directory " . fnamemodify(one_file, ':t') - let fcnt = fcnt + s:Tlist_Process_Dir(one_file, a:pat) - endwhile - - return fcnt -endfunction - -" Tlist_Add_Files_Recursive -" Add files recursively from a directory -function! s:Tlist_Add_Files_Recursive(dir, ...) - let dir_name = fnamemodify(a:dir, ':p') - if !isdirectory(dir_name) - call s:Tlist_Warning_Msg('Error: ' . dir_name . ' is not a directory') - return - endif - - if a:0 == 1 - " User specified file pattern - let pat = a:1 - else - " Default file pattern - let pat = '*' - endif - - echon "\r " - echon "\rProcessing files in directory " . fnamemodify(dir_name, ':t') - let fcnt = s:Tlist_Process_Dir(dir_name, pat) - - echon "\rAdded " . fcnt . " files to the taglist" -endfunction - -" Tlist_Add_Files -" Add the specified list of files to the taglist -function! s:Tlist_Add_Files(...) - let flist = '' - let i = 1 - - " Get all the files matching the file patterns supplied as argument - while i <= a:0 - let flist = flist . glob(a:{i}) . "\n" - let i = i + 1 - endwhile - - if flist == '' - call s:Tlist_Warning_Msg('Error: No matching files are found') - return - endif - - let fcnt = s:Tlist_Process_Filelist(flist) - echon "\rAdded " . fcnt . " files to the taglist" -endfunction - -" Tlist_Extract_Tagtype -" Extract the tag type from the tag text -function! s:Tlist_Extract_Tagtype(tag_line) - " The tag type is after the tag prototype field. The prototype field - " ends with the /;"\t string. We add 4 at the end to skip the characters - " in this special string.. - let start = strridx(a:tag_line, '/;"' . "\t") + 4 - let end = strridx(a:tag_line, 'line:') - 1 - let ttype = strpart(a:tag_line, start, end - start) - - return ttype -endfunction - -" Tlist_Extract_Tag_Scope -" Extract the tag scope from the tag text -function! s:Tlist_Extract_Tag_Scope(tag_line) - let start = strridx(a:tag_line, 'line:') - let end = strridx(a:tag_line, "\t") - if end <= start - return '' - endif - - let tag_scope = strpart(a:tag_line, end + 1) - let tag_scope = strpart(tag_scope, stridx(tag_scope, ':') + 1) - - return tag_scope -endfunction - -" Tlist_Refresh() -" Refresh the taglist -function! s:Tlist_Refresh() - call s:Tlist_Log_Msg('Tlist_Refresh (Skip_Refresh = ' . - \ s:Tlist_Skip_Refresh . ', ' . bufname('%') . ')') - " If we are entering the buffer from one of the taglist functions, then - " no need to refresh the taglist window again. - if s:Tlist_Skip_Refresh - " We still need to update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif - return - endif - - " If part of the winmanager plugin and not configured to process - " tags always and not configured to display the tags menu, then return - if (s:tlist_app_name == 'winmanager') && !g:Tlist_Process_File_Always - \ && !g:Tlist_Show_Menu - return - endif - - " Skip buffers with 'buftype' set to nofile, nowrite, quickfix or help - if &buftype != '' - return - endif - - let filename = fnamemodify(bufname('%'), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype('%') - - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(filename, ftype) - return - endif - - let tlist_win = bufwinnr(g:TagList_title) - - " If the taglist window is not opened and not configured to process - " tags always and not displaying the tags menu, then return - if tlist_win == -1 && !g:Tlist_Process_File_Always && !g:Tlist_Show_Menu - return - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(filename) - return - endif - - " If the taglist should not be auto updated, then return - if !g:Tlist_Auto_Update - return - endif - endif - - let cur_lnum = line('.') - - if fidx == -1 - " Update the tags for the file - let fidx = s:Tlist_Process_File(filename, ftype) - else - let mtime = getftime(filename) - if s:tlist_{fidx}_mtime != mtime - " Invalidate the tags listed for this file - let s:tlist_{fidx}_valid = 0 - - " Update the taglist and the window - call Tlist_Update_File(filename, ftype) - - " Store the new file modification time - let s:tlist_{fidx}_mtime = mtime - endif - endif - - " Update the taglist window - if tlist_win != -1 - " Disable screen updates - let old_lazyredraw = &lazyredraw - set nolazyredraw - - " Save the current window number - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - if !g:Tlist_Auto_Highlight_Tag || !g:Tlist_Highlight_Tag_On_BufEnter - " Save the cursor position - let save_line = line('.') - let save_col = col('.') - endif - - " Update the taglist window - call s:Tlist_Window_Refresh_File(filename, ftype) - - " Open the fold for the file - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen!" - - if g:Tlist_Highlight_Tag_On_BufEnter && g:Tlist_Auto_Highlight_Tag - if g:Tlist_Show_One_File && s:tlist_cur_file_idx != fidx - " If displaying tags for only one file in the taglist - " window and about to display the tags for a new file, - " then center the current tag line for the new file - let center_tag_line = 1 - else - let center_tag_line = 0 - endif - - " Highlight the current tag - call s:Tlist_Window_Highlight_Tag(filename, cur_lnum, 1, center_tag_line) - else - " Restore the cursor position - if v:version >= 601 - call cursor(save_line, save_col) - else - exe save_line - exe 'normal! ' . save_col . '|' - endif - endif - - " Jump back to the original window - if save_winnr != winnr() - call s:Tlist_Exe_Cmd_No_Acmds(save_winnr . 'wincmd w') - endif - - " Restore screen updates - let &lazyredraw = old_lazyredraw - endif - - " Update the taglist menu - if g:Tlist_Show_Menu - call s:Tlist_Menu_Update_File(0) - endif -endfunction - -" Tlist_Change_Sort() -" Change the sort order of the tag listing -" caller == 'cmd', command used in the taglist window -" caller == 'menu', taglist menu -" action == 'toggle', toggle sort from name to order and vice versa -" action == 'set', set the sort order to sort_type -function! s:Tlist_Change_Sort(caller, action, sort_type) - call s:Tlist_Log_Msg('Tlist_Change_Sort (caller = ' . a:caller . - \ ', action = ' . a:action . ', sort_type = ' . a:sort_type . ')') - if a:caller == 'cmd' - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - " Remove the previous highlighting - match none - elseif a:caller == 'menu' - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx == -1 - return - endif - endif - - if a:action == 'toggle' - let sort_type = s:tlist_{fidx}_sort_type - - " Toggle the sort order from 'name' to 'order' and vice versa - if sort_type == 'name' - let s:tlist_{fidx}_sort_type = 'order' - else - let s:tlist_{fidx}_sort_type = 'name' - endif - else - let s:tlist_{fidx}_sort_type = a:sort_type - endif - - " Invalidate the tags listed for this file - let s:tlist_{fidx}_valid = 0 - - if a:caller == 'cmd' - " Save the current line for later restoration - let curline = '\V\^' . getline('.') . '\$' - - call s:Tlist_Window_Refresh_File(s:tlist_{fidx}_filename, - \ s:tlist_{fidx}_filetype) - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'foldopen!' - - " Go back to the cursor line before the tag list is sorted - call search(curline, 'w') - - call s:Tlist_Menu_Update_File(1) - else - call s:Tlist_Menu_Remove_File() - - call s:Tlist_Refresh() - endif -endfunction - -" Tlist_Update_Current_File() -" Update taglist for the current buffer by regenerating the tag list -" Contributed by WEN Guopeng. -function! s:Tlist_Update_Current_File() - call s:Tlist_Log_Msg('Tlist_Update_Current_File()') - if winnr() == bufwinnr(g:TagList_title) - " In the taglist window. Update the current file - call s:Tlist_Window_Update_File() - else - " Not in the taglist window. Update the current buffer - let filename = fnamemodify(bufname('%'), ':p') - let fidx = s:Tlist_Get_File_Index(filename) - if fidx != -1 - let s:tlist_{fidx}_valid = 0 - endif - let ft = s:Tlist_Get_Buffer_Filetype('%') - call Tlist_Update_File(filename, ft) - endif -endfunction - -" Tlist_Window_Update_File() -" Update the tags displayed in the taglist window -function! s:Tlist_Window_Update_File() - call s:Tlist_Log_Msg('Tlist_Window_Update_File()') - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - " Remove the previous highlighting - match none - - " Save the current line for later restoration - let curline = '\V\^' . getline('.') . '\$' - - let s:tlist_{fidx}_valid = 0 - - " Update the taglist window - call s:Tlist_Window_Refresh_File(s:tlist_{fidx}_filename, - \ s:tlist_{fidx}_filetype) - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'foldopen!' - - " Go back to the tag line before the list is updated - call search(curline, 'w') -endfunction - -" Tlist_Window_Get_Tag_Type_By_Linenum() -" Return the tag type index for the specified line in the taglist window -function! s:Tlist_Window_Get_Tag_Type_By_Linenum(fidx, lnum) - let ftype = s:tlist_{a:fidx}_filetype - - " Determine to which tag type the current line number belongs to using the - " tag type start line number and the number of tags in a tag type - let i = 1 - while i <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{i}_name - let start_lnum = - \ s:tlist_{a:fidx}_start + s:tlist_{a:fidx}_{ttype}_offset - let end = start_lnum + s:tlist_{a:fidx}_{ttype}_count - if a:lnum >= start_lnum && a:lnum <= end - break - endif - let i = i + 1 - endwhile - - " Current line doesn't belong to any of the displayed tag types - if i > s:tlist_{ftype}_count - return '' - endif - - return ttype -endfunction - -" Tlist_Window_Get_Tag_Index() -" Return the tag index for the specified line in the taglist window -function! s:Tlist_Window_Get_Tag_Index(fidx, lnum) - let ttype = s:Tlist_Window_Get_Tag_Type_By_Linenum(a:fidx, a:lnum) - - " Current line doesn't belong to any of the displayed tag types - if ttype == '' - return 0 - endif - - " Compute the index into the displayed tags for the tag type - let ttype_lnum = s:tlist_{a:fidx}_start + s:tlist_{a:fidx}_{ttype}_offset - let tidx = a:lnum - ttype_lnum - if tidx == 0 - return 0 - endif - - " Get the corresponding tag line and return it - return s:tlist_{a:fidx}_{ttype}_{tidx} -endfunction - -" Tlist_Window_Highlight_Line -" Highlight the current line -function! s:Tlist_Window_Highlight_Line() - " Clear previously selected name - match none - - " Highlight the current line - if g:Tlist_Display_Prototype == 0 - let pat = '/\%' . line('.') . 'l\s\+\zs.*/' - else - let pat = '/\%' . line('.') . 'l.*/' - endif - - exe 'match TagListTagName ' . pat -endfunction - -" Tlist_Window_Open_File -" Open the specified file in either a new window or an existing window -" and place the cursor at the specified tag pattern -function! s:Tlist_Window_Open_File(win_ctrl, filename, tagpat) - call s:Tlist_Log_Msg('Tlist_Window_Open_File (' . a:filename . ',' . - \ a:win_ctrl . ')') - let prev_Tlist_Skip_Refresh = s:Tlist_Skip_Refresh - let s:Tlist_Skip_Refresh = 1 - - if s:tlist_app_name == "winmanager" - " Let the winmanager edit the file - call WinManagerFileEdit(a:filename, a:win_ctrl == 'newwin') - else - - if a:win_ctrl == 'newtab' - " Create a new tab - exe 'tabnew ' . escape(a:filename, ' ') - " Open the taglist window in the new tab - call s:Tlist_Window_Open() - endif - - if a:win_ctrl == 'checktab' - " Check whether the file is present in any of the tabs. - " If the file is present in the current tab, then use the - " current tab. - if bufwinnr(a:filename) != -1 - let file_present_in_tab = 1 - let i = tabpagenr() - else - let i = 1 - let bnum = bufnr(a:filename) - let file_present_in_tab = 0 - while i <= tabpagenr('$') - if index(tabpagebuflist(i), bnum) != -1 - let file_present_in_tab = 1 - break - endif - let i += 1 - endwhile - endif - - if file_present_in_tab - " Goto the tab containing the file - exe 'tabnext ' . i - else - " Open a new tab - exe 'tabnew ' . escape(a:filename, ' ') - - " Open the taglist window - call s:Tlist_Window_Open() - endif - endif - - let winnum = -1 - if a:win_ctrl == 'prevwin' - " Open the file in the previous window, if it is usable - let cur_win = winnr() - wincmd p - if &buftype == '' && !&previewwindow - exe "edit " . escape(a:filename, ' ') - let winnum = winnr() - else - " Previous window is not usable - exe cur_win . 'wincmd w' - endif - endif - - " Goto the window containing the file. If the window is not there, open a - " new window - if winnum == -1 - let winnum = bufwinnr(a:filename) - endif - - if winnum == -1 - " Locate the previously used window for opening a file - let fwin_num = 0 - let first_usable_win = 0 - - let i = 1 - let bnum = winbufnr(i) - while bnum != -1 - if getwinvar(i, 'tlist_file_window') == 'yes' - let fwin_num = i - break - endif - if first_usable_win == 0 && - \ getbufvar(bnum, '&buftype') == '' && - \ !getwinvar(i, '&previewwindow') - " First non-taglist, non-plugin and non-preview window - let first_usable_win = i - endif - let i = i + 1 - let bnum = winbufnr(i) - endwhile - - " If a previously used window is not found, then use the first - " non-taglist window - if fwin_num == 0 - let fwin_num = first_usable_win - endif - - if fwin_num != 0 - " Jump to the file window - exe fwin_num . "wincmd w" - - " If the user asked to jump to the tag in a new window, then split - " the existing window into two. - if a:win_ctrl == 'newwin' - split - endif - exe "edit " . escape(a:filename, ' ') - else - " Open a new window - if g:Tlist_Use_Horiz_Window - exe 'leftabove split ' . escape(a:filename, ' ') - else - if winbufnr(2) == -1 - " Only the taglist window is present - if g:Tlist_Use_Right_Window - exe 'leftabove vertical split ' . - \ escape(a:filename, ' ') - else - exe 'rightbelow vertical split ' . - \ escape(a:filename, ' ') - endif - - " Go to the taglist window to change the window size to - " the user configured value - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - if g:Tlist_Use_Horiz_Window - exe 'resize ' . g:Tlist_WinHeight - else - exe 'vertical resize ' . g:Tlist_WinWidth - endif - " Go back to the file window - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - else - " A plugin or help window is also present - wincmd w - exe 'leftabove split ' . escape(a:filename, ' ') - endif - endif - endif - " Mark the window, so that it can be reused. - call s:Tlist_Window_Mark_File_Window() - else - if v:version >= 700 - " If the file is opened in more than one window, then check - " whether the last accessed window has the selected file. - " If it does, then use that window. - let lastwin_bufnum = winbufnr(winnr('#')) - if bufnr(a:filename) == lastwin_bufnum - let winnum = winnr('#') - endif - endif - exe winnum . 'wincmd w' - - " If the user asked to jump to the tag in a new window, then split the - " existing window into two. - if a:win_ctrl == 'newwin' - split - endif - endif - endif - - " Jump to the tag - if a:tagpat != '' - " Add the current cursor position to the jump list, so that user can - " jump back using the ' and ` marks. - mark ' - silent call search(a:tagpat, 'w') - - " Bring the line to the middle of the window - normal! z. - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - .foldopen - endif - endif - - " If the user selects to preview the tag then jump back to the - " taglist window - if a:win_ctrl == 'preview' - " Go back to the taglist window - let winnum = bufwinnr(g:TagList_title) - exe winnum . 'wincmd w' - else - " If the user has selected to close the taglist window, when a - " tag is selected, close the taglist window - if g:Tlist_Close_On_Select - call s:Tlist_Window_Goto_Window() - close - - " Go back to the window displaying the selected file - let wnum = bufwinnr(a:filename) - if wnum != -1 && wnum != winnr() - call s:Tlist_Exe_Cmd_No_Acmds(wnum . 'wincmd w') - endif - endif - endif - - let s:Tlist_Skip_Refresh = prev_Tlist_Skip_Refresh -endfunction - -" Tlist_Window_Jump_To_Tag() -" Jump to the location of the current tag -" win_ctrl == useopen - Reuse the existing file window -" win_ctrl == newwin - Open a new window -" win_ctrl == preview - Preview the tag -" win_ctrl == prevwin - Open in previous window -" win_ctrl == newtab - Open in new tab -function! s:Tlist_Window_Jump_To_Tag(win_ctrl) - call s:Tlist_Log_Msg('Tlist_Window_Jump_To_Tag(' . a:win_ctrl . ')') - " Do not process comment lines and empty lines - let curline = getline('.') - if curline =~ '^\s*$' || curline[0] == '"' - return - endif - - " If inside a closed fold, then use the first line of the fold - " and jump to the file. - let lnum = foldclosed('.') - if lnum == -1 - " Jump to the selected tag or file - let lnum = line('.') - else - " Open the closed fold - .foldopen! - endif - - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - if fidx == -1 - return - endif - - " Get the tag output for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, lnum) - if tidx != 0 - let tagpat = s:Tlist_Get_Tag_SearchPat(fidx, tidx) - - " Highlight the tagline - call s:Tlist_Window_Highlight_Line() - else - " Selected a line which is not a tag name. Just edit the file - let tagpat = '' - endif - - call s:Tlist_Window_Open_File(a:win_ctrl, s:tlist_{fidx}_filename, tagpat) -endfunction - -" Tlist_Window_Show_Info() -" Display information about the entry under the cursor -function! s:Tlist_Window_Show_Info() - call s:Tlist_Log_Msg('Tlist_Window_Show_Info()') - - " Clear the previously displayed line - echo - - " Do not process comment lines and empty lines - let curline = getline('.') - if curline =~ '^\s*$' || curline[0] == '"' - return - endif - - " If inside a fold, then don't display the prototype - if foldclosed('.') != -1 - return - endif - - let lnum = line('.') - - " Get the file index - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(lnum) - if fidx == -1 - return - endif - - if lnum == s:tlist_{fidx}_start - " Cursor is on a file name - let fname = s:tlist_{fidx}_filename - if strlen(fname) > 50 - let fname = fnamemodify(fname, ':t') - endif - echo fname . ', Filetype=' . s:tlist_{fidx}_filetype . - \ ', Tag count=' . s:tlist_{fidx}_tag_count - return - endif - - " Get the tag output line for the current tag - let tidx = s:Tlist_Window_Get_Tag_Index(fidx, lnum) - if tidx == 0 - " Cursor is on a tag type - let ttype = s:Tlist_Window_Get_Tag_Type_By_Linenum(fidx, lnum) - if ttype == '' - return - endif - - let ttype_name = '' - - let ftype = s:tlist_{fidx}_filetype - let i = 1 - while i <= s:tlist_{ftype}_count - if ttype == s:tlist_{ftype}_{i}_name - let ttype_name = s:tlist_{ftype}_{i}_fullname - break - endif - let i = i + 1 - endwhile - - echo 'Tag type=' . ttype_name . - \ ', Tag count=' . s:tlist_{fidx}_{ttype}_count - return - endif - - " Get the tag search pattern and display it - echo s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Find_Nearest_Tag_Idx -" Find the tag idx nearest to the supplied line number -" Returns -1, if a tag couldn't be found for the specified line number -function! s:Tlist_Find_Nearest_Tag_Idx(fidx, linenum) - let sort_type = s:tlist_{a:fidx}_sort_type - - let left = 1 - let right = s:tlist_{a:fidx}_tag_count - - if sort_type == 'order' - " Tags sorted by order, use a binary search. - " The idea behind this function is taken from the ctags.vim script (by - " Alexey Marinichev) available at the Vim online website. - - " If the current line is the less than the first tag, then no need to - " search - let first_lnum = s:Tlist_Get_Tag_Linenum(a:fidx, 1) - - if a:linenum < first_lnum - return -1 - endif - - while left < right - let middle = (right + left + 1) / 2 - let middle_lnum = s:Tlist_Get_Tag_Linenum(a:fidx, middle) - - if middle_lnum == a:linenum - let left = middle - break - endif - - if middle_lnum > a:linenum - let right = middle - 1 - else - let left = middle - endif - endwhile - else - " Tags sorted by name, use a linear search. (contributed by Dave - " Eggum). - " Look for a tag with a line number less than or equal to the supplied - " line number. If multiple tags are found, then use the tag with the - " line number closest to the supplied line number. IOW, use the tag - " with the highest line number. - let closest_lnum = 0 - let final_left = 0 - while left <= right - let lnum = s:Tlist_Get_Tag_Linenum(a:fidx, left) - - if lnum < a:linenum && lnum > closest_lnum - let closest_lnum = lnum - let final_left = left - elseif lnum == a:linenum - let closest_lnum = lnum - let final_left = left - break - else - let left = left + 1 - endif - endwhile - if closest_lnum == 0 - return -1 - endif - if left >= right - let left = final_left - endif - endif - - return left -endfunction - -" Tlist_Window_Highlight_Tag() -" Highlight the current tag -" cntx == 1, Called by the taglist plugin itself -" cntx == 2, Forced by the user through the TlistHighlightTag command -" center = 1, move the tag line to the center of the taglist window -function! s:Tlist_Window_Highlight_Tag(filename, cur_lnum, cntx, center) - " Highlight the current tag only if the user configured the - " taglist plugin to do so or if the user explictly invoked the - " command to highlight the current tag. - if !g:Tlist_Auto_Highlight_Tag && a:cntx == 1 - return - endif - - if a:filename == '' - return - endif - - " Make sure the taglist window is present - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Error: Taglist window is not open') - return - endif - - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - return - endif - - " If the file is currently not displayed in the taglist window, then retrn - if !s:tlist_{fidx}_visible - return - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return - endif - - " Ignore all autocommands - let old_ei = &eventignore - set eventignore=all - - " Save the original window number - let org_winnr = winnr() - - if org_winnr == winnum - let in_taglist_window = 1 - else - let in_taglist_window = 0 - endif - - " Go to the taglist window - if !in_taglist_window - exe winnum . 'wincmd w' - endif - - " Clear previously selected name - match none - - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, a:cur_lnum) - if tidx == -1 - " Make sure the current tag line is visible in the taglist window. - " Calling the winline() function makes the line visible. Don't know - " of a better way to achieve this. - let lnum = line('.') - - if lnum < s:tlist_{fidx}_start || lnum > s:tlist_{fidx}_end - " Move the cursor to the beginning of the file - exe s:tlist_{fidx}_start - endif - - if foldclosed('.') != -1 - .foldopen - endif - - call winline() - - if !in_taglist_window - exe org_winnr . 'wincmd w' - endif - - " Restore the autocommands - let &eventignore = old_ei - return - endif - - " Extract the tag type - let ttype = s:Tlist_Get_Tag_Type_By_Tag(fidx, tidx) - - " Compute the line number - " Start of file + Start of tag type + offset - let lnum = s:tlist_{fidx}_start + s:tlist_{fidx}_{ttype}_offset + - \ s:tlist_{fidx}_{tidx}_ttype_idx - - " Goto the line containing the tag - exe lnum - - " Open the fold - if foldclosed('.') != -1 - .foldopen - endif - - if a:center - " Move the tag line to the center of the taglist window - normal! z. - else - " Make sure the current tag line is visible in the taglist window. - " Calling the winline() function makes the line visible. Don't know - " of a better way to achieve this. - call winline() - endif - - " Highlight the tag name - call s:Tlist_Window_Highlight_Line() - - " Go back to the original window - if !in_taglist_window - exe org_winnr . 'wincmd w' - endif - - " Restore the autocommands - let &eventignore = old_ei - return -endfunction - -" Tlist_Get_Tag_Prototype_By_Line -" Get the prototype for the tag on or before the specified line number in the -" current buffer -function! Tlist_Get_Tag_Prototype_By_Line(...) - if a:0 == 0 - " Arguments are not supplied. Use the current buffer name - " and line number - let filename = bufname('%') - let linenr = line('.') - elseif a:0 == 2 - " Filename and line number are specified - let filename = a:1 - let linenr = a:2 - if linenr !~ '\d\+' - " Invalid line number - return "" - endif - else - " Sufficient arguments are not supplied - let msg = 'Usage: Tlist_Get_Tag_Prototype_By_Line <filename> ' . - \ '<line_number>' - call s:Tlist_Warning_Msg(msg) - return "" - endif - - " Expand the file to a fully qualified name - let filename = fnamemodify(filename, ':p') - if filename == '' - return "" - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - return "" - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return "" - endif - - " Get the tag text using the line number - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, linenr) - if tidx == -1 - return "" - endif - - return s:Tlist_Get_Tag_Prototype(fidx, tidx) -endfunction - -" Tlist_Get_Tagname_By_Line -" Get the tag name on or before the specified line number in the -" current buffer -function! Tlist_Get_Tagname_By_Line(...) - if a:0 == 0 - " Arguments are not supplied. Use the current buffer name - " and line number - let filename = bufname('%') - let linenr = line('.') - elseif a:0 == 2 - " Filename and line number are specified - let filename = a:1 - let linenr = a:2 - if linenr !~ '\d\+' - " Invalid line number - return "" - endif - else - " Sufficient arguments are not supplied - let msg = 'Usage: Tlist_Get_Tagname_By_Line <filename> <line_number>' - call s:Tlist_Warning_Msg(msg) - return "" - endif - - " Make sure the current file has a name - let filename = fnamemodify(filename, ':p') - if filename == '' - return "" - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 - return "" - endif - - " If there are no tags for this file, then no need to proceed further - if s:tlist_{fidx}_tag_count == 0 - return "" - endif - - " Get the tag name using the line number - let tidx = s:Tlist_Find_Nearest_Tag_Idx(fidx, linenr) - if tidx == -1 - return "" - endif - - return s:tlist_{fidx}_{tidx}_tag_name -endfunction - -" Tlist_Window_Move_To_File -" Move the cursor to the beginning of the current file or the next file -" or the previous file in the taglist window -" dir == -1, move to start of current or previous function -" dir == 1, move to start of next function -function! s:Tlist_Window_Move_To_File(dir) - if foldlevel('.') == 0 - " Cursor is on a non-folded line (it is not in any of the files) - " Move it to a folded line - if a:dir == -1 - normal! zk - else - " While moving down to the start of the next fold, - " no need to do go to the start of the next file. - normal! zj - return - endif - endif - - let fidx = s:Tlist_Window_Get_File_Index_By_Linenum(line('.')) - if fidx == -1 - return - endif - - let cur_lnum = line('.') - - if a:dir == -1 - if cur_lnum > s:tlist_{fidx}_start - " Move to the beginning of the current file - exe s:tlist_{fidx}_start - return - endif - - if fidx != 0 - " Move to the beginning of the previous file - let fidx = fidx - 1 - else - " Cursor is at the first file, wrap around to the last file - let fidx = s:tlist_file_count - 1 - endif - - exe s:tlist_{fidx}_start - return - else - " Move to the beginning of the next file - let fidx = fidx + 1 - - if fidx >= s:tlist_file_count - " Cursor is at the last file, wrap around to the first file - let fidx = 0 - endif - - if s:tlist_{fidx}_start != 0 - exe s:tlist_{fidx}_start - endif - return - endif -endfunction - -" Tlist_Session_Load -" Load a taglist session (information about all the displayed files -" and the tags) from the specified file -function! s:Tlist_Session_Load(...) - if a:0 == 0 || a:1 == '' - call s:Tlist_Warning_Msg('Usage: TlistSessionLoad <filename>') - return - endif - - let sessionfile = a:1 - - if !filereadable(sessionfile) - let msg = 'Taglist: Error - Unable to open file ' . sessionfile - call s:Tlist_Warning_Msg(msg) - return - endif - - " Mark the current window as the file window - call s:Tlist_Window_Mark_File_Window() - - " Source the session file - exe 'source ' . sessionfile - - let new_file_count = g:tlist_file_count - unlet! g:tlist_file_count - - let i = 0 - while i < new_file_count - let ftype = g:tlist_{i}_filetype - unlet! g:tlist_{i}_filetype - - if !exists('s:tlist_' . ftype . '_count') - if s:Tlist_FileType_Init(ftype) == 0 - let i = i + 1 - continue - endif - endif - - let fname = g:tlist_{i}_filename - unlet! g:tlist_{i}_filename - - let fidx = s:Tlist_Get_File_Index(fname) - if fidx != -1 - let s:tlist_{fidx}_visible = 0 - let i = i + 1 - continue - else - " As we are loading the tags from the session file, if this - " file was previously deleted by the user, now we need to - " add it back. So remove the file from the deleted list. - call s:Tlist_Update_Remove_List(fname, 0) - endif - - let fidx = s:Tlist_Init_File(fname, ftype) - - let s:tlist_{fidx}_filename = fname - - let s:tlist_{fidx}_sort_type = g:tlist_{i}_sort_type - unlet! g:tlist_{i}_sort_type - - let s:tlist_{fidx}_filetype = ftype - let s:tlist_{fidx}_mtime = getftime(fname) - - let s:tlist_{fidx}_start = 0 - let s:tlist_{fidx}_end = 0 - - let s:tlist_{fidx}_valid = 1 - - let s:tlist_{fidx}_tag_count = g:tlist_{i}_tag_count - unlet! g:tlist_{i}_tag_count - - let j = 1 - while j <= s:tlist_{fidx}_tag_count - let s:tlist_{fidx}_{j}_tag = g:tlist_{i}_{j}_tag - let s:tlist_{fidx}_{j}_tag_name = g:tlist_{i}_{j}_tag_name - let s:tlist_{fidx}_{j}_ttype_idx = g:tlist_{i}_{j}_ttype_idx - unlet! g:tlist_{i}_{j}_tag - unlet! g:tlist_{i}_{j}_tag_name - unlet! g:tlist_{i}_{j}_ttype_idx - let j = j + 1 - endwhile - - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - - if exists('g:tlist_' . i . '_' . ttype) - let s:tlist_{fidx}_{ttype} = g:tlist_{i}_{ttype} - unlet! g:tlist_{i}_{ttype} - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = g:tlist_{i}_{ttype}_count - unlet! g:tlist_{i}_{ttype}_count - - let k = 1 - while k <= s:tlist_{fidx}_{ttype}_count - let s:tlist_{fidx}_{ttype}_{k} = g:tlist_{i}_{ttype}_{k} - unlet! g:tlist_{i}_{ttype}_{k} - let k = k + 1 - endwhile - else - let s:tlist_{fidx}_{ttype} = '' - let s:tlist_{fidx}_{ttype}_offset = 0 - let s:tlist_{fidx}_{ttype}_count = 0 - endif - - let j = j + 1 - endwhile - - let i = i + 1 - endwhile - - " If the taglist window is open, then update it - let winnum = bufwinnr(g:TagList_title) - if winnum != -1 - let save_winnr = winnr() - - " Goto the taglist window - call s:Tlist_Window_Goto_Window() - - " Refresh the taglist window - call s:Tlist_Window_Refresh() - - " Go back to the original window - if save_winnr != winnr() - call s:Tlist_Exe_Cmd_No_Acmds('wincmd p') - endif - endif -endfunction - -" Tlist_Session_Save -" Save a taglist session (information about all the displayed files -" and the tags) into the specified file -function! s:Tlist_Session_Save(...) - if a:0 == 0 || a:1 == '' - call s:Tlist_Warning_Msg('Usage: TlistSessionSave <filename>') - return - endif - - let sessionfile = a:1 - - if s:tlist_file_count == 0 - " There is nothing to save - call s:Tlist_Warning_Msg('Warning: Taglist is empty. Nothing to save.') - return - endif - - if filereadable(sessionfile) - let ans = input('Do you want to overwrite ' . sessionfile . ' (Y/N)?') - if ans !=? 'y' - return - endif - - echo "\n" - endif - - let old_verbose = &verbose - set verbose&vim - - exe 'redir! > ' . sessionfile - - silent! echo '" Taglist session file. This file is auto-generated.' - silent! echo '" File information' - silent! echo 'let tlist_file_count = ' . s:tlist_file_count - - let i = 0 - - while i < s:tlist_file_count - " Store information about the file - silent! echo 'let tlist_' . i . "_filename = '" . - \ s:tlist_{i}_filename . "'" - silent! echo 'let tlist_' . i . '_sort_type = "' . - \ s:tlist_{i}_sort_type . '"' - silent! echo 'let tlist_' . i . '_filetype = "' . - \ s:tlist_{i}_filetype . '"' - silent! echo 'let tlist_' . i . '_tag_count = ' . - \ s:tlist_{i}_tag_count - " Store information about all the tags - let j = 1 - while j <= s:tlist_{i}_tag_count - let txt = escape(s:tlist_{i}_{j}_tag, '"\\') - silent! echo 'let tlist_' . i . '_' . j . '_tag = "' . txt . '"' - silent! echo 'let tlist_' . i . '_' . j . '_tag_name = "' . - \ s:tlist_{i}_{j}_tag_name . '"' - silent! echo 'let tlist_' . i . '_' . j . '_ttype_idx' . ' = ' . - \ s:tlist_{i}_{j}_ttype_idx - let j = j + 1 - endwhile - - " Store information about all the tags grouped by their type - let ftype = s:tlist_{i}_filetype - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - if s:tlist_{i}_{ttype}_count != 0 - let txt = escape(s:tlist_{i}_{ttype}, '"\') - let txt = substitute(txt, "\n", "\\\\n", 'g') - silent! echo 'let tlist_' . i . '_' . ttype . ' = "' . - \ txt . '"' - silent! echo 'let tlist_' . i . '_' . ttype . '_count = ' . - \ s:tlist_{i}_{ttype}_count - let k = 1 - while k <= s:tlist_{i}_{ttype}_count - silent! echo 'let tlist_' . i . '_' . ttype . '_' . k . - \ ' = ' . s:tlist_{i}_{ttype}_{k} - let k = k + 1 - endwhile - endif - let j = j + 1 - endwhile - - silent! echo - - let i = i + 1 - endwhile - - redir END - - let &verbose = old_verbose -endfunction - -" Tlist_Buffer_Removed -" A buffer is removed from the Vim buffer list. Remove the tags defined -" for that file -function! s:Tlist_Buffer_Removed(filename) - call s:Tlist_Log_Msg('Tlist_Buffer_Removed (' . a:filename . ')') - - " Make sure a valid filename is supplied - if a:filename == '' - return - endif - - " Get tag list index of the specified file - let fidx = s:Tlist_Get_File_Index(a:filename) - if fidx == -1 - " File not present in the taglist - return - endif - - " Remove the file from the list - call s:Tlist_Remove_File(fidx, 0) -endfunction - -" When a buffer is deleted, remove the file from the taglist -autocmd BufDelete * silent call s:Tlist_Buffer_Removed(expand('<afile>:p')) - -" Tlist_Window_Open_File_Fold -" Open the fold for the specified file and close the fold for all the -" other files -function! s:Tlist_Window_Open_File_Fold(acmd_bufnr) - call s:Tlist_Log_Msg('Tlist_Window_Open_File_Fold (' . a:acmd_bufnr . ')') - - " Make sure the taglist window is present - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - call s:Tlist_Warning_Msg('Taglist: Error - Taglist window is not open') - return - endif - - " Save the original window number - let org_winnr = winnr() - if org_winnr == winnum - let in_taglist_window = 1 - else - let in_taglist_window = 0 - endif - - if in_taglist_window - " When entering the taglist window, no need to update the folds - return - endif - - " Go to the taglist window - if !in_taglist_window - call s:Tlist_Exe_Cmd_No_Acmds(winnum . 'wincmd w') - endif - - " Close all the folds - silent! %foldclose - - " Get tag list index of the specified file - let fname = fnamemodify(bufname(a:acmd_bufnr + 0), ':p') - if filereadable(fname) - let fidx = s:Tlist_Get_File_Index(fname) - if fidx != -1 - " Open the fold for the file - exe "silent! " . s:tlist_{fidx}_start . "," . - \ s:tlist_{fidx}_end . "foldopen" - endif - endif - - " Go back to the original window - if !in_taglist_window - call s:Tlist_Exe_Cmd_No_Acmds(org_winnr . 'wincmd w') - endif -endfunction - -" Tlist_Window_Check_Auto_Open -" Open the taglist window automatically on Vim startup. -" Open the window only when files present in any of the Vim windows support -" tags. -function! s:Tlist_Window_Check_Auto_Open() - let open_window = 0 - - let i = 1 - let buf_num = winbufnr(i) - while buf_num != -1 - let filename = fnamemodify(bufname(buf_num), ':p') - let ft = s:Tlist_Get_Buffer_Filetype(buf_num) - if !s:Tlist_Skip_File(filename, ft) - let open_window = 1 - break - endif - let i = i + 1 - let buf_num = winbufnr(i) - endwhile - - if open_window - call s:Tlist_Window_Toggle() - endif -endfunction - -" Tlist_Refresh_Folds -" Remove and create the folds for all the files displayed in the taglist -" window. Used after entering a tab. If this is not done, then the folds -" are not properly created for taglist windows displayed in multiple tabs. -function! s:Tlist_Refresh_Folds() - let winnum = bufwinnr(g:TagList_title) - if winnum == -1 - return - endif - - let save_wnum = winnr() - exe winnum . 'wincmd w' - - " First remove all the existing folds - normal! zE - - " Create the folds for each in the tag list - let fidx = 0 - while fidx < s:tlist_file_count - let ftype = s:tlist_{fidx}_filetype - - " Create the folds for each tag type in a file - let j = 1 - while j <= s:tlist_{ftype}_count - let ttype = s:tlist_{ftype}_{j}_name - if s:tlist_{fidx}_{ttype}_count - let s = s:tlist_{fidx}_start + s:tlist_{fidx}_{ttype}_offset - let e = s + s:tlist_{fidx}_{ttype}_count - exe s . ',' . e . 'fold' - endif - let j = j + 1 - endwhile - - exe s:tlist_{fidx}_start . ',' . s:tlist_{fidx}_end . 'fold' - exe 'silent! ' . s:tlist_{fidx}_start . ',' . - \ s:tlist_{fidx}_end . 'foldopen!' - let fidx = fidx + 1 - endwhile - - exe save_wnum . 'wincmd w' -endfunction - -function! s:Tlist_Menu_Add_Base_Menu() - call s:Tlist_Log_Msg('Adding the base menu') - - " Add the menu - anoremenu <silent> T&ags.Refresh\ menu :call <SID>Tlist_Menu_Refresh()<CR> - anoremenu <silent> T&ags.Sort\ menu\ by.Name - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'name')<CR> - anoremenu <silent> T&ags.Sort\ menu\ by.Order - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'order')<CR> - anoremenu T&ags.-SEP1- : - - if &mousemodel =~ 'popup' - anoremenu <silent> PopUp.T&ags.Refresh\ menu - \ :call <SID>Tlist_Menu_Refresh()<CR> - anoremenu <silent> PopUp.T&ags.Sort\ menu\ by.Name - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'name')<CR> - anoremenu <silent> PopUp.T&ags.Sort\ menu\ by.Order - \ :call <SID>Tlist_Change_Sort('menu', 'set', 'order')<CR> - anoremenu PopUp.T&ags.-SEP1- : - endif -endfunction - -let s:menu_char_prefix = - \ '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' - -" Tlist_Menu_Get_Tag_Type_Cmd -" Get the menu command for the specified tag type -" fidx - File type index -" ftype - File Type -" add_ttype_name - To add or not to add the tag type name to the menu entries -" ttype_idx - Tag type index -function! s:Tlist_Menu_Get_Tag_Type_Cmd(fidx, ftype, add_ttype_name, ttype_idx) - " Curly brace variable name optimization - let ftype_ttype_idx = a:ftype . '_' . a:ttype_idx - - let ttype = s:tlist_{ftype_ttype_idx}_name - if a:add_ttype_name - " If the tag type name contains space characters, escape it. This - " will be used to create the menu entries. - let ttype_fullname = escape(s:tlist_{ftype_ttype_idx}_fullname, ' ') - endif - - " Curly brace variable name optimization - let fidx_ttype = a:fidx . '_' . ttype - - " Number of tag entries for this tag type - let tcnt = s:tlist_{fidx_ttype}_count - if tcnt == 0 " No entries for this tag type - return '' - endif - - let mcmd = '' - - " Create the menu items for the tags. - " Depending on the number of tags of this type, split the menu into - " multiple sub-menus, if needed. - if tcnt > g:Tlist_Max_Submenu_Items - let j = 1 - while j <= tcnt - let final_index = j + g:Tlist_Max_Submenu_Items - 1 - if final_index > tcnt - let final_index = tcnt - endif - - " Extract the first and last tag name and form the - " sub-menu name - let tidx = s:tlist_{fidx_ttype}_{j} - let first_tag = s:tlist_{a:fidx}_{tidx}_tag_name - - let tidx = s:tlist_{fidx_ttype}_{final_index} - let last_tag = s:tlist_{a:fidx}_{tidx}_tag_name - - " Truncate the names, if they are greater than the - " max length - let first_tag = strpart(first_tag, 0, g:Tlist_Max_Tag_Length) - let last_tag = strpart(last_tag, 0, g:Tlist_Max_Tag_Length) - - " Form the menu command prefix - let m_prefix = 'anoremenu <silent> T\&ags.' - if a:add_ttype_name - let m_prefix = m_prefix . ttype_fullname . '.' - endif - let m_prefix = m_prefix . first_tag . '\.\.\.' . last_tag . '.' - - " Character prefix used to number the menu items (hotkey) - let m_prefix_idx = 0 - - while j <= final_index - let tidx = s:tlist_{fidx_ttype}_{j} - - let tname = s:tlist_{a:fidx}_{tidx}_tag_name - - let mcmd = mcmd . m_prefix . '\&' . - \ s:menu_char_prefix[m_prefix_idx] . '\.' . - \ tname . ' :call <SID>Tlist_Menu_Jump_To_Tag(' . - \ tidx . ')<CR>|' - - let m_prefix_idx = m_prefix_idx + 1 - let j = j + 1 - endwhile - endwhile - else - " Character prefix used to number the menu items (hotkey) - let m_prefix_idx = 0 - - let m_prefix = 'anoremenu <silent> T\&ags.' - if a:add_ttype_name - let m_prefix = m_prefix . ttype_fullname . '.' - endif - let j = 1 - while j <= tcnt - let tidx = s:tlist_{fidx_ttype}_{j} - - let tname = s:tlist_{a:fidx}_{tidx}_tag_name - - let mcmd = mcmd . m_prefix . '\&' . - \ s:menu_char_prefix[m_prefix_idx] . '\.' . - \ tname . ' :call <SID>Tlist_Menu_Jump_To_Tag(' . tidx - \ . ')<CR>|' - - let m_prefix_idx = m_prefix_idx + 1 - let j = j + 1 - endwhile - endif - - return mcmd -endfunction - -" Update the taglist menu with the tags for the specified file -function! s:Tlist_Menu_File_Refresh(fidx) - call s:Tlist_Log_Msg('Refreshing the tag menu for ' . s:tlist_{a:fidx}_filename) - " The 'B' flag is needed in the 'cpoptions' option - let old_cpoptions = &cpoptions - set cpoptions&vim - - exe s:tlist_{a:fidx}_menu_cmd - - " Update the popup menu (if enabled) - if &mousemodel =~ 'popup' - let cmd = substitute(s:tlist_{a:fidx}_menu_cmd, ' T\\&ags\.', - \ ' PopUp.T\\\&ags.', "g") - exe cmd - endif - - " The taglist menu is not empty now - let s:tlist_menu_empty = 0 - - " Restore the 'cpoptions' settings - let &cpoptions = old_cpoptions -endfunction - -" Tlist_Menu_Update_File -" Add the taglist menu -function! s:Tlist_Menu_Update_File(clear_menu) - if !has('gui_running') - " Not running in GUI mode - return - endif - - call s:Tlist_Log_Msg('Updating the tag menu, clear_menu = ' . a:clear_menu) - - " Remove the tags menu - if a:clear_menu - call s:Tlist_Menu_Remove_File() - - endif - - " Skip buffers with 'buftype' set to nofile, nowrite, quickfix or help - if &buftype != '' - return - endif - - let filename = fnamemodify(bufname('%'), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype('%') - - " If the file doesn't support tag listing, skip it - if s:Tlist_Skip_File(filename, ftype) - return - endif - - let fidx = s:Tlist_Get_File_Index(filename) - if fidx == -1 || !s:tlist_{fidx}_valid - " Check whether this file is removed based on user request - " If it is, then don't display the tags for this file - if s:Tlist_User_Removed_File(filename) - return - endif - - " Process the tags for the file - let fidx = s:Tlist_Process_File(filename, ftype) - if fidx == -1 - return - endif - endif - - let fname = escape(fnamemodify(bufname('%'), ':t'), '.') - if fname != '' - exe 'anoremenu T&ags.' . fname . ' <Nop>' - anoremenu T&ags.-SEP2- : - endif - - if !s:tlist_{fidx}_tag_count - return - endif - - if s:tlist_{fidx}_menu_cmd != '' - " Update the menu with the cached command - call s:Tlist_Menu_File_Refresh(fidx) - - return - endif - - " We are going to add entries to the tags menu, so the menu won't be - " empty - let s:tlist_menu_empty = 0 - - let cmd = '' - - " Determine whether the tag type name needs to be added to the menu - " If more than one tag type is present in the taglisting for a file, - " then the tag type name needs to be present - let add_ttype_name = -1 - let i = 1 - while i <= s:tlist_{ftype}_count && add_ttype_name < 1 - let ttype = s:tlist_{ftype}_{i}_name - if s:tlist_{fidx}_{ttype}_count - let add_ttype_name = add_ttype_name + 1 - endif - let i = i + 1 - endwhile - - " Process the tags by the tag type and get the menu command - let i = 1 - while i <= s:tlist_{ftype}_count - let mcmd = s:Tlist_Menu_Get_Tag_Type_Cmd(fidx, ftype, add_ttype_name, i) - if mcmd != '' - let cmd = cmd . mcmd - endif - - let i = i + 1 - endwhile - - " Cache the menu command for reuse - let s:tlist_{fidx}_menu_cmd = cmd - - " Update the menu - call s:Tlist_Menu_File_Refresh(fidx) -endfunction - -" Tlist_Menu_Remove_File -" Remove the tags displayed in the tags menu -function! s:Tlist_Menu_Remove_File() - if !has('gui_running') || s:tlist_menu_empty - return - endif - - call s:Tlist_Log_Msg('Removing the tags menu for a file') - - " Cleanup the Tags menu - silent! unmenu T&ags - if &mousemodel =~ 'popup' - silent! unmenu PopUp.T&ags - endif - - " Add a dummy menu item to retain teared off menu - noremenu T&ags.Dummy l - - silent! unmenu! T&ags - if &mousemodel =~ 'popup' - silent! unmenu! PopUp.T&ags - endif - - call s:Tlist_Menu_Add_Base_Menu() - - " Remove the dummy menu item - unmenu T&ags.Dummy - - let s:tlist_menu_empty = 1 -endfunction - -" Tlist_Menu_Refresh -" Refresh the taglist menu -function! s:Tlist_Menu_Refresh() - call s:Tlist_Log_Msg('Refreshing the tags menu') - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx != -1 - " Invalidate the cached menu command - let s:tlist_{fidx}_menu_cmd = '' - endif - - " Update the taglist, menu and window - call s:Tlist_Update_Current_File() -endfunction - -" Tlist_Menu_Jump_To_Tag -" Jump to the selected tag -function! s:Tlist_Menu_Jump_To_Tag(tidx) - let fidx = s:Tlist_Get_File_Index(fnamemodify(bufname('%'), ':p')) - if fidx == -1 - return - endif - - let tagpat = s:Tlist_Get_Tag_SearchPat(fidx, a:tidx) - if tagpat == '' - return - endif - - " Add the current cursor position to the jump list, so that user can - " jump back using the ' and ` marks. - mark ' - - silent call search(tagpat, 'w') - - " Bring the line to the middle of the window - normal! z. - - " If the line is inside a fold, open the fold - if foldclosed('.') != -1 - .foldopen - endif -endfunction - -" Tlist_Menu_Init -" Initialize the taglist menu -function! s:Tlist_Menu_Init() - call s:Tlist_Menu_Add_Base_Menu() - - " Automatically add the tags defined in the current file to the menu - augroup TagListMenuCmds - autocmd! - - if !g:Tlist_Process_File_Always - autocmd BufEnter * call s:Tlist_Refresh() - endif - autocmd BufLeave * call s:Tlist_Menu_Remove_File() - augroup end - - call s:Tlist_Menu_Update_File(0) -endfunction - -" Tlist_Vim_Session_Load -" Initialize the taglist window/buffer, which is created when loading -" a Vim session file. -function! s:Tlist_Vim_Session_Load() - call s:Tlist_Log_Msg('Tlist_Vim_Session_Load') - - " Initialize the taglist window - call s:Tlist_Window_Init() - - " Refresh the taglist window - call s:Tlist_Window_Refresh() -endfunction - -" Tlist_Set_App -" Set the name of the external plugin/application to which taglist -" belongs. -" Taglist plugin is part of another plugin like cream or winmanager. -function! Tlist_Set_App(name) - if a:name == "" - return - endif - - let s:tlist_app_name = a:name -endfunction - -" Winmanager integration - -" Initialization required for integration with winmanager -function! TagList_Start() - " If current buffer is not taglist buffer, then don't proceed - if bufname('%') != '__Tag_List__' - return - endif - - call Tlist_Set_App('winmanager') - - " Get the current filename from the winmanager plugin - let bufnum = WinManagerGetLastEditedFile() - if bufnum != -1 - let filename = fnamemodify(bufname(bufnum), ':p') - let ftype = s:Tlist_Get_Buffer_Filetype(bufnum) - endif - - " Initialize the taglist window, if it is not already initialized - if !exists('s:tlist_window_initialized') || !s:tlist_window_initialized - call s:Tlist_Window_Init() - call s:Tlist_Window_Refresh() - let s:tlist_window_initialized = 1 - endif - - " Update the taglist window - if bufnum != -1 - if !s:Tlist_Skip_File(filename, ftype) && g:Tlist_Auto_Update - call s:Tlist_Window_Refresh_File(filename, ftype) - endif - endif -endfunction - -function! TagList_IsValid() - return 0 -endfunction - -function! TagList_WrapUp() - return 0 -endfunction - -" restore 'cpo' -let &cpo = s:cpo_save -unlet s:cpo_save - diff --git a/vim/plugin/unimpaired.vim b/vim/plugin/unimpaired.vim deleted file mode 100644 index 60b6c02..0000000 --- a/vim/plugin/unimpaired.vim +++ /dev/null @@ -1,315 +0,0 @@ -" unimpaired.vim - Pairs of handy bracket mappings -" Maintainer: Tim Pope <http://tpo.pe/> -" Version: 1.1 -" GetLatestVimScripts: 1590 1 :AutoInstall: unimpaired.vim - -if exists("g:loaded_unimpaired") || &cp || v:version < 700 - finish -endif -let g:loaded_unimpaired = 1 - -" Next and previous {{{1 - -function! s:MapNextFamily(map,cmd) - let map = '<Plug>unimpaired'.toupper(a:map) - let end = ' ".(v:count ? v:count : "")<CR>' - execute 'nmap <silent> '.map.'Previous :<C-U>exe "'.a:cmd.'previous'.end - execute 'nmap <silent> '.map.'Next :<C-U>exe "'.a:cmd.'next'.end - execute 'nmap <silent> '.map.'First :<C-U>exe "'.a:cmd.'first'.end - execute 'nmap <silent> '.map.'Last :<C-U>exe "'.a:cmd.'last'.end - execute 'nmap <silent> ['. a:map .' '.map.'Previous' - execute 'nmap <silent> ]'. a:map .' '.map.'Next' - execute 'nmap <silent> ['.toupper(a:map).' '.map.'First' - execute 'nmap <silent> ]'.toupper(a:map).' '.map.'Last' -endfunction - -call s:MapNextFamily('a','') -call s:MapNextFamily('b','b') -call s:MapNextFamily('l','l') -call s:MapNextFamily('q','c') -call s:MapNextFamily('t','t') - -function! s:entries(path) - let path = substitute(a:path,'[\\/]$','','') - let files = split(glob(path."/.*"),"\n") - let files += split(glob(path."/*"),"\n") - call map(files,'substitute(v:val,"[\\/]$","","")') - call filter(files,'v:val !~# "[\\\\/]\\.\\.\\=$"') - call filter(files,'v:val[-4:-1] !=# ".swp" && v:val[-1:-1] !=# "~"') - return files -endfunction - -function! s:FileByOffset(num) - let file = expand('%:p') - let num = a:num - while num - let files = s:entries(fnamemodify(file,':h')) - if a:num < 0 - call reverse(sort(filter(files,'v:val < file'))) - else - call sort(filter(files,'v:val > file')) - endif - let temp = get(files,0,'') - if temp == '' - let file = fnamemodify(file,':h') - else - let file = temp - while isdirectory(file) - let files = s:entries(file) - if files == [] - " TODO: walk back up the tree and continue - break - endif - let file = files[num > 0 ? 0 : -1] - endwhile - let num += num > 0 ? -1 : 1 - endif - endwhile - return file -endfunction - -nnoremap <silent> <Plug>unimpairedONext :<C-U>edit `=<SID>FileByOffset(v:count1)`<CR> -nnoremap <silent> <Plug>unimpairedOPrevious :<C-U>edit `=<SID>FileByOffset(-v:count1)`<CR> - -nmap ]o <Plug>unimpairedONext -nmap [o <Plug>unimpairedOPrevious - -nmap [, :call search('^[<=>]\{7\}','bW')<CR> -nmap ], :call search('^[<=>]\{7\}','W')<CR> -omap [, V:call search('^[<=>]\{7\}','bW')<CR> -omap ], V:call search('^[<=>]\{7\}','W')<CR> -xmap [, :<C-U>exe 'norm! gv'<Bar>call search('^[<=>]\{7\}','bW')<CR> -xmap ], :<C-U>exe 'norm! gv'<Bar>call search('^[<=>]\{7\}','W')<CR> -nmap [< :call search('^<<<<<<<','bW')<CR> -nmap [= :call search('^=======','bW')<CR> -nmap [> :call search('^>>>>>>>','bW')<CR> -nmap ]< :call search('^<<<<<<<','W')<CR> -nmap ]= :call search('^=======','W')<CR> -nmap ]> :call search('^>>>>>>>','W')<CR> -xmap [< :<C-U>exe 'norm! gv'<Bar>call search('^<<<<<<<','bW')<CR> -xmap [= :<C-U>exe 'norm! gv'<Bar>call search('^=======','bW')<CR> -xmap [> :<C-U>exe 'norm! gv'<Bar>call search('^>>>>>>>','bW')<CR> -xmap ]< :<C-U>exe 'norm! gv'<Bar>call search('^<<<<<<<','W')<CR> -xmap ]= :<C-U>exe 'norm! gv'<Bar>call search('^=======','W')<CR> -xmap ]> :<C-U>exe 'norm! gv'<Bar>call search('^>>>>>>>','W')<CR> -omap [< V:call search('^<<<<<<<','bW')<CR> -omap [= V:call search('^=======','bW')<CR> -omap [> V:call search('^>>>>>>>','bW')<CR> -omap ]< V:call search('^<<<<<<<','W')<CR> -omap ]= V:call search('^=======','W')<CR> -omap ]> V:call search('^>>>>>>>','W')<CR> - -" }}}1 -" Line operations {{{1 - -function! s:BlankUp(count) abort - put!=repeat(nr2char(10), a:count) - ']+1 - silent! call repeat#set("\<Plug>unimpairedBlankUp", a:count) -endfunction - -function! s:BlankDown(count) abort - put =repeat(nr2char(10), a:count) - '[-1 - silent! call repeat#set("\<Plug>unimpairedBlankDown", a:count) -endfunction - -nnoremap <silent> <Plug>unimpairedBlankUp :<C-U>call <SID>BlankUp(v:count1)<CR> -nnoremap <silent> <Plug>unimpairedBlankDown :<C-U>call <SID>BlankDown(v:count1)<CR> - -nmap [<Space> <Plug>unimpairedBlankUp -nmap ]<Space> <Plug>unimpairedBlankDown - -function! s:Move(cmd, count, map) abort - normal! m` - exe 'move'.a:cmd.a:count - norm! `` - call repeat#set("\<Plug>unimpairedMove".a:map, a:count) -endfunction - -nnoremap <silent> <Plug>unimpairedMoveUp :<C-U>call <SID>Move('--',v:count1,'Up')<CR> -nnoremap <silent> <Plug>unimpairedMoveDown :<C-U>call <SID>Move('+',v:count1,'Down')<CR> -xnoremap <silent> <Plug>unimpairedMoveUp :<C-U>exe 'normal! m`'<Bar>exe '''<,''>move--'.v:count1<CR>`` -xnoremap <silent> <Plug>unimpairedMoveDown :<C-U>exe 'normal! m`'<Bar>exe '''<,''>move''>+'.v:count1<CR>`` - -nmap [e <Plug>unimpairedMoveUp -nmap ]e <Plug>unimpairedMoveDown -xmap [e <Plug>unimpairedMoveUp -xmap ]e <Plug>unimpairedMoveDown - -" }}}1 -" Encoding and decoding {{{1 - -function! s:StringEncode(str) - let map = {"\n": 'n', "\r": 'r', "\t": 't', "\b": 'b', "\f": '\f', '"': '"', '\': '\'} - return substitute(a:str,"[\001-\033\\\\\"]",'\="\\".get(map,submatch(0),printf("%03o",char2nr(submatch(0))))','g') -endfunction - -function! s:StringDecode(str) - let map = {'n': "\n", 'r': "\r", 't': "\t", 'b': "\b", 'f': "\f", 'e': "\e", 'a': "\001", 'v': "\013"} - let str = a:str - if str =~ '^\s*".\{-\}\\\@<!\%(\\\\\)*"\s*\n\=$' - let str = substitute(substitute(str,'^\s*\zs"','',''),'"\ze\s*\n\=$','','') - endif - let str = substitute(str,'\\n\%(\n$\)\=','\n','g') - return substitute(str,'\\\(\o\{1,3\}\|x\x\{1,2\}\|u\x\{1,4\}\|.\)','\=get(map,submatch(1),submatch(1) =~? "^[0-9xu]" ? nr2char("0".substitute(submatch(1),"^[Uu]","x","")) : submatch(1))','g') -endfunction - -function! s:UrlEncode(str) - return substitute(a:str,'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g') -endfunction - -function! s:UrlDecode(str) - let str = substitute(substitute(substitute(a:str,'%0[Aa]\n$','%0A',''),'%0[Aa]','\n','g'),'+',' ','g') - return substitute(str,'%\(\x\x\)','\=nr2char("0x".submatch(1))','g') -endfunction - -" HTML entities {{{2 - -let g:unimpaired_html_entities = { - \ 'nbsp': 160, 'iexcl': 161, 'cent': 162, 'pound': 163, - \ 'curren': 164, 'yen': 165, 'brvbar': 166, 'sect': 167, - \ 'uml': 168, 'copy': 169, 'ordf': 170, 'laquo': 171, - \ 'not': 172, 'shy': 173, 'reg': 174, 'macr': 175, - \ 'deg': 176, 'plusmn': 177, 'sup2': 178, 'sup3': 179, - \ 'acute': 180, 'micro': 181, 'para': 182, 'middot': 183, - \ 'cedil': 184, 'sup1': 185, 'ordm': 186, 'raquo': 187, - \ 'frac14': 188, 'frac12': 189, 'frac34': 190, 'iquest': 191, - \ 'Agrave': 192, 'Aacute': 193, 'Acirc': 194, 'Atilde': 195, - \ 'Auml': 196, 'Aring': 197, 'AElig': 198, 'Ccedil': 199, - \ 'Egrave': 200, 'Eacute': 201, 'Ecirc': 202, 'Euml': 203, - \ 'Igrave': 204, 'Iacute': 205, 'Icirc': 206, 'Iuml': 207, - \ 'ETH': 208, 'Ntilde': 209, 'Ograve': 210, 'Oacute': 211, - \ 'Ocirc': 212, 'Otilde': 213, 'Ouml': 214, 'times': 215, - \ 'Oslash': 216, 'Ugrave': 217, 'Uacute': 218, 'Ucirc': 219, - \ 'Uuml': 220, 'Yacute': 221, 'THORN': 222, 'szlig': 223, - \ 'agrave': 224, 'aacute': 225, 'acirc': 226, 'atilde': 227, - \ 'auml': 228, 'aring': 229, 'aelig': 230, 'ccedil': 231, - \ 'egrave': 232, 'eacute': 233, 'ecirc': 234, 'euml': 235, - \ 'igrave': 236, 'iacute': 237, 'icirc': 238, 'iuml': 239, - \ 'eth': 240, 'ntilde': 241, 'ograve': 242, 'oacute': 243, - \ 'ocirc': 244, 'otilde': 245, 'ouml': 246, 'divide': 247, - \ 'oslash': 248, 'ugrave': 249, 'uacute': 250, 'ucirc': 251, - \ 'uuml': 252, 'yacute': 253, 'thorn': 254, 'yuml': 255, - \ 'OElig': 338, 'oelig': 339, 'Scaron': 352, 'scaron': 353, - \ 'Yuml': 376, 'circ': 710, 'tilde': 732, 'ensp': 8194, - \ 'emsp': 8195, 'thinsp': 8201, 'zwnj': 8204, 'zwj': 8205, - \ 'lrm': 8206, 'rlm': 8207, 'ndash': 8211, 'mdash': 8212, - \ 'lsquo': 8216, 'rsquo': 8217, 'sbquo': 8218, 'ldquo': 8220, - \ 'rdquo': 8221, 'bdquo': 8222, 'dagger': 8224, 'Dagger': 8225, - \ 'permil': 8240, 'lsaquo': 8249, 'rsaquo': 8250, 'euro': 8364, - \ 'fnof': 402, 'Alpha': 913, 'Beta': 914, 'Gamma': 915, - \ 'Delta': 916, 'Epsilon': 917, 'Zeta': 918, 'Eta': 919, - \ 'Theta': 920, 'Iota': 921, 'Kappa': 922, 'Lambda': 923, - \ 'Mu': 924, 'Nu': 925, 'Xi': 926, 'Omicron': 927, - \ 'Pi': 928, 'Rho': 929, 'Sigma': 931, 'Tau': 932, - \ 'Upsilon': 933, 'Phi': 934, 'Chi': 935, 'Psi': 936, - \ 'Omega': 937, 'alpha': 945, 'beta': 946, 'gamma': 947, - \ 'delta': 948, 'epsilon': 949, 'zeta': 950, 'eta': 951, - \ 'theta': 952, 'iota': 953, 'kappa': 954, 'lambda': 955, - \ 'mu': 956, 'nu': 957, 'xi': 958, 'omicron': 959, - \ 'pi': 960, 'rho': 961, 'sigmaf': 962, 'sigma': 963, - \ 'tau': 964, 'upsilon': 965, 'phi': 966, 'chi': 967, - \ 'psi': 968, 'omega': 969, 'thetasym': 977, 'upsih': 978, - \ 'piv': 982, 'bull': 8226, 'hellip': 8230, 'prime': 8242, - \ 'Prime': 8243, 'oline': 8254, 'frasl': 8260, 'weierp': 8472, - \ 'image': 8465, 'real': 8476, 'trade': 8482, 'alefsym': 8501, - \ 'larr': 8592, 'uarr': 8593, 'rarr': 8594, 'darr': 8595, - \ 'harr': 8596, 'crarr': 8629, 'lArr': 8656, 'uArr': 8657, - \ 'rArr': 8658, 'dArr': 8659, 'hArr': 8660, 'forall': 8704, - \ 'part': 8706, 'exist': 8707, 'empty': 8709, 'nabla': 8711, - \ 'isin': 8712, 'notin': 8713, 'ni': 8715, 'prod': 8719, - \ 'sum': 8721, 'minus': 8722, 'lowast': 8727, 'radic': 8730, - \ 'prop': 8733, 'infin': 8734, 'ang': 8736, 'and': 8743, - \ 'or': 8744, 'cap': 8745, 'cup': 8746, 'int': 8747, - \ 'there4': 8756, 'sim': 8764, 'cong': 8773, 'asymp': 8776, - \ 'ne': 8800, 'equiv': 8801, 'le': 8804, 'ge': 8805, - \ 'sub': 8834, 'sup': 8835, 'nsub': 8836, 'sube': 8838, - \ 'supe': 8839, 'oplus': 8853, 'otimes': 8855, 'perp': 8869, - \ 'sdot': 8901, 'lceil': 8968, 'rceil': 8969, 'lfloor': 8970, - \ 'rfloor': 8971, 'lang': 9001, 'rang': 9002, 'loz': 9674, - \ 'spades': 9824, 'clubs': 9827, 'hearts': 9829, 'diams': 9830, - \ 'apos': 39} - -" }}}2 - -function! s:XmlEncode(str) - let str = a:str - let str = substitute(str,'&','\&','g') - let str = substitute(str,'<','\<','g') - let str = substitute(str,'>','\>','g') - let str = substitute(str,'"','\"','g') - return str -endfunction - -function! s:XmlEntityDecode(str) - let str = substitute(a:str,'\c&#\%(0*38\|x0*26\);','&','g') - let str = substitute(str,'\c&#\(\d\+\);','\=nr2char(submatch(1))','g') - let str = substitute(str,'\c&#\(x\x\+\);','\=nr2char("0".submatch(1))','g') - let str = substitute(str,'\c'',"'",'g') - let str = substitute(str,'\c"','"','g') - let str = substitute(str,'\c>','>','g') - let str = substitute(str,'\c<','<','g') - let str = substitute(str,'\C&\(\%(amp;\)\@!\w*\);','\=nr2char(get(g:unimpaired_html_entities,submatch(1),63))','g') - return substitute(str,'\c&','\&','g') -endfunction - -function! s:XmlDecode(str) - let str = substitute(a:str,'<\%([[:alnum:]-]\+=\%("[^"]*"\|''[^'']*''\)\|.\)\{-\}>','','g') - return s:XmlEntityDecode(str) -endfunction - -function! s:Transform(algorithm,type) - let sel_save = &selection - let cb_save = &clipboard - set selection=inclusive clipboard-=unnamed clipboard-=unnamedplus - let reg_save = @@ - if a:type =~ '^\d\+$' - silent exe 'norm! ^v'.a:type.'$hy' - elseif a:type =~ '^.$' - silent exe "normal! `<" . a:type . "`>y" - elseif a:type == 'line' - silent exe "normal! '[V']y" - elseif a:type == 'block' - silent exe "normal! `[\<C-V>`]y" - else - silent exe "normal! `[v`]y" - endif - let @@ = s:{a:algorithm}(@@) - norm! gvp - let @@ = reg_save - let &selection = sel_save - let &clipboard = cb_save - if a:type =~ '^\d\+$' - silent! call repeat#set("\<Plug>unimpairedLine".a:algorithm,a:type) - endif -endfunction - -function! s:TransformOpfunc(type) - return s:Transform(s:encode_algorithm, a:type) -endfunction - -function! s:TransformSetup(algorithm) - let s:encode_algorithm = a:algorithm - let &opfunc = matchstr(expand('<sfile>'), '<SNR>\d\+_').'TransformOpfunc' -endfunction - -function! s:MapTransform(algorithm, key) - exe 'nnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>TransformSetup("'.a:algorithm.'")<CR>g@' - exe 'xnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",visualmode())<CR>' - exe 'nnoremap <silent> <Plug>unimpairedLine'.a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",v:count1)<CR>' - exe 'nmap '.a:key.' <Plug>unimpaired'.a:algorithm - exe 'xmap '.a:key.' <Plug>unimpaired'.a:algorithm - exe 'nmap '.a:key.a:key[strlen(a:key)-1].' <Plug>unimpairedLine'.a:algorithm -endfunction - -call s:MapTransform('StringEncode','[y') -call s:MapTransform('StringDecode',']y') -call s:MapTransform('UrlEncode','[u') -call s:MapTransform('UrlDecode',']u') -call s:MapTransform('XmlEncode','[x') -call s:MapTransform('XmlDecode',']x') - -" }}}1 - -" vim:set sw=2 sts=2: diff --git a/vim/plugin/vim-rspec.rb b/vim/plugin/vim-rspec.rb deleted file mode 100644 index 4d7f4c3..0000000 --- a/vim/plugin/vim-rspec.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "rubygems" -require "hpricot" - -doc = Hpricot(STDIN.read) -h1 = (doc/"h1") -classes = {"spec passed"=>"+","spec failed"=>"-","spec not_implemented"=>"#"} - -puts "* #{h1.inner_html}" - -stats = (doc/"script").select {|script| script.innerHTML =~ /duration|totals/ }.map {|script| script.inner_html.scan(/".*"/).first.gsub(/<\/?strong>/,"") } -stats.each do |stat| - puts "* #{stat.gsub(/\"/,'')}" -end -puts "* Parsed with Hpricot (http://wiki.github.com/why/hpricot)" -puts " " - -(doc/"div[@class='example_group']").each do |example| - puts "[#{(example/"dl/dt").inner_html}]" - (example/"dd").each do |dd| - txt = (dd/"span:first").inner_html - puts "#{classes[dd[:class]]} #{txt}" - next if dd[:class]!="spec failed" - failure = (dd/"div[@class='failure']") - msg = (failure/"div[@class='message']/pre").inner_html - back = (failure/"div[@class='backtrace']/pre").inner_html - ruby = (failure/"pre[@class='ruby']/code").inner_html.scan(/(<span class="linenum">)(\d+)(<\/span>)([^<]+)/).map {|elem| " "+elem[1]+": "+elem[3].chomp+"\n"}.join - puts " #{msg}" - puts " #{back}" - puts ruby - end - puts " " -end diff --git a/vim/plugin/vim-rspec.vim b/vim/plugin/vim-rspec.vim deleted file mode 100644 index edc7145..0000000 --- a/vim/plugin/vim-rspec.vim +++ /dev/null @@ -1,174 +0,0 @@ -" -" Vim Rspec -" Last change: March 5 2009 -" Version> 0.0.5 -" Maintainer: Eustáquio 'TaQ' Rangel -" License: GPL -" URL: git://github.com/taq/vim-rspec -" -" Script to run the spec command inside Vim -" To install, unpack the files on your ~/.vim directory and source it -" -" The following options can be set/overridden in your .vimrc -" * g:RspecXSLPath :: Path to xsl file -" * g:RspecRBFilePath :: Path to vim-rspec.rb -" * g:RspecBin :: Rspec binary command (in rspec 2 this is 'rspec') -" * g:RspecOpts :: Opts to send to rspec call - -let s:xsltproc_cmd = "" -let s:grep_cmd = "" -let s:hpricot_cmd = "" -let s:xslt = 0 -let s:hpricot = 0 -let s:helper_dir = expand("<sfile>:h") - -function! s:find_xslt() - return system("xsltproc --version | head -n1") -endfunction - -function! s:find_grep() - return system("grep --version | head -n1") -endfunction - -function! s:find_hpricot() - return system("gem search -i hpricot") -endfunction - -function! s:error_msg(msg) - echohl ErrorMsg - echo a:msg - echohl None -endfunction - -function! s:notice_msg(msg) - echohl MoreMsg - echo a:msg - echohl None -endfunction - -function! s:fetch(varname, default) - if exists("g:".a:varname) - return eval("g:".a:varname) - else - return a:default - endif -endfunction - -function! s:RunSpecMain(type) - if len(s:xsltproc_cmd)<1 - let s:xsltproc_cmd = s:find_xslt() - let s:xslt = match(s:xsltproc_cmd,'\d')>=0 - end - if len(s:hpricot_cmd)<1 - let s:hpricot_cmd = s:find_hpricot() - let s:hpricot = match(s:hpricot_cmd,'true')>=0 - end - if !s:hpricot && !s:xslt - call s:error_msg("You need the hpricot gem or xsltproc to run this script.") - return - end - if len(s:grep_cmd)<1 - let s:grep_cmd = s:find_grep() - if match(s:grep_cmd,'\d')<0 - call s:error_msg("You need grep to run this script.") - return - end - end - let l:bufn = bufname("%") - - " find the installed rspec command - let l:default_cmd = "" - if executable("spec")==1 - let l:default_cmd = "spec" - elseif executable("rspec")==1 - let l:default_cmd = "rspec" - end - - " filters - let l:xsl = s:fetch("RspecXSLPath", s:helper_dir."/vim-rspec.xsl") - let l:rubys = s:fetch("RspecRBPath", s:helper_dir."/vim-rspec.rb") - - " hpricot gets the priority - let l:type = s:hpricot ? "hpricot" : "xsltproc" - let l:filter = s:hpricot ? "ruby ".l:rubys : "xsltproc --novalid --html ".l:xsl." - " - - " run just the current file - if a:type=="file" - if match(l:bufn,'_spec.rb')>=0 - call s:notice_msg("Running spec on the current file with ".l:type." ...") - let l:spec_bin = s:fetch("RspecBin",l:default_cmd) - let l:spec_opts = s:fetch("RspecOpts", "") - let l:spec = l:spec_bin . " " . l:spec_opts . " -f h " . l:bufn - else - call s:error_msg("Seems ".l:bufn." is not a *_spec.rb file") - return - end - else - let l:dir = expand("%:p:h") - if isdirectory(l:dir."/spec")>0 - call s:notice_msg("Running spec on the spec directory with ".l:type." ...") - else - " try to find a spec directory on the current path - let l:tokens = split(l:dir,"/") - let l:dir = "" - for l:item in l:tokens - call remove(l:tokens,-1) - let l:path = "/".join(l:tokens,"/")."/spec" - if isdirectory(l:path) - let l:dir = l:path - break - end - endfor - if len(l:dir)>0 - call s:notice_msg("Running spec with ".l:type." on the spec directory found (".l:dir.") ...") - else - call s:error_msg("No ".l:dir."/spec directory found") - return - end - end - if isdirectory(l:dir)<0 - call s:error_msg("Could not find the ".l:dir." directory.") - return - end - let l:spec = s:fetch("RspecBin", "spec") . s:fetch("RspecOpts", "") - let l:spec = l:spec . " -f h " . l:dir . " -p **/*_spec.rb" - end - - " run the spec command - let s:cmd = l:spec." | ".l:filter." 2> /dev/null | grep \"^[-\+\[\\#\\* ]\"" - echo - - " put the result on a new buffer - silent exec "new" - setl buftype=nofile - silent exec "r! ".s:cmd - setl syntax=vim-rspec - silent exec "nnoremap <buffer> <cr> :call <SID>TryToOpen()<cr>" - silent exec "nnoremap <buffer> q :q<CR>" - setl foldmethod=expr - setl foldexpr=getline(v:lnum)=~'^\+' - setl foldtext=\"+--\ \".string(v:foldend-v:foldstart+1).\"\ passed\ \" - call cursor(1,1) -endfunction - -function! s:TryToOpen() - let l:line = getline(".") - if match(l:line,'^ [\/\.]')<0 - call s:error_msg("No file found.") - return - end - let l:tokens = split(l:line,":") - silent exec "sp ".substitute(l:tokens[0],'/^\s\+',"","") - call cursor(l:tokens[1],1) -endfunction - -function! RunSpec() - call s:RunSpecMain("file") -endfunction - -function! RunSpecs() - call s:RunSpecMain("dir") -endfunction - -command! RunSpec call RunSpec() -command! RunSpecs call RunSpecs() diff --git a/vim/plugin/vim-rspec.xsl b/vim/plugin/vim-rspec.xsl deleted file mode 100644 index 432dc51..0000000 --- a/vim/plugin/vim-rspec.xsl +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0"?> -<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> -<xsl:output method="text"/> - -<xsl:template match="/"> - <xsl:text>* Rspec Results </xsl:text> - <xsl:text>* Parsed with xsltproc (http://www.xmlsoft.org/XSLT/xsltproc2.html) </xsl:text> - <xsl:text> </xsl:text> - <xsl:apply-templates select="html/body/div[@class='rspec-report']/div[@class='results']"/> -</xsl:template> - -<xsl:template match="div[@class='rspec-report']"> - <xsl:apply-templates/> -</xsl:template> - -<xsl:template match="div[@class='example_group']"> - <xsl:text>[</xsl:text><xsl:value-of select="dl/dt"/><xsl:text>]</xsl:text> - <xsl:text> </xsl:text> - <xsl:apply-templates select="dl/dd"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec passed']"> - <xsl:text>+ </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec failed']"> - <xsl:text>- </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> - <xsl:apply-templates select="div"/> -</xsl:template> - -<xsl:template match="dd[@class='spec not_implemented']"> - <xsl:text># </xsl:text> - <xsl:value-of select="span"/> - <xsl:text> </xsl:text> -</xsl:template> - -<xsl:template match="dd[@class='spec failed']/div[@class='failure']"> - <xsl:text> </xsl:text><xsl:value-of select="div[@class='message']/pre"/> - <xsl:text> </xsl:text> - <xsl:text> </xsl:text><xsl:value-of select="div[@class='backtrace']/pre"/> - <xsl:text> </xsl:text> - <xsl:apply-templates select="pre[@class='ruby']/code"/> -</xsl:template> - -<xsl:template match="code"> - <xsl:value-of select="text()"/> - <xsl:text> </xsl:text> -</xsl:template> - -</xsl:stylesheet> diff --git a/vim/syntax/snippet.vim b/vim/syntax/snippet.vim deleted file mode 100644 index 3aa8571..0000000 --- a/vim/syntax/snippet.vim +++ /dev/null @@ -1,19 +0,0 @@ -" Syntax highlighting for snippet files (used for snipMate.vim) -" Hopefully this should make snippets a bit nicer to write! -syn match snipComment '^#.*' -syn match placeHolder '\${\d\+\(:.\{-}\)\=}' contains=snipCommand -syn match tabStop '\$\d\+' -syn match snipCommand '[^\\]`.\{-}`' -syn match snippet '^snippet.*' transparent contains=multiSnipText,snipKeyword -syn match multiSnipText '\S\+ \zs.*' contained -syn match snipKeyword '^snippet'me=s+8 contained -syn match snipError "^[^#s\t].*$" - -hi link snipComment Comment -hi link multiSnipText String -hi link snipKeyword Keyword -hi link snipComment Comment -hi link placeHolder Special -hi link tabStop Special -hi link snipCommand String -hi link snipError Error diff --git a/vim/syntax/tagbar.vim b/vim/syntax/tagbar.vim deleted file mode 100644 index 49b2ddc..0000000 --- a/vim/syntax/tagbar.vim +++ /dev/null @@ -1,63 +0,0 @@ -" File: tagbar.vim -" Description: Tagbar syntax settings -" Author: Jan Larres <jan@majutsushi.net> -" Licence: Vim licence -" Website: http://majutsushi.github.com/tagbar/ -" Version: 2.3 - -scriptencoding utf-8 - -if exists("b:current_syntax") - finish -endif - -let s:ic = g:tagbar_iconchars[0] -if s:ic =~ '[]^\\-]' - let s:ic = '\' . s:ic -endif -let s:io = g:tagbar_iconchars[1] -if s:io =~ '[]^\\-]' - let s:io = '\' . s:io -endif - -let s:pattern = '\([' . s:ic . s:io . '] \)\@<=[^-+: ]\+[^:]\+$' -execute "syntax match TagbarKind '" . s:pattern . "'" - -let s:pattern = '\([' . s:ic . s:io . '][-+# ]\)\@<=[^*]\+\(\*\?\(([^)]\+)\)\? :\)\@=' -execute "syntax match TagbarScope '" . s:pattern . "'" - -let s:pattern = '[' . s:ic . s:io . ']\([-+# ]\)\@=' -execute "syntax match TagbarFoldIcon '" . s:pattern . "'" - -let s:pattern = '\([' . s:ic . s:io . ' ]\)\@<=+\([^-+# ]\)\@=' -execute "syntax match TagbarAccessPublic '" . s:pattern . "'" -let s:pattern = '\([' . s:ic . s:io . ' ]\)\@<=#\([^-+# ]\)\@=' -execute "syntax match TagbarAccessProtected '" . s:pattern . "'" -let s:pattern = '\([' . s:ic . s:io . ' ]\)\@<=-\([^-+# ]\)\@=' -execute "syntax match TagbarAccessPrivate '" . s:pattern . "'" - -unlet s:pattern - -syntax match TagbarNestedKind '^\s\+\[[^]]\+\]$' -syntax match TagbarComment '^".*' -syntax match TagbarType ' : \zs.*' -syntax match TagbarSignature '(.*)' -syntax match TagbarPseudoID '\*\ze :' - -highlight default link TagbarComment Comment -highlight default link TagbarKind Identifier -highlight default link TagbarNestedKind TagbarKind -highlight default link TagbarScope Title -highlight default link TagbarType Type -highlight default link TagbarSignature SpecialKey -highlight default link TagbarPseudoID NonText -highlight default link TagbarFoldIcon Statement -highlight default link TagbarHighlight Search - -highlight default TagbarAccessPublic guifg=Green ctermfg=Green -highlight default TagbarAccessProtected guifg=Blue ctermfg=Blue -highlight default TagbarAccessPrivate guifg=Red ctermfg=Red - -let b:current_syntax = "tagbar" - -" vim: ts=8 sw=4 sts=4 et foldenable foldmethod=marker foldcolumn=1 diff --git a/vim/syntax_checkers/applescript.vim b/vim/syntax_checkers/applescript.vim deleted file mode 100644 index eb7a6f2..0000000 --- a/vim/syntax_checkers/applescript.vim +++ /dev/null @@ -1,43 +0,0 @@ -"============================================================================== -" FileName: applescript.vim -" Desc: Syntax checking plugin for syntastic.vim -" Author: Zhao Cai -" Email: caizhaoff@gmail.com -" Version: 0.2.1 -" Date Created: Thu 09 Sep 2011 10:30:09 AM EST -" Last Modified: Fri 09 Dec 2011 01:10:24 PM EST -" -" History: 0.1.0 - working, but it will run the script everytime to check -" syntax. Should use osacompile but strangely it does not give -" errors. -" -" 0.2.0 - switch to osacompile, it gives less errors compared -" with osascript. -" -" 0.2.1 - remove g:syntastic_applescript_tempfile. use -" tempname() instead. -" -" License: This program is free software. It comes without any -" warranty, to the extent permitted by applicable law. You can -" redistribute it and/or modify it under the terms of the Do What The -" Fuck You Want To Public License, Version 2, as published by Sam -" Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists("loaded_applescript_syntax_checker") - finish -endif -let loaded_applescript_syntax_checker = 1 - -"bail if the user doesnt have osacompile installed -if !executable("osacompile") - finish -endif - -function! SyntaxCheckers_applescript_GetLocList() - let makeprg = 'osacompile -o ' . tempname() . '.scpt '. shellescape(expand('%')) - let errorformat = '%f:%l:%m' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/c.vim b/vim/syntax_checkers/c.vim deleted file mode 100644 index 8bd486b..0000000 --- a/vim/syntax_checkers/c.vim +++ /dev/null @@ -1,156 +0,0 @@ -"============================================================================ -"File: c.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Gregor Uhlenheuer <kongo2002 at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" In order to also check header files add this to your .vimrc: -" (this usually creates a .gch file in your source directory) -" -" let g:syntastic_c_check_header = 1 -" -" To disable the search of included header files after special -" libraries like gtk and glib add this line to your .vimrc: -" -" let g:syntastic_c_no_include_search = 1 -" -" To enable header files being re-checked on every file write add the -" following line to your .vimrc. Otherwise the header files are checked only -" one time on initially loading the file. -" In order to force syntastic to refresh the header includes simply -" unlet b:syntastic_c_includes. Then the header files are being re-checked on -" the next file write. -" -" let g:syntastic_c_auto_refresh_includes = 1 -" -" Alternatively you can set the buffer local variable b:syntastic_c_cflags. -" If this variable is set for the current buffer no search for additional -" libraries is done. I.e. set the variable like this: -" -" let b:syntastic_c_cflags = ' -I/usr/include/libsoup-2.4' -" -" In order to add some custom include directories that should be added to the -" gcc command line you can add those to the global variable -" g:syntastic_c_include_dirs. This list can be used like this: -" -" let g:syntastic_c_include_dirs = [ 'includes', 'headers' ] -" -" Moreover it is possible to add additional compiler options to the syntax -" checking execution via the variable 'g:syntastic_c_compiler_options': -" -" let g:syntastic_c_compiler_options = ' -ansi' -" -" Using the global variable 'g:syntastic_c_remove_include_errors' you can -" specify whether errors of files included via the g:syntastic_c_include_dirs' -" setting are removed from the result set: -" -" let g:syntastic_c_remove_include_errors = 1 - -if exists('loaded_c_syntax_checker') - finish -endif -let loaded_c_syntax_checker = 1 - -if !executable('gcc') - finish -endif - -let s:save_cpo = &cpo -set cpo&vim - -" default include directories -let s:default_includes = [ '.', '..', 'include', 'includes', - \ '../include', '../includes' ] - -" uniquify the input list -function! s:Unique(list) - let l = [] - for elem in a:list - if index(l, elem) == -1 - let l = add(l, elem) - endif - endfor - return l -endfunction - -" get the gcc include directory argument depending on the default -" includes and the optional user-defined 'g:syntastic_c_include_dirs' -function! s:GetIncludeDirs() - let include_dirs = s:default_includes - - if exists('g:syntastic_c_include_dirs') - call extend(include_dirs, g:syntastic_c_include_dirs) - endif - - return join(map(s:Unique(include_dirs), '"-I" . v:val'), ' ') -endfunction - -function! SyntaxCheckers_c_GetLocList() - let makeprg = 'gcc -fsyntax-only -std=gnu99 '.shellescape(expand('%')). - \ ' '.s:GetIncludeDirs() - let errorformat = '%-G%f:%s:,%-G%f:%l: %#error: %#(Each undeclared '. - \ 'identifier is reported only%.%#,%-G%f:%l: %#error: %#for '. - \ 'each function it appears%.%#,%-GIn file included%.%#,'. - \ '%-G %#from %f:%l\,,%f:%l:%c: %m,%f:%l: %trror: %m,%f:%l: %m' - - " determine whether to parse header files as well - if expand('%') =~? '.h$' - if exists('g:syntastic_c_check_header') - let makeprg = 'gcc -c '.shellescape(expand('%')). - \ ' '.s:GetIncludeDirs() - else - return [] - endif - endif - - " add optional user-defined compiler options - if exists('g:syntastic_c_compiler_options') - let makeprg .= g:syntastic_c_compiler_options - endif - - " check if the user manually set some cflags - if !exists('b:syntastic_c_cflags') - " check whether to search for include files at all - if !exists('g:syntastic_c_no_include_search') || - \ g:syntastic_c_no_include_search != 1 - " refresh the include file search if desired - if exists('g:syntastic_c_auto_refresh_includes') && - \ g:syntastic_c_auto_refresh_includes != 0 - let makeprg .= syntastic#c#SearchHeaders() - else - " search for header includes if not cached already - if !exists('b:syntastic_c_includes') - let b:syntastic_c_includes = syntastic#c#SearchHeaders() - endif - let makeprg .= b:syntastic_c_includes - endif - endif - else - " use the user-defined cflags - let makeprg .= b:syntastic_c_cflags - endif - - " process makeprg - let errors = SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat }) - - " filter the processed errors if desired - if exists('g:syntastic_c_remove_include_errors') && - \ g:syntastic_c_remove_include_errors != 0 - return filter(errors, - \ 'has_key(v:val, "bufnr") && v:val["bufnr"]=='.bufnr('')) - else - return errors - endif -endfunction - -let &cpo = s:save_cpo -unlet s:save_cpo - -" vim: set et sts=4 sw=4: diff --git a/vim/syntax_checkers/coffee.vim b/vim/syntax_checkers/coffee.vim deleted file mode 100644 index 59dca75..0000000 --- a/vim/syntax_checkers/coffee.vim +++ /dev/null @@ -1,27 +0,0 @@ -"============================================================================ -"File: coffee.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Lincoln Stoll <l@lds.li> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_coffee_syntax_checker") - finish -endif -let loaded_coffee_syntax_checker = 1 - -"bail if the user doesnt have coffee installed -if !executable("coffee") - finish -endif - -function! SyntaxCheckers_coffee_GetLocList() - let makeprg = 'coffee -c -l -o /tmp '.shellescape(expand('%')) - let errorformat = 'Syntax%trror: In %f\, %m on line %l,%EError: In %f\, Parse error on line %l: %m,%EError: In %f\, %m on line %l,%W%f(%l): lint warning: %m,%-Z%p^,%W%f(%l): warning: %m,%-Z%p^,%E%f(%l): SyntaxError: %m,%-Z%p^,%-G%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/cpp.vim b/vim/syntax_checkers/cpp.vim deleted file mode 100644 index 1bacf93..0000000 --- a/vim/syntax_checkers/cpp.vim +++ /dev/null @@ -1,94 +0,0 @@ -"============================================================================ -"File: cpp.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Gregor Uhlenheuer <kongo2002 at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" in order to also check header files add this to your .vimrc: -" (this usually creates a .gch file in your source directory) -" -" let g:syntastic_cpp_check_header = 1 -" -" To disable the search of included header files after special -" libraries like gtk and glib add this line to your .vimrc: -" -" let g:syntastic_cpp_no_include_search = 1 -" -" To enable header files being re-checked on every file write add the -" following line to your .vimrc. Otherwise the header files are checked only -" one time on initially loading the file. -" In order to force syntastic to refresh the header includes simply -" unlet b:syntastic_cpp_includes. Then the header files are being re-checked -" on the next file write. -" -" let g:syntastic_cpp_auto_refresh_includes = 1 -" -" Alternatively you can set the buffer local variable b:syntastic_cpp_cflags. -" If this variable is set for the current buffer no search for additional -" libraries is done. I.e. set the variable like this: -" -" let b:syntastic_cpp_cflags = ' -I/usr/include/libsoup-2.4' -" -" Moreover it is possible to add additional compiler options to the syntax -" checking execution via the variable 'g:syntastic_cpp_compiler_options': -" -" let g:syntastic_cpp_compiler_options = ' -std=c++0x' - -if exists('loaded_cpp_syntax_checker') - finish -endif -let loaded_cpp_syntax_checker = 1 - -if !executable('g++') - finish -endif - -let s:save_cpo = &cpo -set cpo&vim - -function! SyntaxCheckers_cpp_GetLocList() - let makeprg = 'g++ -fsyntax-only '.shellescape(expand('%')) - let errorformat = '%-G%f:%s:,%f:%l:%c: %m,%f:%l: %m' - - if expand('%') =~? '\%(.h\|.hpp\|.hh\)$' - if exists('g:syntastic_cpp_check_header') - let makeprg = 'g++ -c '.shellescape(expand('%')) - else - return [] - endif - endif - - if exists('g:syntastic_cpp_compiler_options') - let makeprg .= g:syntastic_cpp_compiler_options - endif - - if !exists('b:syntastic_cpp_cflags') - if !exists('g:syntastic_cpp_no_include_search') || - \ g:syntastic_cpp_no_include_search != 1 - if exists('g:syntastic_cpp_auto_refresh_includes') && - \ g:syntastic_cpp_auto_refresh_includes != 0 - let makeprg .= syntastic#c#SearchHeaders() - else - if !exists('b:syntastic_cpp_includes') - let b:syntastic_cpp_includes = syntastic#c#SearchHeaders() - endif - let makeprg .= b:syntastic_cpp_includes - endif - endif - else - let makeprg .= b:syntastic_cpp_cflags - endif - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction - -let &cpo = s:save_cpo -unlet s:save_cpo - -" vim: set et sts=4 sw=4: diff --git a/vim/syntax_checkers/css.vim b/vim/syntax_checkers/css.vim deleted file mode 100644 index 99a16b8..0000000 --- a/vim/syntax_checkers/css.vim +++ /dev/null @@ -1,31 +0,0 @@ -"============================================================================ -"File: css.vim -"Description: Syntax checking plugin for syntastic.vim using `csslint` CLI tool (http://csslint.net). -"Maintainer: Ory Band <oryband at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ -if exists("loaded_css_syntax_checker") - finish -endif -let loaded_css_syntax_checker = 1 - -" Bail if the user doesn't have `csslint` installed. -if !executable("csslint") - finish -endif - -function! SyntaxCheckers_css_GetLocList() - let makeprg = 'csslint --format=compact '.shellescape(expand('%')) - - " Print CSS Lint's error/warning messages from compact format. Ignores blank lines. - let errorformat = '%-G,%-G%f: lint free!,%f: line %l\, col %c\, %trror - %m,%f: line %l\, col %c\, %tarning - %m,%f: line %l\, col %c\, %m,' - - return SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat, - \ 'defaults': {'bufnr': bufnr("")} }) - -endfunction diff --git a/vim/syntax_checkers/cucumber.vim b/vim/syntax_checkers/cucumber.vim deleted file mode 100644 index c9a87e1..0000000 --- a/vim/syntax_checkers/cucumber.vim +++ /dev/null @@ -1,27 +0,0 @@ -"============================================================================ -"File: cucumber.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_cucumber_syntax_checker") - finish -endif -let loaded_cucumber_syntax_checker = 1 - -"bail if the user doesnt have cucumber installed -if !executable("cucumber") - finish -endif - -function! SyntaxCheckers_cucumber_GetLocList() - let makeprg = 'cucumber --dry-run --quiet --strict --format pretty '.shellescape(expand('%')) - let errorformat = '%f:%l:%c:%m,%W %.%# (%m),%-Z%f:%l:%.%#,%-G%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/cuda.vim b/vim/syntax_checkers/cuda.vim deleted file mode 100644 index 816505e..0000000 --- a/vim/syntax_checkers/cuda.vim +++ /dev/null @@ -1,37 +0,0 @@ -"============================================================================ -"File: cuda.vim -"Description: Syntax checking plugin for syntastic.vim -" -"Author: Hannes Schulz <schulz at ais dot uni-bonn dot de> -" -"============================================================================ - -" in order to also check header files add this to your .vimrc: -" (this creates an empty .syntastic_dummy.cu file in your source directory) -" -" let g:syntastic_cuda_check_header = 1 - -if exists('loaded_cuda_syntax_checker') - finish -endif -let loaded_cuda_syntax_checker = 1 - -if !executable('nvcc') - finish -endif - -function! SyntaxCheckers_cuda_GetLocList() - let makeprg = 'nvcc --cuda -O0 -I . -Xcompiler -fsyntax-only '.shellescape(expand('%')).' -o /dev/null' - "let errorformat = '%-G%f:%s:,%f:%l:%c: %m,%f:%l: %m' - let errorformat = '%*[^"]"%f"%*\D%l: %m,"%f"%*\D%l: %m,%-G%f:%l: (Each undeclared identifier is reported only once,%-G%f:%l: for each function it appears in.),%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,"%f"\, line %l%*\D%c%*[^ ] %m,%D%*\a[%*\d]: Entering directory `%f'',%X%*\a[%*\d]: Leaving directory `%f'',%D%*\a: Entering directory `%f'',%X%*\a: Leaving directory `%f'',%DMaking %*\a in %f,%f|%l| %m' - - if expand('%') =~? '\%(.h\|.hpp\|.cuh\)$' - if exists('g:syntastic_cuda_check_header') - let makeprg = 'echo > .syntastic_dummy.cu ; nvcc --cuda -O0 -I . .syntastic_dummy.cu -Xcompiler -fsyntax-only -include '.shellescape(expand('%')).' -o /dev/null' - else - return [] - endif - endif - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/docbk.vim b/vim/syntax_checkers/docbk.vim deleted file mode 100644 index cd360e4..0000000 --- a/vim/syntax_checkers/docbk.vim +++ /dev/null @@ -1,29 +0,0 @@ -"============================================================================ -"File: docbk.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_docbk_syntax_checker") - finish -endif -let loaded_docbk_syntax_checker = 1 - -"bail if the user doesnt have tidy or grep installed -if !executable("xmllint") - finish -endif - -function! SyntaxCheckers_docbk_GetLocList() - - let makeprg="xmllint --xinclude --noout --postvalid ".shellescape(expand(%:p)) - let errorformat='%E%f:%l: parser error : %m,%W%f:%l: parser warning : %m,%E%f:%l:%.%# validity error : %m,%W%f:%l:%.%# validity warning : %m,%-Z%p^,%-C%.%#,%-G%.%#' - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - return loclist -endfunction diff --git a/vim/syntax_checkers/efm_perl.pl b/vim/syntax_checkers/efm_perl.pl deleted file mode 100644 index 570d6e7..0000000 --- a/vim/syntax_checkers/efm_perl.pl +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/perl -w - -# vimparse.pl - Reformats the error messages of the Perl interpreter for use -# with the quickfix mode of Vim -# -# Copyright () 2001 by Jrg Ziefle <joerg.ziefle@gmx.de> -# You may use and distribute this software under the same terms as Perl itself. -# -# Usage: put one of the two configurations below in your ~/.vimrc (without the -# description and '# ') and enjoy (be sure to adjust the paths to vimparse.pl -# before): -# -# Program is run interactively with 'perl -w': -# -# set makeprg=$HOME/bin/vimparse.pl\ %\ $* -# set errorformat=%f:%l:%m -# -# Program is only compiled with 'perl -wc': -# -# set makeprg=$HOME/bin/vimparse.pl\ -c\ %\ $* -# set errorformat=%f:%l:%m -# -# Usage: -# vimparse.pl [-c] [-f <errorfile>] <programfile> [programargs] -# -# -c compile only, don't run (perl -wc) -# -f write errors to <errorfile> -# -# Example usages: -# * From the command line: -# vimparse.pl program.pl -# -# vimparse.pl -c -f errorfile program.pl -# Then run vim -q errorfile to edit the errors with Vim. -# -# * From Vim: -# Edit in Vim (and save, if you don't have autowrite on), then -# type ':mak' or ':mak args' (args being the program arguments) -# to error check. -# -# Version history: -# 0.2 (04/12/2001): -# * First public version (sent to Bram) -# * -c command line option for compiling only -# * grammatical fix: 'There was 1 error.' -# * bug fix for multiple arguments -# * more error checks -# * documentation (top of file, &usage) -# * minor code clean ups -# 0.1 (02/02/2001): -# * Initial version -# * Basic functionality -# -# Todo: -# * test on more systems -# * use portable way to determine the location of perl ('use Config') -# * include option that shows perldiag messages for each error -# * allow to pass in program by STDIN -# * more intuitive behaviour if no error is found (show message) -# -# Tested under SunOS 5.7 with Perl 5.6.0. Let me know if it's not working for -# you. - -use strict; -use Getopt::Std; - -use vars qw/$opt_c $opt_f $opt_h/; # needed for Getopt in combination with use strict 'vars' - -use constant VERSION => 0.2; - -getopts('cf:h'); - -&usage if $opt_h; # not necessarily needed, but good for further extension - -if (defined $opt_f) { - - open FILE, "> $opt_f" or do { - warn "Couldn't open $opt_f: $!. Using STDOUT instead.\n"; - undef $opt_f; - }; - -}; - -my $handle = (defined $opt_f ? \*FILE : \*STDOUT); - -(my $file = shift) or &usage; # display usage if no filename is supplied -my $args = (@ARGV ? ' ' . join ' ', @ARGV : ''); - -my @lines = `perl @{[defined $opt_c ? '-c ' : '' ]} -w "$file$args" 2>&1`; - -my $errors = 0; -foreach my $line (@lines) { - - chomp($line); - my ($file, $lineno, $message, $rest); - - if ($line =~ /^(.*)\sat\s(.*)\sline\s(\d+)(\.|,\snear\s\".*\")$/) { - - ($message, $file, $lineno, $rest) = ($1, $2, $3, $4); - $errors++; - $message .= $rest if ($rest =~ s/^,//); - print $handle "$file:$lineno:$message\n"; - - } else { next }; - -} - -if (defined $opt_f) { - - my $msg; - if ($errors == 1) { - - $msg = "There was 1 error.\n"; - - } else { - - $msg = "There were $errors errors.\n"; - - }; - - print STDOUT $msg; - close FILE; - unlink $opt_f unless $errors; - -}; - -sub usage { - - (local $0 = $0) =~ s/^.*\/([^\/]+)$/$1/; # remove path from name of program - print<<EOT; -Usage: - $0 [-c] [-f <errorfile>] <programfile> [programargs] - - -c compile only, don't run (executes 'perl -wc') - -f write errors to <errorfile> - -Examples: - * At the command line: - $0 program.pl - Displays output on STDOUT. - - $0 -c -f errorfile program.pl - Then run 'vim -q errorfile' to edit the errors with Vim. - - * In Vim: - Edit in Vim (and save, if you don't have autowrite on), then - type ':mak' or ':mak args' (args being the program arguments) - to error check. -EOT - - exit 0; - -}; diff --git a/vim/syntax_checkers/erlang.vim b/vim/syntax_checkers/erlang.vim deleted file mode 100644 index d7dceae..0000000 --- a/vim/syntax_checkers/erlang.vim +++ /dev/null @@ -1,42 +0,0 @@ -"============================================================================ -"File: erlang.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Pawel Salata <rockplayer.pl at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_erlang_syntax_checker") - finish -endif -let loaded_erlang_syntax_checker = 1 - -"bail if the user doesnt have escript installed -if !executable("escript") - finish -endif - -let s:check_file = expand('<sfile>:p:h') . '/erlang_check_file.erl' - -function! SyntaxCheckers_erlang_GetLocList() - let extension = expand('%:e') - if match(extension, 'hrl') >= 0 - return [] - endif - let shebang = getbufline(bufnr('%'), 1)[0] - if len(shebang) > 0 - if match(shebang, 'escript') >= 0 - let makeprg = 'escript -s '.shellescape(expand('%:p')) - else - let makeprg = s:check_file . ' '. shellescape(expand('%:p')) - endif - else - let makeprg = s:check_file . ' ' . shellescape(expand('%:p')) - endif - let errorformat = '%f:%l:\ %tarning:\ %m,%E%f:%l:\ %m' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/erlang_check_file.erl b/vim/syntax_checkers/erlang_check_file.erl deleted file mode 100755 index 8a85bf6..0000000 --- a/vim/syntax_checkers/erlang_check_file.erl +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env escript --export([main/1]). - -main([FileName]) -> - compile:file(FileName, [warn_obsolete_guard, - warn_unused_import, - warn_shadow_vars, - warn_export_vars, - strong_validation, - report, - {i, filename:dirname(FileName) ++ "/../include"} - ]). diff --git a/vim/syntax_checkers/eruby.vim b/vim/syntax_checkers/eruby.vim deleted file mode 100644 index fcff063..0000000 --- a/vim/syntax_checkers/eruby.vim +++ /dev/null @@ -1,34 +0,0 @@ -"============================================================================ -"File: eruby.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_eruby_syntax_checker") - finish -endif -let loaded_eruby_syntax_checker = 1 - -"bail if the user doesnt have ruby or cat installed -if !executable("ruby") || !executable("cat") - finish -endif - -function! SyntaxCheckers_eruby_GetLocList() - if has('win32') || has('win64') - let makeprg='sed "s/<\%=/<\%/g" '. shellescape(expand("%")) . ' \| ruby -e "require \"erb\"; puts ERB.new(ARGF.read, nil, \"-\").src" \| ruby -c' - else - let makeprg='sed "s/<\%=/<\%/g" '. shellescape(expand("%")) . ' \| RUBYOPT= ruby -e "require \"erb\"; puts ERB.new(ARGF.read, nil, \"-\").src" \| RUBYOPT= ruby -c' - endif - - let errorformat='%-GSyntax OK,%E-:%l: syntax error\, %m,%Z%p^,%W-:%l: warning: %m,%Z%p^,%-C%.%#' - return SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat, - \ 'defaults': {'bufnr': bufnr("")} }) - -endfunction diff --git a/vim/syntax_checkers/fortran.vim b/vim/syntax_checkers/fortran.vim deleted file mode 100644 index ee176f2..0000000 --- a/vim/syntax_checkers/fortran.vim +++ /dev/null @@ -1,44 +0,0 @@ -"============================================================================ -"File: fortran.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Karl Yngve Lervåg <karl.yngve@lervag.net> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"Note: This syntax checker uses gfortran with the option -fsyntax-only -" to check for errors and warnings. Additional flags may be -" supplied through both local and global variables, -" b:syntastic_fortran_flags, -" g:syntastic_fortran_flags. -" This is particularly useful when the source requires module files -" in order to compile (that is when it needs modules defined in -" separate files). -" -"============================================================================ - -if exists("loaded_fortran_syntax_checker") - finish -endif -let loaded_fortran_syntax_checker = 1 - -"bail if the user doesnt have fortran installed -if !executable("gfortran") - finish -endif - -if !exists('g:syntastic_fortran_flags') - let g:syntastic_fortran_flags = '' -endif - -function! SyntaxCheckers_fortran_GetLocList() - let makeprg = 'gfortran -fsyntax-only' - let makeprg .= g:syntastic_fortran_flags - if exists('b:syntastic_fortran_flags') - let makeprg .= b:syntastic_fortran_flags - endif - let makeprg .= ' ' . shellescape(expand('%')) - let errorformat = '%-C %#,%-C %#%.%#,%A%f:%l.%c:,%Z%m,%G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/gentoo_metadata.vim b/vim/syntax_checkers/gentoo_metadata.vim deleted file mode 100644 index d016a88..0000000 --- a/vim/syntax_checkers/gentoo_metadata.vim +++ /dev/null @@ -1,37 +0,0 @@ -"============================================================================ -"File: gentoo-metadata.vim -"Description: Syntax checking plugin for Gentoo's metadata.xml files -"Maintainer: James Rowe <jnrowe at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" The DTDs required to validate metadata.xml files are available in -" $PORTDIR/metadata/dtd, and these local files can be used to significantly -" speed up validation. You can create a catalog file with: -" -" xmlcatalog --create --add rewriteURI http://www.gentoo.org/dtd/ \ -" ${PORTDIR:-/usr/portage}/metadata/dtd/ /etc/xml/gentoo -" -" See xmlcatalog(1) and http://www.xmlsoft.org/catalog.html for more -" information. - -if exists("loaded_gentoo_metadata_syntax_checker") - finish -endif -let loaded_gentoo_metadata_syntax_checker = 1 - -"bail if the user doesn't have xmllint installed -if !executable("xmllint") - finish -endif - -runtime syntax_checkers/xml.vim - -function! SyntaxCheckers_gentoo_metadata_GetLocList() - return SyntaxCheckers_xml_GetLocList() -endfunction diff --git a/vim/syntax_checkers/go.vim b/vim/syntax_checkers/go.vim deleted file mode 100644 index 395ae11..0000000 --- a/vim/syntax_checkers/go.vim +++ /dev/null @@ -1,22 +0,0 @@ -"============================================================================ -"File: go.vim -"Description: Loads a go syntax checker from the go directory -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -" Use g:syntastic_go_checker option to specify which go executable -" should be used (see below for a list of supported checkers). -" If g:syntastic_go_checker is not set, just use the first syntax -" checker that we find installed. -"============================================================================ -if exists("loaded_go_syntax_checker") - finish -endif -let loaded_go_syntax_checker = 1 - -let s:supported_checkers = ["6g", "gofmt"] -call SyntasticLoadChecker(s:supported_checkers) diff --git a/vim/syntax_checkers/go/6g.vim b/vim/syntax_checkers/go/6g.vim deleted file mode 100644 index 1a4249e..0000000 --- a/vim/syntax_checkers/go/6g.vim +++ /dev/null @@ -1,17 +0,0 @@ -"============================================================================ -"File: 6g.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Sam Nguyen <samxnguyen@gmail.com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -function! SyntaxCheckers_go_GetLocList() - let makeprg = '6g -o /dev/null %' - let errorformat = '%E%f:%l: %m' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/go/gofmt.vim b/vim/syntax_checkers/go/gofmt.vim deleted file mode 100644 index 77abe7e..0000000 --- a/vim/syntax_checkers/go/gofmt.vim +++ /dev/null @@ -1,16 +0,0 @@ -"============================================================================ -"File: gofmt.vim -"Description: Check go syntax using gofmt -"Maintainer: Brandon Thomson <bt@brandonthomson.com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -function! SyntaxCheckers_go_GetLocList() - let makeprg = 'gofmt %' - let errorformat = '%f:%l:%c: %m,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'type': 'e'} }) -endfunction diff --git a/vim/syntax_checkers/haml.vim b/vim/syntax_checkers/haml.vim deleted file mode 100644 index b9ad6ad..0000000 --- a/vim/syntax_checkers/haml.vim +++ /dev/null @@ -1,26 +0,0 @@ -"============================================================================ -"File: haml.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_haml_syntax_checker") - finish -endif -let loaded_haml_syntax_checker = 1 - -"bail if the user doesnt have the haml binary installed -if !executable("haml") - finish -endif - -function! SyntaxCheckers_haml_GetLocList() - let makeprg = "haml -c " . shellescape(expand("%")) - let errorformat = 'Haml error on line %l: %m,Syntax error on line %l: %m,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/haskell.vim b/vim/syntax_checkers/haskell.vim deleted file mode 100644 index 07c55e8..0000000 --- a/vim/syntax_checkers/haskell.vim +++ /dev/null @@ -1,37 +0,0 @@ -"============================================================================ -"File: haskell.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Anthony Carapetis <anthony.carapetis at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_haskell_syntax_checker") - finish -endif -let loaded_haskell_syntax_checker = 1 - -"bail if the user doesnt have ghc-mod installed -if !executable("ghc-mod") - finish -endif - -function! SyntaxCheckers_haskell_GetLocList() - let makeprg = - \ "{ ". - \ "ghc-mod check ". shellescape(expand('%')) . "; " . - \ "ghc-mod lint " . shellescape(expand('%')) . ";" . - \ " }" - let errorformat = '%-G\\s%#,%f:%l:%c:%trror: %m,%f:%l:%c:%tarning: %m,'. - \ '%f:%l:%c: %trror: %m,%f:%l:%c: %tarning: %m,%f:%l:%c:%m,'. - \ '%E%f:%l:%c:,%Z%m,' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction - -function! SyntaxCheckers_lhaskell_GetLocList() - return SyntaxCheckers_haskell_GetLocList() -endfunction diff --git a/vim/syntax_checkers/haxe.vim b/vim/syntax_checkers/haxe.vim deleted file mode 100644 index 22183ee..0000000 --- a/vim/syntax_checkers/haxe.vim +++ /dev/null @@ -1,55 +0,0 @@ -"============================================================================ -"File: haxe.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: David Bernard <david.bernard.31 at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_haxe_syntax_checker") - finish -endif -let loaded_haxe_syntax_checker = 1 - -"bail if the user doesn't have haxe installed -if !executable("haxe") - finish -endif - -" s:FindInParent -" find the file argument and returns the path to it. -" Starting with the current working dir, it walks up the parent folders -" until it finds the file, or it hits the stop dir. -" If it doesn't find it, it returns "Nothing" -function! s:FindInParent(fln,flsrt,flstp) - let here = a:flsrt - while ( strlen( here) > 0 ) - let p = split(globpath(here, a:fln), '\n') - if len(p) > 0 - return ['ok', here, fnamemodify(p[0], ':p:t')] - endif - let fr = match(here, '/[^/]*$') - if fr == -1 - break - endif - let here = strpart(here, 0, fr) - if here == a:flstp - break - endif - endwhile - return ['fail', '', ''] -endfunction - -function! SyntaxCheckers_haxe_GetLocList() - let [success, hxmldir, hxmlname] = s:FindInParent('*.hxml', expand('%:p:h'), '/') - if success == 'ok' - let makeprg = 'cd ' . hxmldir . '; haxe ' . hxmlname - let errorformat = '%E%f:%l: characters %c-%*[0-9] : %m' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - else - return SyntasticMake({}) - endif -endfunction diff --git a/vim/syntax_checkers/html.vim b/vim/syntax_checkers/html.vim deleted file mode 100644 index 2c1b8b4..0000000 --- a/vim/syntax_checkers/html.vim +++ /dev/null @@ -1,86 +0,0 @@ -"============================================================================ -"File: html.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_html_syntax_checker") - finish -endif -let loaded_html_syntax_checker = 1 - -"bail if the user doesnt have tidy or grep installed -if !executable("tidy") || !executable("grep") - finish -endif - -" TODO: join this with xhtml.vim for DRY's sake? -function! s:TidyEncOptByFenc() - let tidy_opts = { - \'utf-8' : '-utf8', - \'ascii' : '-ascii', - \'latin1' : '-latin1', - \'iso-2022-jp' : '-iso-2022', - \'cp1252' : '-win1252', - \'macroman' : '-mac', - \'utf-16le' : '-utf16le', - \'utf-16' : '-utf16', - \'big5' : '-big5', - \'sjis' : '-shiftjis', - \'cp850' : '-ibm858', - \} - return get(tidy_opts, &fileencoding, '-utf8') -endfunction - -let s:ignore_html_errors = [ - \ "<table> lacks \"summary\" attribute", - \ "not approved by W3C", - \ "attribute \"placeholder\"", - \ "<meta> proprietary attribute \"charset\"", - \ "<meta> lacks \"content\" attribute", - \ "inserting \"type\" attribute", - \ "proprietary attribute \"data-" - \] - -function! s:ValidateError(text) - let valid = 0 - for i in s:ignore_html_errors - if stridx(a:text, i) != -1 - let valid = 1 - break - endif - endfor - return valid -endfunction - - -function! SyntaxCheckers_html_GetLocList() - - let encopt = s:TidyEncOptByFenc() - let makeprg="tidy ".encopt." --new-blocklevel-tags ".shellescape('section, article, aside, hgroup, header, footer, nav, figure, figcaption')." --new-inline-tags ".shellescape('video, audio, embed, mark, progress, meter, time, ruby, rt, rp, canvas, command, details, datalist')." --new-empty-tags ".shellescape('wbr, keygen')." -e ".shellescape(expand('%'))." 2>&1" - let errorformat='%Wline %l column %c - Warning: %m,%Eline %l column %c - Error: %m,%-G%.%#,%-G%.%#' - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - " process loclist since we need to add some info and filter out valid HTML5 - " from the errors - let n = len(loclist) - 1 - let bufnum = bufnr("") - while n >= 0 - let i = loclist[n] - " filter out valid HTML5 - if s:ValidateError(i['text']) == 1 - unlet loclist[n] - else - "the file name isnt in the output so stick in the buf num manually - let i['bufnr'] = bufnum - endif - let n -= 1 - endwhile - - return loclist -endfunction diff --git a/vim/syntax_checkers/javascript.vim b/vim/syntax_checkers/javascript.vim deleted file mode 100644 index 026c737..0000000 --- a/vim/syntax_checkers/javascript.vim +++ /dev/null @@ -1,23 +0,0 @@ -"============================================================================ -"File: javascript.vim -"Description: Figures out which javascript syntax checker (if any) to load -" from the javascript directory. -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -" Use g:syntastic_javascript_checker option to specify which jslint executable -" should be used (see below for a list of supported checkers). -" If g:syntastic_javascript_checker is not set, just use the first syntax -" checker that we find installed. -"============================================================================ -if exists("loaded_javascript_syntax_checker") - finish -endif -let loaded_javascript_syntax_checker = 1 - -let s:supported_checkers = ["gjslint", "jslint", "jsl", "jshint"] -call SyntasticLoadChecker(s:supported_checkers) diff --git a/vim/syntax_checkers/javascript/gjslint.vim b/vim/syntax_checkers/javascript/gjslint.vim deleted file mode 100644 index 05e1c0f..0000000 --- a/vim/syntax_checkers/javascript/gjslint.vim +++ /dev/null @@ -1,20 +0,0 @@ -"============================================================================ -"File: gjslint.vim -"Description: Javascript syntax checker - using gjslint -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ -if !exists("g:syntastic_javascript_gjslint_conf") - let g:syntastic_javascript_gjslint_conf = "" -endif - -function! SyntaxCheckers_javascript_GetLocList() - let makeprg = "gjslint " . g:syntastic_javascript_gjslint_conf . " --nosummary --unix_mode --nodebug_indentation --nobeep " . shellescape(expand('%')) - let errorformat="%f:%l:(New Error -%\\?\%n) %m,%f:%l:(-%\\?%n) %m,%-G1 files checked, no errors found.,%-G%.%#" - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction - diff --git a/vim/syntax_checkers/javascript/jshint.vim b/vim/syntax_checkers/javascript/jshint.vim deleted file mode 100644 index 164b7bd..0000000 --- a/vim/syntax_checkers/javascript/jshint.vim +++ /dev/null @@ -1,21 +0,0 @@ -"============================================================================ -"File: jshint.vim -"Description: Javascript syntax checker - using jshint -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ -if !exists("g:syntastic_javascript_jshint_conf") - let g:syntastic_javascript_jshint_conf = "" -endif - -function! SyntaxCheckers_javascript_GetLocList() - " node-jshint uses .jshintrc as config unless --config arg is present - let args = !empty(g:syntastic_javascript_jshint_conf) ? ' --config ' . g:syntastic_javascript_jshint_conf : '' - let makeprg = 'jshint ' . shellescape(expand("%")) . args - let errorformat = '%ELine %l:%c,%Z\\s%#Reason: %m,%C%.%#,%f: line %l\, col %c\, %m,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr('')} }) -endfunction diff --git a/vim/syntax_checkers/javascript/jsl.vim b/vim/syntax_checkers/javascript/jsl.vim deleted file mode 100644 index 36c7efc..0000000 --- a/vim/syntax_checkers/javascript/jsl.vim +++ /dev/null @@ -1,20 +0,0 @@ -"============================================================================ -"File: jsl.vim -"Description: Javascript syntax checker - using jsl -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ -if !exists("g:syntastic_javascript_jsl_conf") - let g:syntastic_javascript_jsl_conf = "" -endif - -function! SyntaxCheckers_javascript_GetLocList() - let makeprg = "jsl " . g:syntastic_javascript_jsl_conf . " -nologo -nofilelisting -nosummary -nocontext -process ".shellescape(expand('%')) - let errorformat='%W%f(%l): lint warning: %m,%-Z%p^,%W%f(%l): warning: %m,%-Z%p^,%E%f(%l): SyntaxError: %m,%-Z%p^,%-G' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction - diff --git a/vim/syntax_checkers/javascript/jslint.vim b/vim/syntax_checkers/javascript/jslint.vim deleted file mode 100644 index 94d48f0..0000000 --- a/vim/syntax_checkers/javascript/jslint.vim +++ /dev/null @@ -1,31 +0,0 @@ -"============================================================================ -"File: jslint.vim -"Description: Javascript syntax checker - using jslint -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"Tested with jslint 0.1.4. -"============================================================================ -if !exists("g:syntastic_javascript_jslint_conf") - let g:syntastic_javascript_jslint_conf = "--white --undef --nomen --regexp --plusplus --bitwise --newcap --sloppy --vars" -endif - -function! SyntaxCheckers_javascript_HighlightTerm(error) - let unexpected = matchstr(a:error['text'], 'Expected.*and instead saw \'\zs.*\ze\'') - if len(unexpected) < 1 | return '' | end - return '\V'.split(unexpected, "'")[1] -endfunction - -function! SyntaxCheckers_javascript_GetLocList() - let makeprg = "jslint " . g:syntastic_javascript_jslint_conf . " " . shellescape(expand('%')) - let errorformat='%E %##%n %m,%-Z%.%#Line %l\, Pos %c,%-G%.%#' - let errors = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr("")} }) - call SyntasticHighlightErrors(errors, function('SyntaxCheckers_javascript_HighlightTerm')) - - return errors -endfunction - diff --git a/vim/syntax_checkers/json.vim b/vim/syntax_checkers/json.vim deleted file mode 100644 index 2d2652d..0000000 --- a/vim/syntax_checkers/json.vim +++ /dev/null @@ -1,23 +0,0 @@ -"============================================================================ -"File: json.vim -"Description: Figures out which json syntax checker (if any) to load -" from the json directory. -"Maintainer: Miller Medeiros <contact at millermedeiros dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -" Use g:syntastic_json_checker option to specify which jsonlint executable -" should be used (see below for a list of supported checkers). -" If g:syntastic_json_checker is not set, just use the first syntax -" checker that we find installed. -"============================================================================ -if exists("loaded_json_syntax_checker") - finish -endif -let loaded_json_syntax_checker = 1 - -let s:supported_checkers = ["jsonlint", "jsonval"] -call SyntasticLoadChecker(s:supported_checkers) diff --git a/vim/syntax_checkers/json/jsonlint.vim b/vim/syntax_checkers/json/jsonlint.vim deleted file mode 100644 index 6e4a4c0..0000000 --- a/vim/syntax_checkers/json/jsonlint.vim +++ /dev/null @@ -1,16 +0,0 @@ -"============================================================================ -"File: jsonlint.vim -"Description: JSON syntax checker - using jsonlint -"Maintainer: Miller Medeiros <contact at millermedeiros dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ - -function! SyntaxCheckers_json_GetLocList() - let makeprg = 'jsonlint ' . shellescape(expand("%")) . ' --compact' - let errorformat = '%ELine %l:%c,%Z\\s%#Reason: %m,%C%.%#,%f: line %l\, col %c\, %m,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr('')} }) -endfunction diff --git a/vim/syntax_checkers/json/jsonval.vim b/vim/syntax_checkers/json/jsonval.vim deleted file mode 100644 index f288039..0000000 --- a/vim/syntax_checkers/json/jsonval.vim +++ /dev/null @@ -1,17 +0,0 @@ -"============================================================================ -"File: jsonval.vim -"Description: JSON syntax checker - using jsonval -"Maintainer: Miller Medeiros <contact at millermedeiros dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -"============================================================================ - -function! SyntaxCheckers_json_GetLocList() - " based on https://gist.github.com/1196345 - let makeprg = 'jsonval '. shellescape(expand('%')) - let errorformat = '%E%f:\ %m\ at\ line\ %l,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr('')} }) -endfunction diff --git a/vim/syntax_checkers/less.vim b/vim/syntax_checkers/less.vim deleted file mode 100644 index 1338ffd..0000000 --- a/vim/syntax_checkers/less.vim +++ /dev/null @@ -1,38 +0,0 @@ -"============================================================================ -"File: less.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Julien Blanchard <julien at sideburns dot eu> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_less_syntax_checker") - finish -endif -let loaded_less_syntax_checker = 1 - -"bail if the user doesnt have the lessc binary installed -if !executable("lessc") - finish -endif - -if !exists("g:syntastic_less_options") - let g:syntastic_less_options = "--no-color" -endif - -function! SyntaxCheckers_less_GetLocList() - let makeprg = 'lessc '. g:syntastic_less_options .' '. shellescape(expand('%')) . ' /dev/null' - - "lessc >= 1.2 - let errorformat = '%m in %f:%l:%c' - "lessc < 1.2 - let errorformat .= ', Syntax %trror on line %l in %f,Syntax %trror on line %l,! Syntax %trror: on line %l: %m,%-G%.%#' - - return SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat, - \ 'defaults': {'bufnr': bufnr(""), 'text': "Syntax error"} }) -endfunction - diff --git a/vim/syntax_checkers/lua.vim b/vim/syntax_checkers/lua.vim deleted file mode 100644 index 03acb08..0000000 --- a/vim/syntax_checkers/lua.vim +++ /dev/null @@ -1,58 +0,0 @@ -"============================================================================ -"File: lua.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Gregor Uhlenheuer <kongo2002 at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists('loaded_lua_syntax_checker') - finish -endif -let loaded_lua_syntax_checker = 1 - -" check if the lua compiler is installed -if !executable('luac') - finish -endif - -function! SyntaxCheckers_lua_Term(pos) - let near = matchstr(a:pos['text'], "near '[^']\\+'") - let result = '' - if len(near) > 0 - let near = split(near, "'")[1] - if near == '<eof>' - let p = getpos('$') - let a:pos['lnum'] = p[1] - let a:pos['col'] = p[2] - let result = '\%'.p[2].'c' - else - let result = '\V'.near - endif - let open = matchstr(a:pos['text'], "(to close '[^']\\+' at line [0-9]\\+)") - if len(open) > 0 - let oline = split(open, "'")[1:2] - let line = 0+strpart(oline[1], 9) - call matchadd('SpellCap', '\%'.line.'l\V'.oline[0]) - endif - endif - return result -endfunction - -function! SyntaxCheckers_lua_GetLocList() - let makeprg = 'luac -p ' . shellescape(expand('%')) - let errorformat = 'luac: %#%f:%l: %m' - - let loclist = SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat, - \ 'defaults': { 'bufnr': bufnr(''), 'type': 'E' } }) - - call SyntasticHighlightErrors(loclist, function("SyntaxCheckers_lua_Term")) - - return loclist -endfunction - diff --git a/vim/syntax_checkers/matlab.vim b/vim/syntax_checkers/matlab.vim deleted file mode 100644 index 595b312..0000000 --- a/vim/syntax_checkers/matlab.vim +++ /dev/null @@ -1,28 +0,0 @@ -"============================================================================ -"File: matlab.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Jason Graham <jason at the-graham dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists("loaded_matlab_syntax_checker") - finish -endif -let loaded_matlab_syntax_checker = 1 - -"bail if the user doesn't have mlint installed -if !executable("mlint") - finish -endif - -function! SyntaxCheckers_matlab_GetLocList() - let makeprg = 'mlint -id $* '.shellescape(expand('%')) - let errorformat = 'L %l (C %c): %*[a-zA-Z0-9]: %m,L %l (C %c-%*[0-9]): %*[a-zA-Z0-9]: %m' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr("")} }) -endfunction - diff --git a/vim/syntax_checkers/ocaml.vim b/vim/syntax_checkers/ocaml.vim deleted file mode 100644 index 6a2470f..0000000 --- a/vim/syntax_checkers/ocaml.vim +++ /dev/null @@ -1,89 +0,0 @@ -"============================================================================ -"File: ocaml.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Török Edwin <edwintorok at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -" -" By default the camlp4o preprocessor is used to check the syntax of .ml, and .mli files, -" ocamllex is used to check .mll files and menhir is used to check .mly files. -" The output is all redirected to /dev/null, nothing is written to the disk. -" -" If your source code needs camlp4r then you can define this in your .vimrc: -" -" let g:syntastic_ocaml_camlp4r = 1 -" -" If you used some syntax extensions, or you want to also typecheck the source -" code, then you can define this: -" -" let g:syntastic_ocaml_use_ocamlbuild = 1 -" -" This will run ocamlbuild <name>.inferred.mli, so it will write to your _build -" directory (and possibly rebuild your myocamlbuild.ml plugin), only enable this -" if you are ok with that. -" -" If you are using syntax extensions / external libraries and have a properly -" set up _tags (and myocamlbuild.ml file) then it should just work -" to enable this flag and get syntax / type checks through syntastic. -" -" For best results your current directory should be the project root -" (same situation if you want useful output from :make). - -if exists("loaded_ocaml_syntax_checker") - finish -endif -let loaded_ocaml_syntax_checker = 1 - -if exists('g:syntastic_ocaml_camlp4r') && - \ g:syntastic_ocaml_camlp4r != 0 - let s:ocamlpp="camlp4r" -else - let s:ocamlpp="camlp4o" -endif - -"bail if the user doesnt have the preprocessor -if !executable(s:ocamlpp) - finish -endif - -function! SyntaxCheckers_ocaml_GetLocList() - if exists('g:syntastic_ocaml_use_ocamlbuild') && - \ g:syntastic_ocaml_use_ocamlbuild != 0 && - \ executable("ocamlbuild") && - \ isdirectory('_build') - let makeprg = "ocamlbuild -quiet -no-log -tag annot,". s:ocamlpp. " -no-links -no-hygiene -no-sanitize ". - \ shellescape(expand('%:r')).".cmi" - else - let extension = expand('%:e') - if match(extension, 'mly') >= 0 - " ocamlyacc output can't be redirected, so use menhir - if !executable("menhir") - return [] - endif - let makeprg = "menhir --only-preprocess ".shellescape(expand('%')) . " >/dev/null" - elseif match(extension,'mll') >= 0 - if !executable("ocamllex") - return [] - endif - let makeprg = "ocamllex -q -o /dev/null ".shellescape(expand('%')) - else - let makeprg = "camlp4o -o /dev/null ".shellescape(expand('%')) - endif - endif - let errorformat = '%AFile "%f"\, line %l\, characters %c-%*\d:,'. - \ '%AFile "%f"\, line %l\, characters %c-%*\d (end at line %*\d\, character %*\d):,'. - \ '%AFile "%f"\, line %l\, character %c:,'. - \ '%AFile "%f"\, line %l\, character %c:%m,'. - \ '%-GPreprocessing error %.%#,'. - \ '%-GCommand exited %.%#,'. - \ '%C%tarning %n: %m,'. - \ '%C%m,'. - \ '%-G+%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/perl.vim b/vim/syntax_checkers/perl.vim deleted file mode 100644 index e8aa577..0000000 --- a/vim/syntax_checkers/perl.vim +++ /dev/null @@ -1,29 +0,0 @@ -"============================================================================ -"File: perl.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Anthony Carapetis <anthony.carapetis at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_perl_syntax_checker") - finish -endif -let loaded_perl_syntax_checker = 1 - -"bail if the user doesnt have perl installed -if !executable("perl") - finish -endif - -let s:checker = 'perl ' . shellescape(expand('<sfile>:p:h') . '/efm_perl.pl') . ' -c' - -function! SyntaxCheckers_perl_GetLocList() - let makeprg = s:checker . ' ' . shellescape(expand('%')) - let errorformat = '%f:%l:%m' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/php.vim b/vim/syntax_checkers/php.vim deleted file mode 100644 index 4f22f91..0000000 --- a/vim/syntax_checkers/php.vim +++ /dev/null @@ -1,58 +0,0 @@ -"============================================================================ -"File: php.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_php_syntax_checker") - finish -endif -let loaded_php_syntax_checker = 1 - -"bail if the user doesnt have php installed -if !executable("php") - finish -endif - -"Support passing configuration directives to phpcs -if !exists("g:syntastic_phpcs_conf") - let g:syntastic_phpcs_conf = "" -endif - -if !exists("g:syntastic_phpcs_disable") - let g:syntastic_phpcs_disable = 0 -endif - -function! SyntaxCheckers_php_Term(item) - let unexpected = matchstr(a:item['text'], "unexpected '[^']\\+'") - if len(unexpected) < 1 | return '' | end - return '\V'.split(unexpected, "'")[1] -endfunction - -function! SyntaxCheckers_php_GetLocList() - - let errors = [] - - let makeprg = "php -l ".shellescape(expand('%')) - let errorformat='%-GNo syntax errors detected in%.%#,PHP Parse error: %#syntax %trror\, %m in %f on line %l,PHP Fatal %trror: %m in %f on line %l,%-GErrors parsing %.%#,%-G\s%#,Parse error: %#syntax %trror\, %m in %f on line %l,Fatal %trror: %m in %f on line %l' - let errors = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - if empty(errors) && !g:syntastic_phpcs_disable && executable("phpcs") - let errors = errors + s:GetPHPCSErrors() - endif - - call SyntasticHighlightErrors(errors, function('SyntaxCheckers_php_Term')) - - return errors -endfunction - -function! s:GetPHPCSErrors() - let makeprg = "phpcs " . g:syntastic_phpcs_conf . " --report=csv ".shellescape(expand('%')) - let errorformat = '%-GFile\,Line\,Column\,Type\,Message\,Source\,Severity,"%f"\,%l\,%c\,%t%*[a-zA-Z]\,"%m"\,%*[a-zA-Z0-9_.-]\,%*[0-9]' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'subtype': 'Style' }) -endfunction diff --git a/vim/syntax_checkers/puppet.vim b/vim/syntax_checkers/puppet.vim deleted file mode 100644 index 51c898e..0000000 --- a/vim/syntax_checkers/puppet.vim +++ /dev/null @@ -1,54 +0,0 @@ -"============================================================================ -"File: puppet.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Eivind Uggedal <eivind at uggedal dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_puppet_syntax_checker") - finish -endif -let loaded_puppet_syntax_checker = 1 - -"bail if the user doesnt have puppet installed -if !executable("puppet") - finish -endif - -function! s:ExtractVersion() - let output = system("puppet --version") - let output = substitute(output, '\n$', '', '') - return split(output, '\.') -endfunction - -let s:puppetVersion = s:ExtractVersion() - -function! SyntaxCheckers_puppet_GetLocList() - "If puppet is >= version 2.7 then use the new executable - if s:puppetVersion[0] >= '2' && s:puppetVersion[1] >= '7' - let makeprg = 'puppet parser validate ' . - \ shellescape(expand('%')) . - \ ' --color=false' . - \ ' --storeconfigs' - - "add --ignoreimport for versions < 2.7.10 - if s:puppetVersion[2] < '10' - let makeprg .= ' --ignoreimport' - endif - - else - let makeprg = 'puppet --color=false --parseonly --ignoreimport '.shellescape(expand('%')) - endif - - "some versions of puppet (e.g. 2.7.10) output the message below if there - "are any syntax errors - let errorformat = '%-Gerr: Try ''puppet help parser validate'' for usage,' - - let errorformat .= 'err: Could not parse for environment %*[a-z]: %m at %f:%l' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/python.vim b/vim/syntax_checkers/python.vim deleted file mode 100644 index a20539b..0000000 --- a/vim/syntax_checkers/python.vim +++ /dev/null @@ -1,80 +0,0 @@ -"============================================================================ -"File: python.vim -"Description: Syntax checking plugin for syntastic.vim -" -"Authors: Martin Grenfell <martin.grenfell@gmail.com> -" kstep <me@kstep.me> -" Parantapa Bhattacharya <parantapa@gmail.com> -" -"============================================================================ -" -" For forcing the use of flake8, pyflakes, or pylint set -" -" let g:syntastic_python_checker = 'pyflakes' -" -" in your .vimrc. Default is flake8. - -if exists("loaded_python_syntax_checker") - finish -endif -let loaded_python_syntax_checker = 1 - -"bail if the user doesnt have his favorite checker or flake8 or pyflakes installed -if !exists('g:syntastic_python_checker') || !executable(g:syntastic_python_checker) - if executable("flake8") - let g:syntastic_python_checker = 'flake8' - elseif executable("pyflakes") - let g:syntastic_python_checker = 'pyflakes' - elseif executable("pylint") - let g:syntastic_python_checker = 'pylint' - else - finish - endif -endif -if !exists('g:syntastic_python_checker_args') - let g:syntastic_python_checker_args = '' -endif - -function! SyntaxCheckers_python_Term(i) - if a:i['type'] ==# 'E' - let a:i['text'] = "Syntax error" - endif - if match(a:i['text'], 'is assigned to but never used') > -1 - \ || match(a:i['text'], 'imported but unused') > -1 - \ || match(a:i['text'], 'undefined name') > -1 - \ || match(a:i['text'], 'redefinition of') > -1 - \ || match(a:i['text'], 'referenced before assignment') > -1 - \ || match(a:i['text'], 'duplicate argument') > -1 - \ || match(a:i['text'], 'after other statements') > -1 - \ || match(a:i['text'], 'shadowed by loop variable') > -1 - - let term = split(a:i['text'], "'", 1)[1] - return '\V\<'.term.'\>' - endif - return '' -endfunction - -if g:syntastic_python_checker == 'pylint' - function! SyntaxCheckers_python_GetLocList() - let makeprg = 'pylint -f parseable -r n -i y ' . - \ shellescape(expand('%')) . - \ ' \| sed ''s_: \[[RC]_: \[W_''' . - \ ' \| sed ''s_: \[[F]_:\ \[E_''' - let errorformat = '%f:%l: [%t%n] %m,%-GNo config%m' - let errors = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - return errors - endfunction -else - function! SyntaxCheckers_python_GetLocList() - let makeprg = g:syntastic_python_checker.' '.g:syntastic_python_checker_args.' '.shellescape(expand('%')) - let errorformat = - \ '%E%f:%l: could not compile,%-Z%p^,%W%f:%l:%c: %m,%W%f:%l: %m,%-G%.%#' - - let errors = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - call SyntasticHighlightErrors(errors, function('SyntaxCheckers_python_Term')) - - return errors - endfunction -endif diff --git a/vim/syntax_checkers/rst.vim b/vim/syntax_checkers/rst.vim deleted file mode 100644 index 107aafe..0000000 --- a/vim/syntax_checkers/rst.vim +++ /dev/null @@ -1,37 +0,0 @@ -"============================================================================ -"File: rst.vim -"Description: Syntax checking plugin for docutil's reStructuredText files -"Maintainer: James Rowe <jnrowe at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" We use rst2pseudoxml.py, as it is ever so marginally faster than the other -" rst2${x} tools in docutils. - -if exists("loaded_rst_syntax_checker") - finish -endif -let loaded_rst_syntax_checker = 1 - -"bail if the user doesn't have rst2pseudoxml.py installed -if !executable("rst2pseudoxml.py") - finish -endif - -function! SyntaxCheckers_rst_GetLocList() - let makeprg = 'rst2pseudoxml.py --report=1 --exit-status=1 ' . - \ shellescape(expand('%')) . ' /dev/null' - - let errorformat = '%f:%l:\ (%tNFO/1)\ %m, - \%f:%l:\ (%tARNING/2)\ %m, - \%f:%l:\ (%tRROR/3)\ %m, - \%f:%l:\ (%tEVERE/4)\ %m, - \%-G%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/ruby.vim b/vim/syntax_checkers/ruby.vim deleted file mode 100644 index 8c3cd81..0000000 --- a/vim/syntax_checkers/ruby.vim +++ /dev/null @@ -1,32 +0,0 @@ -"============================================================================ -"File: ruby.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_ruby_syntax_checker") - finish -endif -let loaded_ruby_syntax_checker = 1 - -"bail if the user doesnt have ruby installed -if !executable("ruby") - finish -endif - -function! SyntaxCheckers_ruby_GetLocList() - " we cannot set RUBYOPT on windows like that - if has('win32') || has('win64') - let makeprg = 'ruby -W1 -T1 -c '.shellescape(expand('%')) - else - let makeprg = 'RUBYOPT= ruby -W1 -c '.shellescape(expand('%')) - endif - let errorformat = '%-GSyntax OK,%E%f:%l: syntax error\, %m,%Z%p^,%W%f:%l: warning: %m,%Z%p^,%W%f:%l: %m,%-C%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/rust.vim b/vim/syntax_checkers/rust.vim deleted file mode 100644 index fef48e8..0000000 --- a/vim/syntax_checkers/rust.vim +++ /dev/null @@ -1,33 +0,0 @@ -"============================================================================ -"File: rust.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Chad Jablonski <chad.jablonski at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_rust_syntax_checker") - finish -endif -let loaded_rust_syntax_checker = 1 - -"bail if the user doesnt have rustc installed -if !executable("rustc") - finish -endif - -function! SyntaxCheckers_rust_GetLocList() - let makeprg = 'rustc --parse-only '.shellescape(expand('%')) - - let errorformat = '%E%f:%l:%c: \\d%#:\\d%# %.%\{-}error:%.%\{-} %m,' . - \ '%W%f:%l:%c: \\d%#:\\d%# %.%\{-}warning:%.%\{-} %m,' . - \ '%C%f:%l %m,' . - \ '%-Z%.%#' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction - - diff --git a/vim/syntax_checkers/sass.vim b/vim/syntax_checkers/sass.vim deleted file mode 100644 index 23bf345..0000000 --- a/vim/syntax_checkers/sass.vim +++ /dev/null @@ -1,35 +0,0 @@ -"============================================================================ -"File: sass.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_sass_syntax_checker") - finish -endif -let loaded_sass_syntax_checker = 1 - -"bail if the user doesnt have the sass binary installed -if !executable("sass") - finish -endif - -"use compass imports if available -let s:imports = "" -if executable("compass") - let s:imports = "--compass" -endif - -function! SyntaxCheckers_sass_GetLocList() - let makeprg='sass '.s:imports.' --check '.shellescape(expand('%')) - let errorformat = '%ESyntax %trror:%m,%C on line %l of %f,%Z%.%#' - let errorformat .= ',%Wwarning on line %l:,%Z%m,Syntax %trror on line %l: %m' - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - return loclist -endfunction diff --git a/vim/syntax_checkers/scss.vim b/vim/syntax_checkers/scss.vim deleted file mode 100644 index d3ae5e7..0000000 --- a/vim/syntax_checkers/scss.vim +++ /dev/null @@ -1,27 +0,0 @@ - -"============================================================================ -"File: scss.vim -"Description: scss syntax checking plugin for syntastic -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_scss_syntax_checker") - finish -endif -let loaded_scss_syntax_checker = 1 - -"bail if the user doesnt have the sass binary installed -if !executable("sass") - finish -endif - -runtime syntax_checkers/sass.vim - -function! SyntaxCheckers_scss_GetLocList() - return SyntaxCheckers_sass_GetLocList() -endfunction diff --git a/vim/syntax_checkers/sh.vim b/vim/syntax_checkers/sh.vim deleted file mode 100644 index 5b55172..0000000 --- a/vim/syntax_checkers/sh.vim +++ /dev/null @@ -1,52 +0,0 @@ -"============================================================================ -"File: sh.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Gregor Uhlenheuer <kongo2002 at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists('loaded_sh_syntax_checker') - finish -endif -let loaded_sh_syntax_checker = 1 - -function! s:GetShell() - if !exists('b:shell') || b:shell == "" - let b:shell = '' - let shebang = getbufline(bufnr('%'), 1)[0] - if len(shebang) > 0 - if match(shebang, 'bash') >= 0 - let b:shell = 'bash' - elseif match(shebang, 'zsh') >= 0 - let b:shell = 'zsh' - elseif match(shebang, 'sh') >= 0 - let b:shell = 'sh' - endif - endif - endif - return b:shell -endfunction - -function! SyntaxCheckers_sh_GetLocList() - if len(s:GetShell()) == 0 || !executable(s:GetShell()) - return [] - endif - let output = split(system(s:GetShell().' -n '.shellescape(expand('%'))), '\n') - if v:shell_error != 0 - let result = [] - for err_line in output - let line = substitute(err_line, '^[^:]*:\D\{-}\(\d\+\):.*', '\1', '') - let msg = substitute(err_line, '^[^:]*:\D\{-}\d\+: \(.*\)', '\1', '') - call add(result, {'lnum' : line, - \ 'text' : msg, - \ 'bufnr': bufnr(''), - \ 'type': 'E' }) - endfor - return result - endif - return [] -endfunction diff --git a/vim/syntax_checkers/tcl.vim b/vim/syntax_checkers/tcl.vim deleted file mode 100644 index 83b5df3..0000000 --- a/vim/syntax_checkers/tcl.vim +++ /dev/null @@ -1,28 +0,0 @@ -"============================================================================ -"File: tcl.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Eric Thomas <eric.l.m.thomas at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists("loaded_tcl_syntax_checker") - finish -endif -let loaded_tcl_syntax_checker = 1 - -"bail if the user doesnt have tclsh installed -if !executable("tclsh") - finish -endif - -function! SyntaxCheckers_tcl_GetLocList() - let makeprg = 'tclsh '.shellescape(expand('%')) - let errorformat = '%f:%l:%m' - - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/tex.vim b/vim/syntax_checkers/tex.vim deleted file mode 100644 index 4369f4c..0000000 --- a/vim/syntax_checkers/tex.vim +++ /dev/null @@ -1,26 +0,0 @@ -"============================================================================ -"File: tex.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_tex_syntax_checker") - finish -endif -let loaded_tex_syntax_checker = 1 - -"bail if the user doesnt have lacheck installed -if !executable("lacheck") - finish -endif - -function! SyntaxCheckers_tex_GetLocList() - let makeprg = 'lacheck '.shellescape(expand('%')) - let errorformat = '%-G** %f:,%E"%f"\, line %l: %m' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction diff --git a/vim/syntax_checkers/vala.vim b/vim/syntax_checkers/vala.vim deleted file mode 100644 index f174790..0000000 --- a/vim/syntax_checkers/vala.vim +++ /dev/null @@ -1,56 +0,0 @@ -"============================================================================ -"File: vala.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Konstantin Stepanov (me@kstep.me) -"Notes: Add special comment line into your vala file starting with -" "// modules: " and containing space delimited list of vala -" modules, used by the file, so this script can build correct -" --pkg arguments. -" Valac compiler is not the fastest thing in the world, so you -" may want to disable this plugin with -" let g:syntastic_vala_check_disabled = 1 command in your .vimrc or -" command line. Unlet this variable to set it to 0 to reenable -" this checker. -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -if exists('loaded_vala_syntax_checker') - finish -endif -let loaded_vala_syntax_checker = 1 - -if !executable('valac') - finish -endif - -if exists('g:syntastic_vala_check_disabled') && g:syntastic_vala_check_disabled - finish -endif - -function! SyntaxCheckers_vala_Term(pos) - let strlength = strlen(matchstr(a:pos['text'], '\^\+$')) - return '\%>'.(a:pos.col-1).'c.*\%<'.(a:pos.col+strlength+1).'c' -endfunction - -function! s:GetValaModules() - let modules_line = search('^// modules: ', 'n') - let modules_str = getline(modules_line) - let modules = split(strpart(modules_str, 12), '\s\+') - return modules -endfunction - -function! SyntaxCheckers_vala_GetLocList() - let vala_pkg_args = join(map(s:GetValaModules(), '"--pkg ".v:val'), ' ') - let makeprg = 'valac -C ' . vala_pkg_args . ' ' .shellescape(expand('%')) - let errorformat = '%A%f:%l.%c-%\d%\+.%\d%\+: %t%[a-z]%\+: %m,%C%m,%Z%m' - - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - call SyntasticHighlightErrors(loclist, function("SyntaxCheckers_vala_Term"), 1) - return loclist -endfunction - diff --git a/vim/syntax_checkers/xhtml.vim b/vim/syntax_checkers/xhtml.vim deleted file mode 100644 index 80d981a..0000000 --- a/vim/syntax_checkers/xhtml.vim +++ /dev/null @@ -1,46 +0,0 @@ -"============================================================================ -"File: xhtml.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_xhtml_syntax_checker") - finish -endif -let loaded_xhtml_syntax_checker = 1 - -"bail if the user doesnt have tidy or grep installed -if !executable("tidy") - finish -endif - -" TODO: join this with html.vim DRY's sake? -function! s:TidyEncOptByFenc() - let tidy_opts = { - \'utf-8' : '-utf8', - \'ascii' : '-ascii', - \'latin1' : '-latin1', - \'iso-2022-jp' : '-iso-2022', - \'cp1252' : '-win1252', - \'macroman' : '-mac', - \'utf-16le' : '-utf16le', - \'utf-16' : '-utf16', - \'big5' : '-big5', - \'sjis' : '-shiftjis', - \'cp850' : '-ibm858', - \} - return get(tidy_opts, &fileencoding, '-utf8') -endfunction - -function! SyntaxCheckers_xhtml_GetLocList() - - let encopt = s:TidyEncOptByFenc() - let makeprg="tidy ".encopt." -xml -e ".shellescape(expand('%')) - let errorformat='%Wline %l column %c - Warning: %m,%Eline %l column %c - Error: %m,%-G%.%#,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat, 'defaults': {'bufnr': bufnr("")} }) -endfunction diff --git a/vim/syntax_checkers/xml.vim b/vim/syntax_checkers/xml.vim deleted file mode 100644 index 55c0cdd..0000000 --- a/vim/syntax_checkers/xml.vim +++ /dev/null @@ -1,42 +0,0 @@ -"============================================================================ -"File: xml.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Sebastian Kusnier <sebastian at kusnier dot net> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" You can use a local installation of DTDs to significantly speed up validation -" and allow you to validate XML data without network access, see xmlcatalog(1) -" and http://www.xmlsoft.org/catalog.html for more information. - -if exists("loaded_xml_syntax_checker") - finish -endif -let loaded_xml_syntax_checker = 1 - -"bail if the user doesnt have tidy or grep installed -if !executable("xmllint") - finish -endif - -function! SyntaxCheckers_xml_GetLocList() - - let makeprg="xmllint --xinclude --noout --postvalid " . shellescape(expand("%:p")) - let errorformat='%E%f:%l:\ error\ :\ %m, - \%-G%f:%l:\ validity\ error\ :\ Validation\ failed:\ no\ DTD\ found\ %m, - \%W%f:%l:\ warning\ :\ %m, - \%W%f:%l:\ validity\ warning\ :\ %m, - \%E%f:%l:\ validity\ error\ :\ %m, - \%E%f:%l:\ parser\ error\ :\ %m, - \%E%f:%l:\ %m, - \%-Z%p^, - \%-G%.%#' - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - return loclist -endfunction diff --git a/vim/syntax_checkers/xslt.vim b/vim/syntax_checkers/xslt.vim deleted file mode 100644 index b9b3cac..0000000 --- a/vim/syntax_checkers/xslt.vim +++ /dev/null @@ -1,38 +0,0 @@ -"============================================================================ -"File: xslt.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Sebastian Kusnier <sebastian at kusnier dot net> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ -if exists("loaded_xslt_syntax_checker") - finish -endif -let loaded_xslt_syntax_checker = 1 - -"bail if the user doesnt have tidy or grep installed -if !executable("xmllint") - finish -endif - -function! SyntaxCheckers_xslt_GetLocList() - - let makeprg="xmllint --xinclude --noout --postvalid " . shellescape(expand("%:p")) - let errorformat='%E%f:%l:\ error\ :\ %m, - \%-G%f:%l:\ validity\ error\ :\ Validation\ failed:\ no\ DTD\ found\ %m, - \%W%f:%l:\ warning\ :\ %m, - \%W%f:%l:\ validity\ warning\ :\ %m, - \%E%f:%l:\ validity\ error\ :\ %m, - \%E%f:%l:\ parser\ error\ :\ %m, - \%E%f:%l:\ namespace\ error\ :\ %m, - \%E%f:%l:\ %m, - \%-Z%p^, - \%-G%.%#' - let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) - - return loclist -endfunction diff --git a/vim/syntax_checkers/yaml.vim b/vim/syntax_checkers/yaml.vim deleted file mode 100644 index f45d849..0000000 --- a/vim/syntax_checkers/yaml.vim +++ /dev/null @@ -1,30 +0,0 @@ -"============================================================================ -"File: yaml.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -" -"Installation: $ npm install -g js-yaml.bin -" -"============================================================================ -if exists("loaded_yaml_syntax_checker") - finish -endif -let loaded_yaml_syntax_checker = 1 - -if !executable("js-yaml") - finish -endif - -function! SyntaxCheckers_yaml_GetLocList() - let makeprg='js-yaml --compact ' . shellescape(expand('%')) - let errorformat='Error on line %l\, col %c:%m,%-G%.%#' - return SyntasticMake({ 'makeprg': makeprg, - \ 'errorformat': errorformat, - \ 'defaults': {'bufnr': bufnr("")} }) -endfunction diff --git a/vim/syntax_checkers/zpt.vim b/vim/syntax_checkers/zpt.vim deleted file mode 100644 index 0b0063b..0000000 --- a/vim/syntax_checkers/zpt.vim +++ /dev/null @@ -1,36 +0,0 @@ -"============================================================================ -"File: zpt.vim -"Description: Syntax checking plugin for syntastic.vim -"Maintainer: claytron <robots at claytron dot com> -"License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -"============================================================================ - -" In order for this plugin to be useful, you will need to set up the -" zpt filetype in your vimrc -" -" " set up zope page templates as the zpt filetype -" au BufNewFile,BufRead *.pt,*.cpt,*.zpt set filetype=zpt syntax=xml -" -" Then install the zptlint program, found on pypi: -" http://pypi.python.org/pypi/zptlint - -if exists("loaded_zpt_syntax_checker") - finish -endif -let loaded_zpt_syntax_checker = 1 - -" Bail if the user doesn't have zptlint installed -if !executable("zptlint") - finish -endif - -function! SyntaxCheckers_zpt_GetLocList() - let makeprg="zptlint ".shellescape(expand('%')) - let errorformat='%-P*** Error in: %f,%Z%*\s\, at line %l\, column %c,%E%*\s%m,%-Q' - return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) -endfunction |