diff options
Diffstat (limited to 'files/.vim/plugin')
| -rw-r--r-- | files/.vim/plugin/CSApprox.vim | 987 | ||||
| -rw-r--r-- | files/.vim/plugin/SyntaxFolds.vim | 323 | ||||
| -rwxr-xr-x | files/.vim/plugin/XMLFolding.vim | 105 | ||||
| -rw-r--r-- | files/.vim/plugin/filebrowser.vim | 251 | ||||
| -rw-r--r-- | files/.vim/plugin/imaps.vim | 831 | ||||
| -rw-r--r-- | files/.vim/plugin/libList.vim | 249 | ||||
| -rw-r--r-- | files/.vim/plugin/matchit.vim | 812 | ||||
| -rw-r--r-- | files/.vim/plugin/project.vim | 1293 | ||||
| -rw-r--r-- | files/.vim/plugin/remoteOpen.vim | 163 |
9 files changed, 0 insertions, 5014 deletions
diff --git a/files/.vim/plugin/CSApprox.vim b/files/.vim/plugin/CSApprox.vim deleted file mode 100644 index 0cb727f..0000000 --- a/files/.vim/plugin/CSApprox.vim +++ /dev/null @@ -1,987 +0,0 @@ -" CSApprox: Make gvim-only colorschemes Just Work terminal vim -" Maintainer: Matthew Wozniski (mjw@drexel.edu) -" Date: Wed, 01 Apr 2009 22:10:19 -0400 -" Version: 3.50 -" History: :help csapprox-changelog -" -" Long Description: -" It's hard to find colorschemes for terminal Vim. Most colorschemes are -" written to only support GVim, and don't work at all in terminal Vim. -" -" This plugin makes GVim-only colorschemes Just Work in terminal Vim, as long -" as the terminal supports 88 or 256 colors - and most do these days. This -" usually requires no user interaction (but see below for what to do if things -" don't Just Work). After getting this plugin happily installed, any time you -" use :colorscheme it will do its magic and make the colorscheme Just Work. -" -" Whenever you change colorschemes using the :colorscheme command this script -" will be executed. It will take the colors that the scheme specified for use -" in the GUI and use an approximation algorithm to try to gracefully degrade -" them to the closest color available in your terminal. If you are running in -" a GUI or if your terminal doesn't support 88 or 256 colors, no changes are -" made. Also, no changes will be made if the colorscheme seems to have been -" high color already. -" -" License: -" Copyright (c) 2009, Matthew J. Wozniski -" All rights reserved. -" -" Redistribution and use 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. -" * The names of the contributors may not be used to endorse or promote -" products derived from this software without specific prior written -" permission. -" -" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 HOLDER 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. - -" {>1} Basic plugin setup - -" {>2} Check preconditions -" Quit if the user doesn't want or need us or is missing the gui feature. We -" need +gui to be able to check the gui color settings; vim doesn't bother to -" store them if it is not built with +gui. -if !has('gui') || exists('g:CSApprox_loaded') - " XXX This depends upon knowing the default for g:CSApprox_verbose_level - let s:verbose = 1 - if exists("g:CSApprox_verbose_level") - let s:verbose = g:CSApprox_verbose_level - endif - - if ! has('gui') && s:verbose > 0 - echomsg "CSApprox needs gui support - not loading." - echomsg " See :help |csapprox-+gui| for possible workarounds." - endif - - unlet s:verbose - - finish -endif - -" {1} Mark us as loaded, and disable all compatibility options for now. -let g:CSApprox_loaded = 1 - -let s:savecpo = &cpo -set cpo&vim - -" {>1} Built-in approximation algorithm - -" {>2} Cube definitions -let s:xterm_colors = [ 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF ] -let s:eterm_colors = [ 0x00, 0x2A, 0x55, 0x7F, 0xAA, 0xD4 ] -let s:konsole_colors = [ 0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF ] -let s:xterm_greys = [ 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, - \ 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76, - \ 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, - \ 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE ] - -let s:urxvt_colors = [ 0x00, 0x8B, 0xCD, 0xFF ] -let s:urxvt_greys = [ 0x2E, 0x5C, 0x73, 0x8B, - \ 0xA2, 0xB9, 0xD0, 0xE7 ] - -" {>2} Integer comparator -" Used to sort the complete list of possible colors -function! s:IntCompare(i1, i2) - return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1 -endfunc - -" {>2} Approximator -" Takes 3 decimal values for r, g, and b, and returns the closest cube number. -" Uses &term to determine which cube should be used, though if &term is set to -" "xterm" or begins with "screen", the variables g:CSApprox_eterm and -" g:CSApprox_konsole can be used to select a different palette. -" -" This approximator considers closeness based upon the individiual components. -" For each of r, g, and b, it finds the closest cube component available on -" the cube. If the three closest matches can combine to form a valid color, -" this color is used, otherwise we repeat the search with the greys removed, -" meaning that the three new matches must make a valid color when combined. -function! s:ApproximatePerComponent(r,g,b) - let hex = printf("%02x%02x%02x", a:r, a:g, a:b) - - let greys = (&t_Co == 88 ? s:urxvt_greys : s:xterm_greys) - - if &t_Co == 88 - let colors = s:urxvt_colors - let type = 'urxvt' - elseif ((&term ==# 'xterm' || &term =~# '^screen' || &term==# 'builtin_gui') - \ && exists('g:CSApprox_konsole') && g:CSApprox_konsole) - \ || &term =~? '^konsole' - let colors = s:konsole_colors - let type = 'konsole' - elseif ((&term ==# 'xterm' || &term =~# '^screen' || &term==# 'builtin_gui') - \ && exists('g:CSApprox_eterm') && g:CSApprox_eterm) - \ || &term =~? '^eterm' - let colors = s:eterm_colors - let type = 'eterm' - else - let colors = s:xterm_colors - let type = 'xterm' - endif - - if !exists('s:approximator_cache_'.type) - let s:approximator_cache_{type} = {} - endif - - let rv = get(s:approximator_cache_{type}, hex, -1) - if rv != -1 - return rv - endif - - " Only obtain sorted list once - if !exists("s:".type."_greys_colors") - let s:{type}_greys_colors = sort(greys + colors, "s:IntCompare") - endif - - let greys_colors = s:{type}_greys_colors - - let r = s:NearestElemInList(a:r, greys_colors) - let g = s:NearestElemInList(a:g, greys_colors) - let b = s:NearestElemInList(a:b, greys_colors) - - let len = len(colors) - if (r == g && g == b && index(greys, r) != -1) - let rv = 16 + len * len * len + index(greys, r) - else - let r = s:NearestElemInList(a:r, colors) - let g = s:NearestElemInList(a:g, colors) - let b = s:NearestElemInList(a:b, colors) - let rv = index(colors, r) * len * len - \ + index(colors, g) * len - \ + index(colors, b) - \ + 16 - endif - - let s:approximator_cache_{type}[hex] = rv - return rv -endfunction - -" {>2} Color comparator -" Finds the nearest element to the given element in the given list -function! s:NearestElemInList(elem, list) - let len = len(a:list) - for i in range(len-1) - if (a:elem <= (a:list[i] + a:list[i+1]) / 2) - return a:list[i] - endif - endfor - return a:list[len-1] -endfunction - -" {>1} Collect info for the set highlights - -" {>2} Determine if synIDattr is usable -" synIDattr() couldn't support 'guisp' until 7.2.052. This function returns -" true if :redir is needed to find the 'guisp' attribute, false if synIDattr() -" is functional. This test can be overridden by setting the global variable -" g:CSApprox_redirfallback to 1 (to force use of :redir) or to 0 (to force use -" of synIDattr()). -function! s:NeedRedirFallback() - if !exists("g:CSApprox_redirfallback") - let g:CSApprox_redirfallback = (v:version == 702 && !has('patch52')) - \ || v:version < 702 - endif - return g:CSApprox_redirfallback -endfunction - -" {>2} Collect and store the highlights -" Get a dictionary containing information for every highlight group not merely -" linked to another group. Return value is a dictionary, with highlight group -" numbers for keys and values that are dictionaries with four keys each, -" 'name', 'term', 'cterm', and 'gui'. 'name' holds the group name, and each -" of the others holds highlight information for that particular mode. -function! s:Highlights(modes) - let rv = {} - - let i = 0 - while 1 - let i += 1 - - " Only interested in groups that exist and aren't linked - if synIDtrans(i) == 0 - break - endif - - " Handle vim bug allowing groups with name == "" to be created - if synIDtrans(i) != i || len(synIDattr(i, "name")) == 0 - continue - endif - - let rv[i] = {} - let rv[i].name = synIDattr(i, "name") - - for where in a:modes - let rv[i][where] = {} - for attr in [ "bold", "italic", "reverse", "underline", "undercurl" ] - let rv[i][where][attr] = synIDattr(i, attr, where) - endfor - - for attr in [ "fg", "bg" ] - let rv[i][where][attr] = synIDattr(i, attr.'#', where) - endfor - - if where == "gui" - let rv[i][where]["sp"] = s:SynGuiSp(i, rv[i].name) - else - let rv[i][where]["sp"] = -1 - endif - - for attr in [ "fg", "bg", "sp" ] - if rv[i][where][attr] == -1 - let rv[i][where][attr] = '' - endif - endfor - endfor - endwhile - - return rv -endfunction - -" {>2} Retrieve guisp - -" Get guisp using whichever method is specified by _redir_fallback -function! s:SynGuiSp(idx, name) - if !s:NeedRedirFallback() - return s:SynGuiSpAttr(a:idx) - else - return s:SynGuiSpRedir(a:name) - endif -endfunction - -" {>3} Implementation for retrieving guisp with redir hack -function! s:SynGuiSpRedir(name) - redir => temp - exe 'sil hi ' . a:name - redir END - let temp = matchstr(temp, 'guisp=\zs.*') - if len(temp) == 0 || temp[0] =~ '\s' - let temp = "" - else - " Make sure we can handle guisp='dark red' - let temp = substitute(temp, '[\x00].*', '', '') - let temp = substitute(temp, '\s*\(c\=term\|gui\).*', '', '') - let temp = substitute(temp, '\s*$', '', '') - endif - return temp -endfunction - -" {>3} Implementation for retrieving guisp with synIDattr() -function! s:SynGuiSpAttr(idx) - return synIDattr(a:idx, 'sp#', 'gui') -endfunction - -" {>1} Handle color names - -" Place to store rgb.txt name to color mappings - lazy loaded if needed -let s:rgb = {} - -" {>2} Builtin gui color names -" gui_x11.c and gui_gtk_x11.c have some default colors names that are searched -" if the x server doesn't know about a color. If 'showrgb' is available, -" we'll default to using these color names and values, and overwrite them with -" other values if 'showrgb' tells us about those colors. -let s:rgb_defaults = { "lightred" : "#FFBBBB", - \ "lightgreen" : "#88FF88", - \ "lightmagenta" : "#FFBBFF", - \ "darkcyan" : "#008888", - \ "darkblue" : "#0000BB", - \ "darkred" : "#BB0000", - \ "darkmagenta" : "#BB00BB", - \ "darkgrey" : "#BBBBBB", - \ "darkyellow" : "#BBBB00", - \ "gray10" : "#1A1A1A", - \ "grey10" : "#1A1A1A", - \ "gray20" : "#333333", - \ "grey20" : "#333333", - \ "gray30" : "#4D4D4D", - \ "grey30" : "#4D4D4D", - \ "gray40" : "#666666", - \ "grey40" : "#666666", - \ "gray50" : "#7F7F7F", - \ "grey50" : "#7F7F7F", - \ "gray60" : "#999999", - \ "grey60" : "#999999", - \ "gray70" : "#B3B3B3", - \ "grey70" : "#B3B3B3", - \ "gray80" : "#CCCCCC", - \ "grey80" : "#CCCCCC", - \ "gray90" : "#E5E5E5", - \ "grey90" : "#E5E5E5" } - -" {>2} Colors that vim will use by name in one of the default schemes, either -" for bg=light or for bg=dark. This lets us avoid loading the entire rgb.txt -" database when the scheme itself doesn't ask for colors by name. -let s:rgb_presets = { "black" : "#000000", - \ "blue" : "#0000ff", - \ "brown" : "#a52a2a", - \ "cyan" : "#00ffff", - \ "darkblue" : "#00008b", - \ "darkcyan" : "#008b8b", - \ "darkgrey" : "#a9a9a9", - \ "darkmagenta" : "#8b008b", - \ "green" : "#00ff00", - \ "grey" : "#bebebe", - \ "grey40" : "#666666", - \ "grey90" : "#e5e5e5", - \ "lightblue" : "#add8e6", - \ "lightcyan" : "#e0ffff", - \ "lightgrey" : "#d3d3d3", - \ "lightmagenta" : "#ffbbff", - \ "magenta" : "#ff00ff", - \ "red" : "#ff0000", - \ "seagreen" : "#2e8b57", - \ "white" : "#ffffff", - \ "yellow" : "#ffff00" } - -" {>2} Find available color names -" Find the valid named colors. By default, use our own rgb list, but try to -" retrieve the system's list if g:CSApprox_use_showrgb is set to true. Store -" the color names and color values to the dictionary s:rgb - the keys are -" color names (in lowercase), the values are strings representing color values -" (as '#rrggbb'). -function! s:UpdateRgbHash() - try - if !exists("g:CSApprox_use_showrgb") || !g:CSApprox_use_showrgb - throw "Not using showrgb" - endif - - " We want to use the 'showrgb' program, if it's around - let lines = split(system('showrgb'), '\n') - - if v:shell_error || !exists('lines') || empty(lines) - throw "'showrgb' didn't give us an rgb.txt" - endif - - let s:rgb = copy(s:rgb_defaults) - - " fmt is (blanks?)(red)(blanks)(green)(blanks)(blue)(blanks)(name) - let parsepat = '^\s*\(\d\+\)\s\+\(\d\+\)\s\+\(\d\+\)\s\+\(.*\)$' - - for line in lines - let v = matchlist(line, parsepat) - if len(v) < 0 - throw "CSApprox: Bad RGB line: " . string(line) - endif - let s:rgb[tolower(v[4])] = printf("#%02x%02x%02x", v[1], v[2], v[3]) - endfor - catch - try - let s:rgb = csapprox#rgb() - catch - echohl ErrorMsg - echomsg "Can't call rgb() from autoload/csapprox.vim" - echomsg "Named colors will not be available!" - echohl None - endtry - endtry - - return 0 -endfunction - -" {>1} Derive and set cterm attributes - -" {>2} Attribute overrides -" Allow the user to override a specified attribute with another attribute. -" For example, the default is to map 'italic' to 'underline' (since many -" terminals cannot display italic text, and gvim itself will replace italics -" with underlines where italicizing is impossible), and to replace 'sp' with -" 'fg' (since terminals can't use one color for the underline and another for -" the foreground, we color the entire word). This default can of course be -" overridden by the user, by setting g:CSApprox_attr_map. This map must be -" a dictionary of string keys, representing the same attributes that synIDattr -" can look up, to string values, representing the attribute mapped to or an -" empty string to disable the given attribute entirely. -function! s:attr_map(attr) - let rv = get(g:CSApprox_attr_map, a:attr, a:attr) - - return rv -endfunction - -function! s:NormalizeAttrMap(map) - let old = copy(a:map) - let new = filter(a:map, '0') - - let valid_attrs = [ 'bg', 'fg', 'sp', 'bold', 'italic', - \ 'reverse', 'underline', 'undercurl' ] - - let colorattrs = [ 'fg', 'bg', 'sp' ] - - for olhs in keys(old) - if olhs ==? 'inverse' - let nlhs = 'reverse' - endif - - let orhs = old[olhs] - - if orhs ==? 'inverse' - let nrhs = 'reverse' - endif - - let nlhs = tolower(olhs) - let nrhs = tolower(orhs) - - try - if index(valid_attrs, nlhs) == -1 - echomsg "CSApprox: Bad attr map (removing unrecognized attribute " . olhs . ")" - elseif nrhs != '' && index(valid_attrs, nrhs) == -1 - echomsg "CSApprox: Bad attr map (removing unrecognized attribute " . orhs . ")" - elseif nrhs != '' && !!(index(colorattrs, nlhs)+1) != !!(index(colorattrs, nrhs)+1) - echomsg "CSApprox: Bad attr map (removing " . olhs . "; type mismatch with " . orhs . ")" - elseif nrhs == 'sp' - echomsg "CSApprox: Bad attr map (removing " . olhs . "; can't map to 'sp')" - else - let new[nlhs] = nrhs - endif - catch - echo v:exception - endtry - endfor -endfunction - -" {>2} Normalize the GUI settings of a highlight group -" If the Normal group is cleared, set it to gvim's default, black on white -" Though this would be a really weird thing for a scheme to do... *shrug* -function! s:FixupGuiInfo(highlights) - if a:highlights[s:hlid_normal].gui.bg == '' - let a:highlights[s:hlid_normal].gui.bg = 'white' - endif - - if a:highlights[s:hlid_normal].gui.fg == '' - let a:highlights[s:hlid_normal].gui.fg = 'black' - endif -endfunction - -" {>2} Map gui settings to cterm settings -" Given information about a highlight group, replace the cterm settings with -" the mapped gui settings, applying any attribute overrides along the way. In -" particular, this gives special treatment to the 'reverse' attribute and the -" 'guisp' attribute. In particular, if the 'reverse' attribute is set for -" gvim, we unset it for the terminal and instead set ctermfg to match guibg -" and vice versa, since terminals can consider a 'reverse' flag to mean using -" default-bg-on-default-fg instead of current-bg-on-current-fg. We also -" ensure that the 'sp' attribute is never set for cterm, since no terminal can -" handle that particular highlight. If the user wants to display the guisp -" color, he should map it to either 'fg' or 'bg' using g:CSApprox_attr_map. -function! s:FixupCtermInfo(highlights) - for hl in values(a:highlights) - - if !has_key(hl, 'cterm') - let hl["cterm"] = {} - endif - - " Find attributes to be set in the terminal - for attr in [ "bold", "italic", "reverse", "underline", "undercurl" ] - let hl.cterm[attr] = '' - if hl.gui[attr] == 1 - if s:attr_map(attr) != '' - let hl.cterm[ s:attr_map(attr) ] = 1 - endif - endif - endfor - - for color in [ "bg", "fg" ] - let eff_color = color - if hl.cterm['reverse'] - let eff_color = (color == 'bg' ? 'fg' : 'bg') - endif - - let hl.cterm[color] = get(hl.gui, s:attr_map(eff_color), '') - endfor - - if hl.gui['sp'] != '' && s:attr_map('sp') != '' - let hl.cterm[s:attr_map('sp')] = hl.gui['sp'] - endif - - if hl.cterm['reverse'] && hl.cterm.bg == '' - let hl.cterm.bg = 'fg' - endif - - if hl.cterm['reverse'] && hl.cterm.fg == '' - let hl.cterm.fg = 'bg' - endif - - if hl.cterm['reverse'] - let hl.cterm.reverse = '' - endif - endfor -endfunction - -" {>2} Set cterm colors for a highlight group -" Given the information for a single highlight group (ie, the value of -" one of the items in s:Highlights() already normalized with s:FixupCtermInfo -" and s:FixupGuiInfo), handle matching the gvim colors to the closest cterm -" colors by calling the appropriate approximator as specified with the -" g:CSApprox_approximator_function variable and set the colors and attributes -" appropriately to match the gui. -function! s:SetCtermFromGui(hl) - let hl = a:hl - - " Set up the default approximator function, if needed - if !exists("g:CSApprox_approximator_function") - let g:CSApprox_approximator_function=function("s:ApproximatePerComponent") - endif - - " Clear existing highlights - exe 'hi ' . hl.name . ' cterm=NONE ctermbg=NONE ctermfg=NONE' - - for which in [ 'bg', 'fg' ] - let val = hl.cterm[which] - - " Skip unset colors - if val == -1 || val == "" - continue - endif - - " Try translating anything but 'fg', 'bg', #rrggbb, and rrggbb from an - " rgb.txt color to a #rrggbb color - if val !~? '^[fb]g$' && val !~ '^#\=\x\{6}$' - try - " First see if it is in our preset-by-vim rgb list - let val = s:rgb_presets[tolower(val)] - catch - " Then try loading and checking our real rgb list - if empty(s:rgb) - call s:UpdateRgbHash() - endif - try - let val = s:rgb[tolower(val)] - catch - " And then barf if we still haven't found it - if &verbose - echomsg "CSApprox: Colorscheme uses unknown color \"" . val . "\"" - endif - continue - endtry - endtry - endif - - if val =~? '^[fb]g$' - exe 'hi ' . hl.name . ' cterm' . which . '=' . val - let hl.cterm[which] = val - elseif val =~ '^#\=\x\{6}$' - let val = substitute(val, '^#', '', '') - let r = str2nr(val[0:1], 16) - let g = str2nr(val[2:3], 16) - let b = str2nr(val[4:5], 16) - let hl.cterm[which] = g:CSApprox_approximator_function(r, g, b) - exe 'hi ' . hl.name . ' cterm' . which . '=' . hl.cterm[which] - else - throw "Internal error handling color: " . val - endif - endfor - - " Finally, set the attributes - let attrs = [ 'bold', 'italic', 'underline', 'undercurl' ] - call filter(attrs, 'hl.cterm[v:val] == 1') - - if !empty(attrs) - exe 'hi ' . hl.name . ' cterm=' . join(attrs, ',') - endif -endfunction - - -" {>1} Top-level control - -" Cache the highlight ID of the normal group; it's used often and won't change -let s:hlid_normal = hlID('Normal') - -" {>2} Builtin cterm color names above 15 -" Vim defines some color name to high color mappings internally (see -" syntax.c:do_highlight). Since we don't want to overwrite a colorscheme that -" was actually written for a high color terminal with our choices, but have no -" way to tell if a colorscheme was written for a high color terminal, we fall -" back on guessing. If any highlight group has a cterm color set to 16 or -" higher, we assume that the user has used a high color colorscheme - unless -" that color is one of the below, which vim can set internally when a color is -" requested by name. -let s:presets_88 = [] -let s:presets_88 += [32] " Brown -let s:presets_88 += [72] " DarkYellow -let s:presets_88 += [84] " Gray -let s:presets_88 += [84] " Grey -let s:presets_88 += [82] " DarkGray -let s:presets_88 += [82] " DarkGrey -let s:presets_88 += [43] " LightBlue -let s:presets_88 += [61] " LightGreen -let s:presets_88 += [63] " LightCyan -let s:presets_88 += [74] " LightRed -let s:presets_88 += [75] " LightMagenta -let s:presets_88 += [78] " LightYellow - -let s:presets_256 = [] -let s:presets_256 += [130] " Brown -let s:presets_256 += [130] " DarkYellow -let s:presets_256 += [248] " Gray -let s:presets_256 += [248] " Grey -let s:presets_256 += [242] " DarkGray -let s:presets_256 += [242] " DarkGrey -let s:presets_256 += [ 81] " LightBlue -let s:presets_256 += [121] " LightGreen -let s:presets_256 += [159] " LightCyan -let s:presets_256 += [224] " LightRed -let s:presets_256 += [225] " LightMagenta -let s:presets_256 += [229] " LightYellow - -" {>2} Wrapper around :exe to allow :executing multiple commands. -" "cmd" is the command to be :executed. -" If the variable is a String, it is :executed. -" If the variable is a List, each element is :executed. -function! s:exe(cmd) - if type(a:cmd) == type('') - exe a:cmd - else - for cmd in a:cmd - call s:exe(cmd) - endfor - endif -endfunction - -" {>2} Function to handle hooks -" Prototype: HandleHooks(type [, scheme]) -" "type" is the type of hook to be executed, ie. "pre" or "post" -" "scheme" is the name of the colorscheme that is currently active, if known -" -" If the variables g:CSApprox_hook_{type} and g:CSApprox_hook_{scheme}_{type} -" exist, this will :execute them in that order. If one does not exist, it -" will silently be ignored. -" -" If the scheme name contains characters that are invalid in a variable name, -" they will simply be removed. Ie, g:colors_name = "123 foo_bar-baz456" -" becomes "foo_barbaz456" -" -" NOTE: Exceptions will be printed out, rather than end processing early. The -" rationale is that it is worse for the user to fix the hook in an editor with -" broken colors. :) -function! s:HandleHooks(type, ...) - let type = a:type - let scheme = (a:0 == 1 ? a:1 : "") - let scheme = substitute(scheme, '[^[:alnum:]_]', '', 'g') - let scheme = substitute(scheme, '^\d\+', '', '') - - for cmd in [ 'g:CSApprox_hook_' . type, - \ 'g:CSApprox_' . scheme . '_hook_' . type, - \ 'g:CSApprox_hook_' . scheme . '_' . type ] - if exists(cmd) - try - call s:exe(eval(cmd)) - catch - echomsg "Error processing " . cmd . ":" - echomsg v:exception - endtry - endif - endfor -endfunction - -" {>2} Main function -" Wrapper around the actual implementation to make it easier to ensure that -" all temporary settings are restored by the time we return, whether or not -" something was thrown. Additionally, sets the 'verbose' option to the max of -" g:CSApprox_verbose_level (default 1) and &verbose for the duration of the -" main function. This allows us to default to a message whenever any error, -" even a recoverable one, occurs, meaning the user quickly finds out when -" something's wrong, but makes it very easy for the user to make us silent. -function! s:CSApprox() - try - let savelz = &lz - - set lz - - if exists("g:CSApprox_attr_map") && type(g:CSApprox_attr_map) == type({}) - call s:NormalizeAttrMap(g:CSApprox_attr_map) - else - let g:CSApprox_attr_map = { 'italic' : 'underline', 'sp' : 'fg' } - endif - - " colors_name must be unset and reset, or vim will helpfully reload the - " colorscheme when we set the background for the Normal group. - " See the help entries ':hi-normal-cterm' and 'g:colors_name' - if exists("g:colors_name") - let colors_name = g:colors_name - unlet g:colors_name - endif - - " Similarly, the global variable "syntax_cmd" must be set to something vim - " doesn't recognize, lest vim helpfully switch all colors back to the - " default whenever the Normal group is changed (in syncolor.vim)... - if exists("g:syntax_cmd") - let syntax_cmd = g:syntax_cmd - endif - let g:syntax_cmd = "PLEASE DON'T CHANGE ANY COLORS!!!" - - " Set up our verbosity level, if needed. - " Default to 1, so the user can know if something's wrong. - if !exists("g:CSApprox_verbose_level") - let g:CSApprox_verbose_level = 1 - endif - - call s:HandleHooks("pre", (exists("colors_name") ? colors_name : "")) - - " Set 'verbose' set to the maximum of &verbose and CSApprox_verbose_level - exe max([&vbs, g:CSApprox_verbose_level]) 'verbose call s:CSApproxImpl()' - - call s:HandleHooks("post", (exists("colors_name") ? colors_name : "")) - finally - if exists("colors_name") - let g:colors_name = colors_name - endif - - unlet g:syntax_cmd - if exists("syntax_cmd") - let g:syntax_cmd = syntax_cmd - endif - - let &lz = savelz - endtry -endfunction - -" {>2} CSApprox implementation -" Verifies that the user has not started the gui, and that vim recognizes his -" terminal as having enough colors for us to go on, then gathers the existing -" highlights and sets the cterm colors to match the gui colors for all those -" highlights (unless the colorscheme was already high-color). -function! s:CSApproxImpl() - " Return if not running in an 88/256 color terminal - if &t_Co != 256 && &t_Co != 88 - if &verbose && !has('gui_running') - echomsg "CSApprox skipped; terminal only has" &t_Co "colors, not 88/256" - echomsg "Try checking :help csapprox-terminal for workarounds" - endif - - return - endif - - " Get the current highlight colors - let highlights = s:Highlights(["gui"]) - - let hinums = keys(highlights) - - " Make sure that the script is not already 256 color by checking to make - " sure that no groups are set to a value above 256, unless the color they're - " set to can be set internally by vim (gotten by scraping - " color_numbers_{88,256} in syntax.c:do_highlight) - " - " XXX: s:inhibit_hicolor_test allows this test to be skipped for snapshots - if !exists("s:inhibit_hicolor_test") || !s:inhibit_hicolor_test - for hlid in hinums - for type in [ 'bg', 'fg' ] - let color = synIDattr(hlid, type, 'cterm') - - if color > 15 && index(s:presets_{&t_Co}, str2nr(color)) < 0 - " The value is set above 15, and wasn't set by vim. - if &verbose >= 2 - echomsg 'CSApprox: Exiting - high' type 'color found for' highlights[hlid].name - endif - return - endif - endfor - endfor - endif - - call s:FixupGuiInfo(highlights) - call s:FixupCtermInfo(highlights) - - " We need to set the Normal group first so 'bg' and 'fg' work as colors - call insert(hinums, remove(hinums, index(hinums, string(s:hlid_normal)))) - - " then set each color's cterm attributes to match gui - for hlid in hinums - call s:SetCtermFromGui(highlights[hlid]) - endfor -endfunction - -" {>2} Write out the current colors to an 88/256 color colorscheme file. -" "file" - destination filename -" "overwrite" - overwrite an existing file -function! s:CSApproxSnapshot(file, overwrite) - let force = a:overwrite - let file = fnamemodify(a:file, ":p") - - if empty(file) - throw "Bad file name: \"" . file . "\"" - elseif (filewritable(fnamemodify(file, ':h')) != 2) - throw "Cannot write to directory \"" . fnamemodify(file, ':h') . "\"" - elseif (glob(file) || filereadable(file)) && !force - " TODO - respect 'confirm' here and prompt if it's set. - echohl ErrorMsg - echomsg "E13: File exists (add ! to override)" - echohl None - return - endif - - " Sigh... This is basically a bug, but one that I have no chance of fixing. - " Vim decides that Pmenu should be highlighted in 'LightMagenta' in terminal - " vim and as 'Magenta' in gvim... And I can't ask it what color it actually - " *wants*. As far as I can see, there's no way for me to learn that - " I should output 'Magenta' when 'LightMagenta' is provided by vim for the - " terminal. - if !has('gui_running') - echohl WarningMsg - echomsg "Warning: The written colorscheme may have incorrect colors" - echomsg " when CSApproxSnapshot is used in terminal vim!" - echohl None - endif - - let save_t_Co = &t_Co - let s:inhibit_hicolor_test = 1 - if exists("g:CSApprox_konsole") - let save_CSApprox_konsole = g:CSApprox_konsole - endif - if exists("g:CSApprox_eterm") - let save_CSApprox_eterm = g:CSApprox_eterm - endif - - " Needed just like in CSApprox() - if exists("g:colors_name") - let colors_name = g:colors_name - unlet g:colors_name - endif - - " Needed just like in CSApprox() - if exists("g:syntax_cmd") - let syntax_cmd = g:syntax_cmd - endif - let g:syntax_cmd = "PLEASE DON'T CHANGE ANY COLORS!!!" - - try - let lines = [] - let lines += [ '" This scheme was created by CSApproxSnapshot' ] - let lines += [ '" on ' . strftime("%a, %d %b %Y") ] - let lines += [ '' ] - let lines += [ 'hi clear' ] - let lines += [ 'if exists("syntax_on")' ] - let lines += [ ' syntax reset' ] - let lines += [ 'endif' ] - let lines += [ '' ] - let lines += [ 'if v:version < 700' ] - let lines += [ ' let g:colors_name = expand("<sfile>:t:r")' ] - let lines += [ ' command! -nargs=+ CSAHi exe "hi" substitute(substitute(<q-args>, "undercurl", "underline", "g"), "guisp\\S\\+", "", "g")' ] - let lines += [ 'else' ] - let lines += [ ' let g:colors_name = expand("<sfile>:t:r")' ] - let lines += [ ' command! -nargs=+ CSAHi exe "hi" <q-args>' ] - let lines += [ 'endif' ] - let lines += [ '' ] - - let lines += [ 'if 0' ] - for round in [ 'konsole', 'eterm', 'xterm', 'urxvt' ] - sil! unlet g:CSApprox_eterm - sil! unlet g:CSApprox_konsole - - if round == 'konsole' - let g:CSApprox_konsole = 1 - elseif round == 'eterm' - let g:CSApprox_eterm = 1 - endif - - if round == 'urxvt' - set t_Co=88 - else - set t_Co=256 - endif - - call s:CSApprox() - - let highlights = s:Highlights(["term", "cterm", "gui"]) - call s:FixupGuiInfo(highlights) - - if round == 'konsole' || round == 'eterm' - let lines += [ 'elseif has("gui_running") || (&t_Co == ' . &t_Co - \ . ' && (&term ==# "xterm" || &term =~# "^screen")' - \ . ' && exists("g:CSApprox_' . round . '")' - \ . ' && g:CSApprox_' . round . ')' - \ . ' || &term =~? "^' . round . '"' ] - else - let lines += [ 'elseif has("gui_running") || &t_Co == ' . &t_Co ] - endif - - let hinums = keys(highlights) - - call insert(hinums, remove(hinums, index(hinums, string(s:hlid_normal)))) - - for hlnum in hinums - let hl = highlights[hlnum] - let line = ' CSAHi ' . hl.name - for type in [ 'term', 'cterm', 'gui' ] - let attrs = [ 'reverse', 'bold', 'italic', 'underline', 'undercurl' ] - call filter(attrs, 'hl[type][v:val] == 1') - let line .= ' ' . type . '=' . (empty(attrs) ? 'NONE' : join(attrs, ',')) - if type != 'term' - let line .= ' ' . type . 'bg=' . (len(hl[type].bg) ? hl[type].bg : 'bg') - let line .= ' ' . type . 'fg=' . (len(hl[type].fg) ? hl[type].fg : 'fg') - if type == 'gui' && hl.gui.sp !~ '^\s*$' - let line .= ' ' . type . 'sp=' . hl[type].sp - endif - endif - endfor - let lines += [ line ] - endfor - endfor - let lines += [ 'endif' ] - let lines += [ '' ] - let lines += [ 'if 1' ] - let lines += [ ' delcommand CSAHi' ] - let lines += [ 'endif' ] - call writefile(lines, file) - finally - let &t_Co = save_t_Co - - if exists("save_CSApprox_konsole") - let g:CSApprox_konsole = save_CSApprox_konsole - endif - if exists("save_CSApprox_eterm") - let g:CSApprox_eterm = save_CSApprox_eterm - endif - - if exists("colors_name") - let g:colors_name = colors_name - endif - - unlet g:syntax_cmd - if exists("syntax_cmd") - let g:syntax_cmd = syntax_cmd - endif - - call s:CSApprox() - - unlet s:inhibit_hicolor_test - endtry -endfunction - -" {>2} Snapshot user command -command! -bang -nargs=1 -complete=file -bar CSApproxSnapshot - \ call s:CSApproxSnapshot(<f-args>, strlen("<bang>")) - -" {>1} Hooks - -" {>2} Autocmds -" Set up an autogroup to hook us on the completion of any :colorscheme command -augroup CSApprox - au! - au ColorScheme * call s:CSApprox() - "au User CSApproxPost highlight Normal ctermbg=none | highlight NonText ctermbg=None -augroup END - -" {>2} Execute -" The last thing to do when sourced is to run and actually fix up the colors. -if !has('gui_running') - call s:CSApprox() -endif - -" {>1} Restore compatibility options -let &cpo = s:savecpo -unlet s:savecpo - - -" {0} vim:sw=2:sts=2:et:fdm=expr:fde=substitute(matchstr(getline(v\:lnum),'^\\s*"\\s*{\\zs.\\{-}\\ze}'),'^$','=','') diff --git a/files/.vim/plugin/SyntaxFolds.vim b/files/.vim/plugin/SyntaxFolds.vim deleted file mode 100644 index 27c622c..0000000 --- a/files/.vim/plugin/SyntaxFolds.vim +++ /dev/null @@ -1,323 +0,0 @@ -" ============================================================================== -" File: syntaxFolds.vim -" Author: Srinath Avadhanula -" ( srinath@fastmail.fm ) -" Last Change: Sun Oct 27 01:00 AM 2002 PST -" Description: Emulation of the syntax folding capability of vim using manual -" folding -" -" This script provides an emulation of the syntax folding of vim using manual -" folding. Just as in syntax folding, the folds are defined by regions. Each -" region is specified by a call to FoldRegions() which accepts 4 parameters: -" -" call FoldRegions(startpat, endpat, startoff, endoff) -" -" startpat: a line matching this pattern defines the beginning of a fold. -" endpat : a line matching this pattern defines the end of a fold. -" startoff: this is the offset from the starting line at which folding will -" actually start -" endoff : like startoff, but gives the offset of the actual fold end from -" the line satisfying endpat. -" startoff and endoff are necessary when the folding region does -" not have a specific end pattern corresponding to a start -" pattern. for example in latex, -" \begin{section} -" defines the beginning of a section, but its not necessary to -" have a corresponding -" \end{section} -" the section is assumed to end 1 line _before_ another section -" starts. -" startskip: a pattern which defines the beginning of a "skipped" region. -" -" For example, suppose we define a \itemize fold as follows: -" startpat = '^\s*\\item', -" endpat = '^\s*\\item\|^\s*\\end{\(enumerate\|itemize\|description\)}', -" startoff = 0, -" endoff = -1 -" -" This defines a fold which starts with a line beginning with an -" \item and ending one line before a line beginning with an -" \item or \end{enumerate} etc. -" -" Then, as long as \item's are not nested things are fine. -" However, once items begin to nest, the fold started by one -" \item can end because of an \item in an \itemize -" environment within this \item. i.e, the following can happen: -" -" \begin{itemize} -" \item Some text <------- fold will start here -" This item will contain a nested item -" \begin{itemize} <----- fold will end here because next line contains \item... -" \item Hello -" \end{itemize} <----- ... instead of here. -" \item Next item of the parent itemize -" \end{itemize} -" -" Therefore, in order to completely define a folding item which -" allows nesting, we need to also define a "skip" pattern. -" startskip and end skip do that. -" Leave '' when there is no nesting. -" endskip: the pattern which defines the end of the "skip" pattern for -" nested folds. -" -" Example: -" 1. A syntax fold region for a latex section is -" startpat = "\\section{" -" endpat = "\\section{" -" startoff = 0 -" endoff = -1 -" startskip = '' -" endskip = '' -" Note that the start and end patterns are thus the same and endoff has a -" negative value to capture the effect of a section ending one line before -" the next starts. -" 2. A syntax fold region for the \itemize environment is: -" startpat = '^\s*\\item', -" endpat = '^\s*\\item\|^\s*\\end{\(enumerate\|itemize\|description\)}', -" startoff = 0, -" endoff = -1, -" startskip = '^\s*\\begin{\(enumerate\|itemize\|description\)}', -" endskip = '^\s*\\end{\(enumerate\|itemize\|description\)}' -" Note the use of startskip and endskip to allow nesting. -" -" -" Each time a call is made to FoldRegions(), all the regions (which might be -" disjoint, but not nested) are folded up. -" Nested folds can be created by successive calls to FoldRegions(). The first -" call defines the region which is deepest in the folding. See MakeTexFolds() -" for an idea of how this works for latex files. - -" Function: AddSyntaxFoldItem (start, end, startoff, endoff [, skipStart, skipEnd]) {{{ -function! AddSyntaxFoldItem(start, end, startoff, endoff, ...) - if a:0 > 0 - let skipStart = a:1 - let skipEnd = a:2 - else - let skipStart = '' - let skipEnd = '' - end - if !exists('b:numFoldItems') - let b:numFoldItems = 0 - end - let b:numFoldItems = b:numFoldItems + 1 - - exe 'let b:startPat_'.b:numFoldItems.' = a:start' - exe 'let b:endPat_'.b:numFoldItems.' = a:end' - exe 'let b:startOff_'.b:numFoldItems.' = a:startoff' - exe 'let b:endOff_'.b:numFoldItems.' = a:endoff' - exe 'let b:skipStartPat_'.b:numFoldItems.' = skipStart' - exe 'let b:skipEndPat_'.b:numFoldItems.' = skipEnd' -endfunction - - -" }}} -" Function: MakeSyntaxFolds (force) {{{ -" Description: This function calls FoldRegions() several times with the -" parameters specifying various regions resulting in a nested fold -" structure for the file. -function! MakeSyntaxFolds(force, ...) - if exists('b:doneFolding') && a:force == 0 - return - end - - let skipEndPattern = '' - if a:0 > 0 - let line1 = a:1 - let skipEndPattern = '\|'.a:2 - else - let line1 = 1 - let r = line('.') - let c = virtcol('.') - - setlocal fdm=manual - normal! zE - end - if !exists('b:numFoldItems') - b:numFoldItems = 1000000 - end - - let i = 1 - - let maxline = line('.') - - while exists('b:startPat_'.i) && i <= b:numFoldItems - exe 'let startPat = b:startPat_'.i - exe 'let endPat = b:endPat_'.i - exe 'let startOff = b:startOff_'.i - exe 'let endOff = b:endOff_'.i - - let skipStart = '' - let skipEnd = '' - if exists('b:skipStartPat_'.i) - exe 'let skipStart = b:skipStartPat_'.i - exe 'let skipEnd = b:skipEndPat_'.i - end - exe line1 - let lastLoc = line1 - - if skipStart != '' - call InitStack('BeginSkipArray') - call FoldRegionsWithSkip(startPat, endPat, startOff, endOff, skipStart, skipEnd, 1, line('$')) - " call PrintError('done folding ['.startPat.']') - else - call FoldRegionsWithNoSkip(startPat, endPat, startOff, endOff, 1, line('$'), '') - end - - let i = i + 1 - endwhile - - exe maxline - - if a:0 == 0 - exe r - exe "normal! ".c."|" - if foldlevel(r) > 1 - exe "normal! ".(foldlevel(r) - 1)."zo" - end - let b:doneFolding = 0 - end -endfunction - - -" }}} -" FoldRegionsWithSkip: folding things such as \item's which can be nested. {{{ -function! FoldRegionsWithSkip(startpat, endpat, startoff, endoff, startskip, endskip, line1, line2) - exe a:line1 - " count the regions which have been skipped as we go along. do not want to - " create a fold which with a beginning or end line in one of the skipped - " regions. - let skippedRegions = '' - - " start searching for either the starting pattern or the end pattern. - while search(a:startskip.'\|'.a:endskip, 'W') - - if getline('.') =~ a:endskip - - let lastBegin = Pop('BeginSkipArray') - " call PrintError('popping '.lastBegin.' from stack and folding till '.line('.')) - call FoldRegionsWithNoSkip(a:startpat, a:endpat, a:startoff, a:endoff, lastBegin, line('.'), skippedRegions) - let skippedRegions = skippedRegions.lastBegin.','.line('.').'|' - - - " if this is the beginning of a skip region, then, push this line as - " the beginning of a skipped region. - elseif getline('.') =~ a:startskip - - " call PrintError('pushing '.line('.').' ['.getline('.').'] into stack') - call Push('BeginSkipArray', line('.')) - - end - endwhile - - " call PrintError('with skip starting at '.a:line1.' returning at line# '.line('.')) -endfunction - -" }}} -" FoldRegionsWithNoSkip: folding things such as \sections which do not nest. {{{ -function! FoldRegionsWithNoSkip(startpat, endpat, startoff, endoff, line1, line2, skippedRegions) - exe a:line1 - - " call PrintError('line1 = '.a:line1.', searching from '.line('.').'... for ['.a:startpat.'') - let lineBegin = s:MySearch(a:startpat, 'in') - " call PrintError('... and finding it at '.lineBegin) - - while lineBegin <= a:line2 - if IsInSkippedRegion(lineBegin, a:skippedRegions) - let lineBegin = s:MySearch(a:startpat, 'out') - " call PrintError(lineBegin.' is being skipped') - continue - end - let lineEnd = s:MySearch(a:endpat, 'out') - while IsInSkippedRegion(lineEnd, a:skippedRegions) && lineEnd <= a:line2 - let lineEnd = s:MySearch(a:endpat, 'out') - endwhile - if lineEnd > a:line2 - exe (lineBegin + a:startoff).','.a:line2.' fold' - break - else - " call PrintError ('for ['.a:startpat.'] '.(lineBegin + a:startoff).','.(lineEnd + a:endoff).' fold') - exe (lineBegin + a:startoff).','.(lineEnd + a:endoff).' fold' - end - - " call PrintError('line1 = '.a:line1.', searching from '.line('.').'... for ['.a:startpat.'') - let lineBegin = s:MySearch(a:startpat, 'in') - " call PrintError('... and finding it at '.lineBegin) - endwhile - - exe a:line2 - return -endfunction - -" }}} -" InitStack: initialize a stack {{{ -function! InitStack(name) - exe 'let s:'.a:name.'_numElems = 0' -endfunction -" }}} -" Push: push element into stack {{{ -function! Push(name, elem) - exe 'let numElems = s:'.a:name.'_numElems' - let numElems = numElems + 1 - exe 'let s:'.a:name.'_Element_'.numElems.' = a:elem' - exe 'let s:'.a:name.'_numElems = numElems' -endfunction -" }}} -" Pop: pops element off stack {{{ -function! Pop(name) - exe 'let numElems = s:'.a:name.'_numElems' - if numElems == 0 - return '' - else - exe 'let ret = s:'.a:name.'_Element_'.numElems - let numElems = numElems - 1 - exe 'let s:'.a:name.'_numElems = numElems' - return ret - end -endfunction -" }}} -" MySearch: just like search(), but returns large number on failure {{{ -function! <SID>MySearch(pat, opt) - if a:opt == 'in' - if getline('.') =~ a:pat - let ret = line('.') - else - let ret = search(a:pat, 'W') - end - else - normal! $ - let ret = search(a:pat, 'W') - end - - if ret == 0 - let ret = line('$') + 1 - end - return ret -endfunction -" }}} -" Function: IsInSkippedRegion (lnum, regions) {{{ -" Description: finds whether a given line number is within one of the regions -" skipped. -function! IsInSkippedRegion(lnum, regions) - let i = 1 - let subset = s:Strntok(a:regions, '|', i) - while subset != '' - let n1 = s:Strntok(subset, ',', 1) - let n2 = s:Strntok(subset, ',', 2) - if a:lnum >= n1 && a:lnum <= n2 - return 1 - end - - let subset = s:Strntok(a:regions, '|', i) - let i = i + 1 - endwhile - - return 0 -endfunction " }}} -" Function: Strntok (string, tok, n) {{{ -" extract the n^th token from s seperated by tok. -" example: Strntok('1,23,3', ',', 2) = 23 -fun! <SID>Strntok(s, tok, n) - return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') -endfun " }}} - -" vim600:fdm=marker diff --git a/files/.vim/plugin/XMLFolding.vim b/files/.vim/plugin/XMLFolding.vim deleted file mode 100755 index ec5487b..0000000 --- a/files/.vim/plugin/XMLFolding.vim +++ /dev/null @@ -1,105 +0,0 @@ -" About XMLFolding Script {{{ - -" XMLFolding version 1.1 - May 13th, 2006 -" Author: Thadeu Aparecido Coelho de Paula -" E-mail: thadeudepaula@gmail.com -" WebPage: http://mundolivre.hostrixonline.com -" -" This is my first vim script... at this point I already worked three -" continual weeks to make it. Never give up your objectives! -" I hope that you enjoy it, and use it to accomplish your projects! -" -" This script is under GNU Public License... use it, change it, sell it but -" never forget to mention the original author" -" -" Made using Vim 6.04 on Debian GNU/Linux -" -" This Script supports: -" -" Folding of comments "<!-- -->" -" Folding of open/close tags in different lines "<> </>" -" Folding between CDATA markers "<![CDATA[" and "]]>" - -" }}} - -" Howto {{{ - - " Installing {{{ -" Copy this file for any location yow want to... I suggest that you put it on -" your ~/.vim/plugin directory. -" -" To load this script in your vim session, type on normal mode: -" :so ~/.vim/script/XMLFolding.vim -" (If you saved on local where I suggested!) - -"}}} - - " How to load this script automaticaly? {{{ -"You can use this script more easily configuring your vim to run it on start... -"You'll need to put this line in your /etc/vim/vimrc or ~/.vimrc: - -" au BufNewFile,BufRead *.xml,*.htm,*.html so ~/.vim/plugin/XMLFolding.vim - -" The "*.xml,*.html" can be changed for the file extensions that you want to -" use with this script. - "}}} - - " Limitatios... i.e, when the fold won't occurs {{{ - -" The syntax need to be perfectly to match correctly... the tags needs to be -" nested correctly... -" All the tags nested in the same line will not be folded... like this: -" -" <start>blablabla<middle>blablabla</middle>asdsad -" </start> -" -" In this example only "start" will be folded... -" -" An other problem will occur when you end the line closing a tag different -" than the open tag that starts the line, because the matches ignore the lines -" that starts opening a tag and ends closing a tag... -" -" <start><middle>asdasdsd</middle> -" </start> -" -" This will cause an error, because MATCHES ARE NOT MADE BY THE CONTENT OF A -" TAG, but by the presence of start and end aspect: <----> </----> independent -" of the tag content... if it encounter an incorrect nesting, the folding for -" the document will be broken. -" -" This way, the script serves as an validator, limited but functional! - - "}}} - - -"}}} - -" Folding def commands {{{ - - " Basic vim commands for folding definition {{{ -syn sync fromstart -set foldmethod=syntax - "}}} - - " Matches and regions {{{ - -syn region XMLFold start=+^<\([^/?!><]*[^/]>\)\&.*\(<\1\|[[:alnum:]]\)$+ end=+^</.*[^-?]>$+ fold transparent keepend extend - -syn match XMLCData "<!\[CDATA\[\_.\{-}\]\]>" fold transparent extend - -syn match XMLCommentFold "<!--\_.\{-}-->" fold transparent extend - - - "}}} - - " Label shown for folded lines {{{ -set foldtext=XMLFoldLabel() - fun! XMLFoldLabel() - let getcontent = substitute(getline(v:foldstart), "^[[:space:]]*", "", 'g') - let linestart = substitute(v:folddashes, ".", '»', 'g') - return linestart . " " . getcontent -endfunction - - "}}} - -"}}} diff --git a/files/.vim/plugin/filebrowser.vim b/files/.vim/plugin/filebrowser.vim deleted file mode 100644 index e9de049..0000000 --- a/files/.vim/plugin/filebrowser.vim +++ /dev/null @@ -1,251 +0,0 @@ -" filebrowser.vim: utility file for vim 6.2+ -" -" Copyright: Srinath Avadhanula <srinath AT fastmail DOT fm> -" Parts of this file are taken from explorer.vim which is a plugin file -" distributed with vim under the Vim charityware license. -" License: distributed under the Vim charityware license. -" -" Settings: -" FB_CallBackFunction: the function name which gets called when the user -" presses <cr> on a file-name in the file browser. -" FB_AllowRegexp: A filename has to match this regexp to be displayed. -" FB_RejectRegexp: If a filename matches this regexp, then its not displayed. -" (Both these regexps are '' by default which means no filtering is -" done). - -" line continuation used here. -let s:save_cpo = &cpo -set cpo&vim - -"====================================================================== -" Globally visible functions (API) -"====================================================================== -" FB_OpenFileBrowser: opens a new buffer and displays the file list {{{ -" Description: -function! FB_OpenFileBrowser(dir) - if !isdirectory(a:dir) - return - endif - if exists('s:FB_BufferNumber') - if bufwinnr(s:FB_BufferNumber) != -1 - execute bufwinnr(s:FB_BufferNumber).' wincmd w' - return - endif - execute 'aboveleft split #'.s:FB_BufferNumber - else - aboveleft split __Choose_File__ - let s:FB_BufferNumber = bufnr('%') - endif - call FB_DisplayFiles(a:dir) -endfunction " }}} -" FB_DisplayFiles: displays the files in a given directory {{{ -" Description: -" Call this function only when the cursor is in a temporary buffer -function! FB_DisplayFiles(dir) - if !isdirectory(a:dir) - return - endif - call s:FB_SetSilentSettings() - " make this a "scratch" buffer - call s:FB_SetScratchSettings() - - let allowRegexp = s:FB_GetVar('FB_AllowRegexp', '') - let rejectRegexp = s:FB_GetVar('FB_RejectRegexp', '') - - " change to the directory to make processing simpler. - execute "lcd ".a:dir - " delete everything in the buffer. - " IMPORTANT: we need to be in a scratch buffer - 0,$ d_ - - let allFilenames = glob('*') - let dispFiles = "" - let subDirs = "../\n" - - let i = 1 - while 1 - let filename = s:FB_Strntok(allFilenames, "\n", i) - if filename == '' - break - endif - if isdirectory(filename) - let subDirs = subDirs.filename."/\n" - else - if allowRegexp != '' && filename !~ allowRegexp - elseif rejectRegexp != '' && filename =~ rejectRegexp - else - let dispFiles = dispFiles.filename."\n" - endif - endif - let i = i + 1 - endwhile - 0put!=dispFiles - 0put!=subDirs - " delte the last empty line resulting from the put - $ d_ - - call s:FB_SetHighlighting() - call s:FB_DisplayHelp() - call s:FB_SetMaps() - - " goto the first file/directory - 0 - call search('^"=', 'w') - normal! j:<bs> - - set nomodified nomodifiable - - call s:FB_ResetSilentSettings() -endfunction " }}} -" FB_SetVar: sets script local variables from outside this script {{{ -" Description: -function! FB_SetVar(varname, value) - let s:{a:varname} = a:value -endfunction " }}} - -" FB_SetHighlighting: sets syntax highlighting for the buffer {{{ -" Description: -" Origin: from explorer.vim in vim -function! <SID>FB_SetHighlighting() - " Set up syntax highlighting - " Something wrong with the evaluation of the conditional though... - if has("syntax") && exists("g:syntax_on") && !has("syntax_items") - syn match browseSynopsis "^\"[ -].*" - syn match browseDirectory "[^\"].*/ " - syn match browseDirectory "[^\"].*/$" - syn match browseCurDir "^\"= .*$" - syn match browseSortBy "^\" Sorted by .*$" contains=browseSuffixInfo - syn match browseSuffixInfo "(.*)$" contained - syn match browseFilter "^\" Not Showing:.*$" - syn match browseFiletime "«\d\+$" - - "hi def link browseSynopsis PreProc - hi def link browseSynopsis Special - hi def link browseDirectory Directory - hi def link browseCurDir Statement - hi def link browseSortBy String - hi def link browseSuffixInfo Type - hi def link browseFilter String - hi def link browseFiletime Ignore - hi def link browseSuffixes Type - endif -endfunction " }}} -" FB_SetMaps: sets buffer local maps {{{ -" Description: -function! <SID>FB_SetMaps() - nnoremap <buffer> <silent> q :bdelete<cr> - nnoremap <buffer> <silent> C :call FB_DisplayFiles(getcwd())<CR> - nnoremap <buffer> <silent> <esc> :bdelete<cr> - nnoremap <buffer> <silent> <CR> :call <SID>FB_EditEntry()<CR> - nnoremap <buffer> <silent> ? :call <SID>FB_ToggleHelp()<CR> - - " lock the user in this window - nnoremap <buffer> <C-w> <nop> -endfunction " }}} -" FB_SetSilentSettings: some settings which make things silent {{{ -" Description: -" Origin: from explorer.vim distributed with vim. -function! <SID>FB_SetSilentSettings() - let s:save_report=&report - let s:save_showcmd = &sc - set report=10000 noshowcmd -endfunction -" FB_ResetSilentSettings: reset settings set by FB_SetSilentSettings -" Description: -function! <SID>FB_ResetSilentSettings() - let &report=s:save_report - let &showcmd = s:save_showcmd -endfunction " }}} -" FB_SetScratchSettings: makes the present buffer a scratch buffer {{{ -" Description: -function! <SID>FB_SetScratchSettings() - " Turn off the swapfile, set the buffer type so that it won't get - " written, and so that it will get deleted when it gets hidden. - setlocal noreadonly modifiable - setlocal noswapfile - setlocal buftype=nowrite - setlocal bufhidden=delete - " Don't wrap around long lines - setlocal nowrap -endfunction - -" }}} -" FB_ToggleHelp: toggles verbosity of help {{{ -" Description: -function! <SID>FB_ToggleHelp() - let s:FB_VerboseHelp = 1 - s:FB_GetVar('FB_VerboseHelp', 0) - - call FB_DisplayFiles('.') -endfunction " }}} -" FB_DisplayHelp: displays a helpful header {{{ -" Description: -function! <SID>FB_DisplayHelp() - let verboseHelp = s:FB_GetVar('FB_VerboseHelp', 0) - if verboseHelp - let txt = - \ "\" <cr>: on file, choose the file and quit\n" - \ ."\" on dir, enter directory\n" - \ ."\" q/<esc>: quit without choosing\n" - \ ."\" C: change directory to getcwd()\n" - \ ."\" ?: toggle help verbosity\n" - \ ."\"= ".getcwd() - else - let txt = "\" ?: toggle help verbosity\n" - \ ."\"= ".getcwd() - endif - 0put!=txt -endfunction " }}} - -" Handles various actions in the file-browser -" FB_EditEntry: handles the user pressing <enter> on a line {{{ -" Description: -function! <SID>FB_EditEntry() - let line = getline('.') - - if isdirectory(line) - call FB_DisplayFiles(line) - endif - - " If the user has a call back function defined on choosing a file, handle - " it. - let cbf = s:FB_GetVar('FB_CallBackFunction', '') - if cbf != '' && line !~ '^" ' && filereadable(line) - let fname = fnamemodify(line, ':p') - bdelete - - let arguments = s:FB_GetVar('FB_CallBackFunctionArgs', '') - if arguments != '' - let arguments = ','.arguments - endif - call Tex_Debug('arguments = '.arguments, 'fb') - call Tex_Debug("call ".cbf."('".fname."'".arguments.')', 'fb') - exec "call ".cbf."('".fname."'".arguments.')' - endif -endfunction " }}} - -" FB_Strntok (string, tok, n) {{{ -" extract the n^th token from s seperated by tok. -" example: FB_Strntok('1,23,3', ',', 2) = 23 -fun! <SID>FB_Strntok(s, tok, n) - return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') -endfun " }}} -" FB_GetVar: gets the most local value of a variable {{{ -function! <SID>FB_GetVar(name, default) - if exists('s:'.a:name) - return s:{a:name} - elseif exists('w:'.a:name) - return w:{a:name} - elseif exists('b:'.a:name) - return b:{a:name} - elseif exists('g:'.a:name) - return g:{a:name} - else - return a:default - endif -endfunction - -" }}} - -let &cpo = s:save_cpo - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4:nowrap diff --git a/files/.vim/plugin/imaps.vim b/files/.vim/plugin/imaps.vim deleted file mode 100644 index d871aa1..0000000 --- a/files/.vim/plugin/imaps.vim +++ /dev/null @@ -1,831 +0,0 @@ -" File: imaps.vim -" Authors: Srinath Avadhanula <srinath AT fastmail.fm> -" Benji Fisher <benji AT member.AMS.org> -" -" WWW: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/vim-latex/vimfiles/plugin/imaps.vim?only_with_tag=MAIN -" -" Description: insert mode template expander with cursor placement -" while preserving filetype indentation. -" -" $Id: imaps.vim 997 2006-03-20 09:45:45Z srinathava $ -" -" Documentation: {{{ -" -" Motivation: -" this script provides a way to generate insert mode mappings which do not -" suffer from some of the problem of mappings and abbreviations while allowing -" cursor placement after the expansion. It can alternatively be thought of as -" a template expander. -" -" Consider an example. If you do -" -" imap lhs something -" -" then a mapping is set up. However, there will be the following problems: -" 1. the 'ttimeout' option will generally limit how easily you can type the -" lhs. if you type the left hand side too slowly, then the mapping will not -" be activated. -" 2. if you mistype one of the letters of the lhs, then the mapping is -" deactivated as soon as you backspace to correct the mistake. -" -" If, in order to take care of the above problems, you do instead -" -" iab lhs something -" -" then the timeout problem is solved and so is the problem of mistyping. -" however, abbreviations are only expanded after typing a non-word character. -" which causes problems of cursor placement after the expansion and invariably -" spurious spaces are inserted. -" -" Usage Example: -" this script attempts to solve all these problems by providing an emulation -" of imaps wchich does not suffer from its attendant problems. Because maps -" are activated without having to press additional characters, therefore -" cursor placement is possible. furthermore, file-type specific indentation is -" preserved, because the rhs is expanded as if the rhs is typed in literally -" by the user. -" -" The script already provides some default mappings. each "mapping" is of the -" form: -" -" call IMAP (lhs, rhs, ft) -" -" Some characters in the RHS have special meaning which help in cursor -" placement. -" -" Example One: -" -" call IMAP ("bit`", "\\begin{itemize}\<cr>\\item <++>\<cr>\\end{itemize}<++>", "tex") -" -" This effectively sets up the map for "bit`" whenever you edit a latex file. -" When you type in this sequence of letters, the following text is inserted: -" -" \begin{itemize} -" \item * -" \end{itemize}<++> -" -" where * shows the cursor position. The cursor position after inserting the -" text is decided by the position of the first "place-holder". Place holders -" are special characters which decide cursor placement and movement. In the -" example above, the place holder characters are <+ and +>. After you have typed -" in the item, press <C-j> and you will be taken to the next set of <++>'s. -" Therefore by placing the <++> characters appropriately, you can minimize the -" use of movement keys. -" -" NOTE: Set g:Imap_UsePlaceHolders to 0 to disable placeholders altogether. -" Set -" g:Imap_PlaceHolderStart and g:Imap_PlaceHolderEnd -" to something else if you want different place holder characters. -" Also, b:Imap_PlaceHolderStart and b:Imap_PlaceHolderEnd override the values -" of g:Imap_PlaceHolderStart and g:Imap_PlaceHolderEnd respectively. This is -" useful for setting buffer specific place hoders. -" -" Example Two: -" You can use the <C-r> command to insert dynamic elements such as dates. -" call IMAP ('date`', "\<c-r>=strftime('%b %d %Y')\<cr>", '') -" -" sets up the map for date` to insert the current date. -" -"--------------------------------------%<-------------------------------------- -" Bonus: This script also provides a command Snip which puts tearoff strings, -" '----%<----' above and below the visually selected range of lines. The -" length of the string is chosen to be equal to the longest line in the range. -" Recommended Usage: -" '<,'>Snip -"--------------------------------------%<-------------------------------------- -" }}} - -" line continuation used here. -let s:save_cpo = &cpo -set cpo&vim - -" ============================================================================== -" Script Options / Variables -" ============================================================================== -" Options {{{ -if !exists('g:Imap_StickyPlaceHolders') - let g:Imap_StickyPlaceHolders = 1 -endif -if !exists('g:Imap_DeleteEmptyPlaceHolders') - let g:Imap_DeleteEmptyPlaceHolders = 1 -endif -" }}} -" Variables {{{ -" s:LHS_{ft}_{char} will be generated automatically. It will look like -" s:LHS_tex_o = 'fo\|foo\|boo' and contain all mapped sequences ending in "o". -" s:Map_{ft}_{lhs} will be generated automatically. It will look like -" s:Map_c_foo = 'for(<++>; <++>; <++>)', the mapping for "foo". -" -" }}} - -" ============================================================================== -" functions for easy insert mode mappings. -" ============================================================================== -" IMAP: Adds a "fake" insert mode mapping. {{{ -" For example, doing -" IMAP('abc', 'def' ft) -" will mean that if the letters abc are pressed in insert mode, then -" they will be replaced by def. If ft != '', then the "mapping" will be -" specific to the files of type ft. -" -" Using IMAP has a few advantages over simply doing: -" imap abc def -" 1. with imap, if you begin typing abc, the cursor will not advance and -" long as there is a possible completion, the letters a, b, c will be -" displayed on on top of the other. using this function avoids that. -" 2. with imap, if a backspace or arrow key is pressed before completing -" the word, then the mapping is lost. this function allows movement. -" (this ofcourse means that this function is only limited to -" left-hand-sides which do not have movement keys or unprintable -" characters) -" It works by only mapping the last character of the left-hand side. -" when this character is typed in, then a reverse lookup is done and if -" the previous characters consititute the left hand side of the mapping, -" the previously typed characters and erased and the right hand side is -" inserted - -" IMAP: set up a filetype specific mapping. -" Description: -" "maps" the lhs to rhs in files of type 'ft'. If supplied with 2 -" additional arguments, then those are assumed to be the placeholder -" characters in rhs. If unspecified, then the placeholder characters -" are assumed to be '<+' and '+>' These placeholder characters in -" a:rhs are replaced with the users setting of -" [bg]:Imap_PlaceHolderStart and [bg]:Imap_PlaceHolderEnd settings. -" -function! IMAP(lhs, rhs, ft, ...) - - " Find the place holders to save for IMAP_PutTextWithMovement() . - if a:0 < 2 - let phs = '<+' - let phe = '+>' - else - let phs = a:1 - let phe = a:2 - endif - - let hash = s:Hash(a:lhs) - let s:Map_{a:ft}_{hash} = a:rhs - let s:phs_{a:ft}_{hash} = phs - let s:phe_{a:ft}_{hash} = phe - - " Add a:lhs to the list of left-hand sides that end with lastLHSChar: - let lastLHSChar = a:lhs[strlen(a:lhs)-1] - let hash = s:Hash(lastLHSChar) - if !exists("s:LHS_" . a:ft . "_" . hash) - let s:LHS_{a:ft}_{hash} = escape(a:lhs, '\') - else - let s:LHS_{a:ft}_{hash} = escape(a:lhs, '\') .'\|'. s:LHS_{a:ft}_{hash} - endif - - " map only the last character of the left-hand side. - if lastLHSChar == ' ' - let lastLHSChar = '<space>' - end - exe 'inoremap <silent>' - \ escape(lastLHSChar, '|') - \ '<C-r>=<SID>LookupCharacter("' . - \ escape(lastLHSChar, '\|"') . - \ '")<CR>' -endfunction - -" }}} -" IMAP_list: list the rhs and place holders corresponding to a:lhs {{{ -" -" Added mainly for debugging purposes, but maybe worth keeping. -function! IMAP_list(lhs) - let char = a:lhs[strlen(a:lhs)-1] - let charHash = s:Hash(char) - if exists("s:LHS_" . &ft ."_". charHash) && a:lhs =~ s:LHS_{&ft}_{charHash} - let ft = &ft - elseif exists("s:LHS__" . charHash) && a:lhs =~ s:LHS__{charHash} - let ft = "" - else - return "" - endif - let hash = s:Hash(a:lhs) - return "rhs = " . s:Map_{ft}_{hash} . " place holders = " . - \ s:phs_{ft}_{hash} . " and " . s:phe_{ft}_{hash} -endfunction -" }}} -" LookupCharacter: inserts mapping corresponding to this character {{{ -" -" This function extracts from s:LHS_{&ft}_{a:char} or s:LHS__{a:char} -" the longest lhs matching the current text. Then it replaces lhs with the -" corresponding rhs saved in s:Map_{ft}_{lhs} . -" The place-holder variables are passed to IMAP_PutTextWithMovement() . -function! s:LookupCharacter(char) - if IMAP_GetVal('Imap_FreezeImap', 0) == 1 - return a:char - endif - let charHash = s:Hash(a:char) - - " The line so far, including the character that triggered this function: - let text = strpart(getline("."), 0, col(".")-1) . a:char - " Prefer a local map to a global one, even if the local map is shorter. - " Is this what we want? Do we care? - " Use '\V' (very no-magic) so that only '\' is special, and it was already - " escaped when building up s:LHS_{&ft}_{charHash} . - if exists("s:LHS_" . &ft . "_" . charHash) - \ && text =~ "\\C\\V\\(" . s:LHS_{&ft}_{charHash} . "\\)\\$" - let ft = &ft - elseif exists("s:LHS__" . charHash) - \ && text =~ "\\C\\V\\(" . s:LHS__{charHash} . "\\)\\$" - let ft = "" - else - " If this is a character which could have been used to trigger an - " abbreviation, check if an abbreviation exists. - if a:char !~ '\k' - let lastword = matchstr(getline('.'), '\k\+$', '') - call IMAP_Debug('getting lastword = ['.lastword.']', 'imap') - if lastword != '' - " An extremeley wierd way to get around the fact that vim - " doesn't have the equivalent of the :mapcheck() function for - " abbreviations. - let _a = @a - exec "redir @a | silent! iab ".lastword." | redir END" - let abbreviationRHS = matchstr(@a."\n", "\n".'i\s\+'.lastword.'\s\+@\?\zs.*\ze'."\n") - - call IMAP_Debug('getting abbreviationRHS = ['.abbreviationRHS.']', 'imap') - - if @a =~ "No abbreviation found" || abbreviationRHS == "" - let @a = _a - return a:char - endif - - let @a = _a - let abbreviationRHS = escape(abbreviationRHS, '\<"') - exec 'let abbreviationRHS = "'.abbreviationRHS.'"' - - let lhs = lastword.a:char - let rhs = abbreviationRHS.a:char - let phs = IMAP_GetPlaceHolderStart() - let phe = IMAP_GetPlaceHolderEnd() - else - return a:char - endif - else - return a:char - endif - endif - " Find the longest left-hand side that matches the line so far. - " matchstr() returns the match that starts first. This automatically - " ensures that the longest LHS is used for the mapping. - if !exists('lhs') || !exists('rhs') - let lhs = matchstr(text, "\\C\\V\\(" . s:LHS_{ft}_{charHash} . "\\)\\$") - let hash = s:Hash(lhs) - let rhs = s:Map_{ft}_{hash} - let phs = s:phs_{ft}_{hash} - let phe = s:phe_{ft}_{hash} - endif - - if strlen(lhs) == 0 - return a:char - endif - " enough back-spaces to erase the left-hand side; -1 for the last - " character typed: - let bs = substitute(strpart(lhs, 1), ".", "\<bs>", "g") - return bs . IMAP_PutTextWithMovement(rhs, phs, phe) -endfunction - -" }}} -" IMAP_PutTextWithMovement: returns the string with movement appended {{{ -" Description: -" If a:str contains "placeholders", then appends movement commands to -" str in a way that the user moves to the first placeholder and enters -" insert or select mode. If supplied with 2 additional arguments, then -" they are assumed to be the placeholder specs. Otherwise, they are -" assumed to be '<+' and '+>'. These placeholder chars are replaced -" with the users settings of [bg]:Imap_PlaceHolderStart and -" [bg]:Imap_PlaceHolderEnd. -function! IMAP_PutTextWithMovement(str, ...) - - " The placeholders used in the particular input string. These can be - " different from what the user wants to use. - if a:0 < 2 - let phs = '<+' - let phe = '+>' - else - let phs = escape(a:1, '\') - let phe = escape(a:2, '\') - endif - - let text = a:str - - " The user's placeholder settings. - let phsUser = IMAP_GetPlaceHolderStart() - let pheUser = IMAP_GetPlaceHolderEnd() - - " Problem: depending on the setting of the 'encoding' option, a character - " such as "\xab" may not match itself. We try to get around this by - " changing the encoding of all our strings. At the end, we have to - " convert text back. - let phsEnc = s:Iconv(phs, "encode") - let pheEnc = s:Iconv(phe, "encode") - let phsUserEnc = s:Iconv(phsUser, "encode") - let pheUserEnc = s:Iconv(pheUser, "encode") - let textEnc = s:Iconv(text, "encode") - if textEnc != text - let textEncoded = 1 - else - let textEncoded = 0 - endif - - let pattern = '\V\(\.\{-}\)' .phs. '\(\.\{-}\)' .phe. '\(\.\*\)' - " If there are no placeholders, just return the text. - if textEnc !~ pattern - call IMAP_Debug('Not getting '.phs.' and '.phe.' in '.textEnc, 'imap') - return text - endif - " Break text up into "initial <+template+> final"; any piece may be empty. - let initialEnc = substitute(textEnc, pattern, '\1', '') - let templateEnc = substitute(textEnc, pattern, '\2', '') - let finalEnc = substitute(textEnc, pattern, '\3', '') - - " If the user does not want to use placeholders, then remove all but the - " first placeholder. - " Otherwise, replace all occurences of the placeholders here with the - " user's choice of placeholder settings. - if exists('g:Imap_UsePlaceHolders') && !g:Imap_UsePlaceHolders - let finalEnc = substitute(finalEnc, '\V'.phs.'\.\{-}'.phe, '', 'g') - else - let finalEnc = substitute(finalEnc, '\V'.phs.'\(\.\{-}\)'.phe, - \ phsUserEnc.'\1'.pheUserEnc, 'g') - endif - - " The substitutions are done, so convert back, if necessary. - if textEncoded - let initial = s:Iconv(initialEnc, "decode") - let template = s:Iconv(templateEnc, "decode") - let final = s:Iconv(finalEnc, "decode") - else - let initial = initialEnc - let template = templateEnc - let final = finalEnc - endif - - " Build up the text to insert: - " 1. the initial text plus an extra character; - " 2. go to Normal mode with <C-\><C-N>, so it works even if 'insertmode' - " is set, and mark the position; - " 3. replace the extra character with tamplate and final; - " 4. back to Normal mode and restore the cursor position; - " 5. call IMAP_Jumpfunc(). - let template = phsUser . template . pheUser - " Old trick: insert and delete a character to get the same behavior at - " start, middle, or end of line and on empty lines. - let text = initial . "X\<C-\>\<C-N>:call IMAP_Mark('set')\<CR>\"_s" - let text = text . template . final - let text = text . "\<C-\>\<C-N>:call IMAP_Mark('go')\<CR>" - let text = text . "i\<C-r>=IMAP_Jumpfunc('', 1)\<CR>" - - call IMAP_Debug('IMAP_PutTextWithMovement: text = ['.text.']', 'imap') - return text -endfunction - -" }}} -" IMAP_Jumpfunc: takes user to next <+place-holder+> {{{ -" Author: Luc Hermitte -" Arguments: -" direction: flag for the search() function. If set to '', search forwards, -" if 'b', then search backwards. See the {flags} argument of the -" |search()| function for valid values. -" inclusive: In vim, the search() function is 'exclusive', i.e we always goto -" next cursor match even if there is a match starting from the -" current cursor position. Setting this argument to 1 makes -" IMAP_Jumpfunc() also respect a match at the current cursor -" position. 'inclusive'ness is necessary for IMAP() because a -" placeholder string can occur at the very beginning of a map which -" we want to select. -" We use a non-zero value only in special conditions. Most mappings -" should use a zero value. -function! IMAP_Jumpfunc(direction, inclusive) - - " The user's placeholder settings. - let phsUser = IMAP_GetPlaceHolderStart() - let pheUser = IMAP_GetPlaceHolderEnd() - - let searchString = '' - " If this is not an inclusive search or if it is inclusive, but the - " current cursor position does not contain a placeholder character, then - " search for the placeholder characters. - if !a:inclusive || strpart(getline('.'), col('.')-1) !~ '\V\^'.phsUser - let searchString = '\V'.phsUser.'\_.\{-}'.pheUser - endif - - " If we didn't find any placeholders return quietly. - if searchString != '' && !search(searchString, a:direction) - return '' - endif - - " Open any closed folds and make this part of the text visible. - silent! foldopen! - - " Calculate if we have an empty placeholder or if it contains some - " description. - let template = - \ matchstr(strpart(getline('.'), col('.')-1), - \ '\V\^'.phsUser.'\zs\.\{-}\ze\('.pheUser.'\|\$\)') - let placeHolderEmpty = !strlen(template) - - " If we are selecting in exclusive mode, then we need to move one step to - " the right - let extramove = '' - if &selection == 'exclusive' - let extramove = 'l' - endif - - " Select till the end placeholder character. - let movement = "\<C-o>v/\\V".pheUser."/e\<CR>".extramove - - " First remember what the search pattern was. s:RemoveLastHistoryItem will - " reset @/ to this pattern so we do not create new highlighting. - let g:Tex_LastSearchPattern = @/ - - " Now either goto insert mode or select mode. - if placeHolderEmpty && g:Imap_DeleteEmptyPlaceHolders - " delete the empty placeholder into the blackhole. - return movement."\"_c\<C-o>:".s:RemoveLastHistoryItem."\<CR>" - else - return movement."\<C-\>\<C-N>:".s:RemoveLastHistoryItem."\<CR>gv\<C-g>" - endif - -endfunction - -" }}} -" Maps for IMAP_Jumpfunc {{{ -" -" These mappings use <Plug> and thus provide for easy user customization. When -" the user wants to map some other key to jump forward, he can do for -" instance: -" nmap ,f <plug>IMAP_JumpForward -" etc. - -" jumping forward and back in insert mode. -imap <silent> <Plug>IMAP_JumpForward <c-r>=IMAP_Jumpfunc('', 0)<CR> -imap <silent> <Plug>IMAP_JumpBack <c-r>=IMAP_Jumpfunc('b', 0)<CR> - -" jumping in normal mode -nmap <silent> <Plug>IMAP_JumpForward i<c-r>=IMAP_Jumpfunc('', 0)<CR> -nmap <silent> <Plug>IMAP_JumpBack i<c-r>=IMAP_Jumpfunc('b', 0)<CR> - -" deleting the present selection and then jumping forward. -vmap <silent> <Plug>IMAP_DeleteAndJumpForward "_<Del>i<c-r>=IMAP_Jumpfunc('', 0)<CR> -vmap <silent> <Plug>IMAP_DeleteAndJumpBack "_<Del>i<c-r>=IMAP_Jumpfunc('b', 0)<CR> - -" jumping forward without deleting present selection. -vmap <silent> <Plug>IMAP_JumpForward <C-\><C-N>i<c-r>=IMAP_Jumpfunc('', 0)<CR> -vmap <silent> <Plug>IMAP_JumpBack <C-\><C-N>`<i<c-r>=IMAP_Jumpfunc('b', 0)<CR> - -" }}} -" Default maps for IMAP_Jumpfunc {{{ -" map only if there is no mapping already. allows for user customization. -" NOTE: Default mappings for jumping to the previous placeholder are not -" provided. It is assumed that if the user will create such mappings -" hself if e so desires. -if !hasmapto('<Plug>IMAP_JumpForward', 'i') - imap <C-J> <Plug>IMAP_JumpForward -endif -if !hasmapto('<Plug>IMAP_JumpForward', 'n') - nmap <C-J> <Plug>IMAP_JumpForward -endif -if exists('g:Imap_StickyPlaceHolders') && g:Imap_StickyPlaceHolders - if !hasmapto('<Plug>IMAP_JumpForward', 'v') - vmap <C-J> <Plug>IMAP_JumpForward - endif -else - if !hasmapto('<Plug>IMAP_DeleteAndJumpForward', 'v') - vmap <C-J> <Plug>IMAP_DeleteAndJumpForward - endif -endif -" }}} - -nmap <silent> <script> <plug><+SelectRegion+> `<v`> - -" ============================================================================== -" enclosing selected region. -" ============================================================================== -" VEnclose: encloses the visually selected region with given arguments {{{ -" Description: allows for differing action based on visual line wise -" selection or visual characterwise selection. preserves the -" marks and search history. -function! VEnclose(vstart, vend, VStart, VEnd) - - " its characterwise if - " 1. characterwise selection and valid values for vstart and vend. - " OR - " 2. linewise selection and invalid values for VStart and VEnd - if (visualmode() == 'v' && (a:vstart != '' || a:vend != '')) || (a:VStart == '' && a:VEnd == '') - - let newline = "" - let _r = @r - - let normcmd = "normal! \<C-\>\<C-n>`<v`>\"_s" - - exe "normal! \<C-\>\<C-n>`<v`>\"ry" - if @r =~ "\n$" - let newline = "\n" - let @r = substitute(@r, "\n$", '', '') - endif - - " In exclusive selection, we need to select an extra character. - if &selection == 'exclusive' - let movement = 8 - else - let movement = 7 - endif - let normcmd = normcmd. - \ a:vstart."!!mark!!".a:vend.newline. - \ "\<C-\>\<C-N>?!!mark!!\<CR>v".movement."l\"_s\<C-r>r\<C-\>\<C-n>" - - " this little if statement is because till very recently, vim used to - " report col("'>") > length of selected line when `> is $. on some - " systems it reports a -ve number. - if col("'>") < 0 || col("'>") > strlen(getline("'>")) - let lastcol = strlen(getline("'>")) - else - let lastcol = col("'>") - endif - if lastcol - col("'<") != 0 - let len = lastcol - col("'<") - else - let len = '' - endif - - " the next normal! is for restoring the marks. - let normcmd = normcmd."`<v".len."l\<C-\>\<C-N>" - - " First remember what the search pattern was. s:RemoveLastHistoryItem - " will reset @/ to this pattern so we do not create new highlighting. - let g:Tex_LastSearchPattern = @/ - - silent! exe normcmd - " this is to restore the r register. - let @r = _r - " and finally, this is to restore the search history. - execute s:RemoveLastHistoryItem - - else - - exec 'normal! `<O'.a:VStart."\<C-\>\<C-n>" - exec 'normal! `>o'.a:VEnd."\<C-\>\<C-n>" - if &indentexpr != '' - silent! normal! `<kV`>j= - endif - silent! normal! `> - endif -endfunction - -" }}} -" ExecMap: adds the ability to correct an normal/visual mode mapping. {{{ -" Author: Hari Krishna Dara <hari_vim@yahoo.com> -" Reads a normal mode mapping at the command line and executes it with the -" given prefix. Press <BS> to correct and <Esc> to cancel. -function! ExecMap(prefix, mode) - " Temporarily remove the mapping, otherwise it will interfere with the - " mapcheck call below: - let myMap = maparg(a:prefix, a:mode) - exec a:mode."unmap ".a:prefix - - " Generate a line with spaces to clear the previous message. - let i = 1 - let clearLine = "\r" - while i < &columns - let clearLine = clearLine . ' ' - let i = i + 1 - endwhile - - let mapCmd = a:prefix - let foundMap = 0 - let breakLoop = 0 - echon "\rEnter Map: " . mapCmd - while !breakLoop - let char = getchar() - if char !~ '^\d\+$' - if char == "\<BS>" - let mapCmd = strpart(mapCmd, 0, strlen(mapCmd) - 1) - endif - else " It is the ascii code. - let char = nr2char(char) - if char == "\<Esc>" - let breakLoop = 1 - else - let mapCmd = mapCmd . char - if maparg(mapCmd, a:mode) != "" - let foundMap = 1 - let breakLoop = 1 - elseif mapcheck(mapCmd, a:mode) == "" - let mapCmd = strpart(mapCmd, 0, strlen(mapCmd) - 1) - endif - endif - endif - echon clearLine - echon "\rEnter Map: " . mapCmd - endwhile - if foundMap - if a:mode == 'v' - " use a plug to select the region instead of using something like - " `<v`> to avoid problems caused by some of the characters in - " '`<v`>' being mapped. - let gotoc = "\<plug><+SelectRegion+>" - else - let gotoc = '' - endif - exec "normal ".gotoc.mapCmd - endif - exec a:mode.'noremap '.a:prefix.' '.myMap -endfunction - -" }}} - -" ============================================================================== -" helper functions -" ============================================================================== -" Strntok: extract the n^th token from a list {{{ -" example: Strntok('1,23,3', ',', 2) = 23 -fun! <SID>Strntok(s, tok, n) - return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') -endfun - -" }}} -" s:RemoveLastHistoryItem: removes last search item from search history {{{ -" Description: Execute this string to clean up the search history. -let s:RemoveLastHistoryItem = ':call histdel("/", -1)|let @/=g:Tex_LastSearchPattern' - -" }}} -" s:Hash: Return a version of a string that can be used as part of a variable" {{{ -" name. -" Converts every non alphanumeric character into _{ascii}_ where {ascii} is -" the ASCII code for that character... -fun! s:Hash(text) - return substitute(a:text, '\([^[:alnum:]]\)', - \ '\="_".char2nr(submatch(1))."_"', 'g') -endfun -"" }}} -" IMAP_GetPlaceHolderStart and IMAP_GetPlaceHolderEnd: "{{{ -" return the buffer local placeholder variables, or the global one, or the default. -function! IMAP_GetPlaceHolderStart() - if exists("b:Imap_PlaceHolderStart") && strlen(b:Imap_PlaceHolderEnd) - return b:Imap_PlaceHolderStart - elseif exists("g:Imap_PlaceHolderStart") && strlen(g:Imap_PlaceHolderEnd) - return g:Imap_PlaceHolderStart - else - return "<+" -endfun -function! IMAP_GetPlaceHolderEnd() - if exists("b:Imap_PlaceHolderEnd") && strlen(b:Imap_PlaceHolderEnd) - return b:Imap_PlaceHolderEnd - elseif exists("g:Imap_PlaceHolderEnd") && strlen(g:Imap_PlaceHolderEnd) - return g:Imap_PlaceHolderEnd - else - return "+>" -endfun -" }}} -" s:Iconv: a wrapper for iconv()" {{{ -" Problem: after -" let text = "\xab" -" (or using the raw 8-bit ASCII character in a file with 'fenc' set to -" "latin1") if 'encoding' is set to utf-8, then text does not match itself: -" echo text =~ text -" returns 0. -" Solution: When this happens, a re-encoded version of text does match text: -" echo iconv(text, "latin1", "utf8") =~ text -" returns 1. In this case, convert text to utf-8 with iconv(). -" TODO: Is it better to use &encoding instead of "utf8"? Internally, vim -" uses utf-8, and can convert between latin1 and utf-8 even when compiled with -" -iconv, so let's try using utf-8. -" Arguments: -" a:text = text to be encoded or decoded -" a:mode = "encode" (latin1 to utf8) or "decode" (utf8 to latin1) -" Caution: do not encode and then decode without checking whether the text -" has changed, becuase of the :if clause in encoding! -function! s:Iconv(text, mode) - if a:mode == "decode" - return iconv(a:text, "utf8", "latin1") - endif - if a:text =~ '\V\^' . escape(a:text, '\') . '\$' - return a:text - endif - let textEnc = iconv(a:text, "latin1", "utf8") - if textEnc !~ '\V\^' . escape(a:text, '\') . '\$' - call IMAP_Debug('Encoding problems with text '.a:text.' ', 'imap') - endif - return textEnc -endfun -"" }}} -" IMAP_Debug: interface to Tex_Debug if available, otherwise emulate it {{{ -" Description: -" Do not want a memory leak! Set this to zero so that imaps always -" starts out in a non-debugging mode. -if !exists('g:Imap_Debug') - let g:Imap_Debug = 0 -endif -function! IMAP_Debug(string, pattern) - if !g:Imap_Debug - return - endif - if exists('*Tex_Debug') - call Tex_Debug(a:string, a:pattern) - else - if !exists('s:debug_'.a:pattern) - let s:debug_{a:pattern} = a:string - else - let s:debug_{a:pattern} = s:debug_{a:pattern}.a:string - endif - endif -endfunction " }}} -" IMAP_DebugClear: interface to Tex_DebugClear if avaialable, otherwise emulate it {{{ -" Description: -function! IMAP_DebugClear(pattern) - if exists('*Tex_DebugClear') - call Tex_DebugClear(a:pattern) - else - let s:debug_{a:pattern} = '' - endif -endfunction " }}} -" IMAP_PrintDebug: interface to Tex_DebugPrint if avaialable, otherwise emulate it {{{ -" Description: -function! IMAP_PrintDebug(pattern) - if exists('*Tex_PrintDebug') - call Tex_PrintDebug(a:pattern) - else - if exists('s:debug_'.a:pattern) - echo s:debug_{a:pattern} - endif - endif -endfunction " }}} -" IMAP_Mark: Save the cursor position (if a:action == 'set') in a" {{{ -" script-local variable; restore this position if a:action == 'go'. -let s:Mark = "(0,0)" -let s:initBlanks = '' -function! IMAP_Mark(action) - if a:action == 'set' - let s:Mark = "(" . line(".") . "," . col(".") . ")" - let s:initBlanks = matchstr(getline('.'), '^\s*') - elseif a:action == 'go' - execute "call cursor" s:Mark - let blanksNow = matchstr(getline('.'), '^\s*') - if strlen(blanksNow) > strlen(s:initBlanks) - execute 'silent! normal! '.(strlen(blanksNow) - strlen(s:initBlanks)).'l' - elseif strlen(blanksNow) < strlen(s:initBlanks) - execute 'silent! normal! '.(strlen(s:initBlanks) - strlen(blanksNow)).'h' - endif - endif -endfunction "" }}} -" IMAP_GetVal: gets the value of a variable {{{ -" Description: first checks window local, then buffer local etc. -function! IMAP_GetVal(name, ...) - if a:0 > 0 - let default = a:1 - else - let default = '' - endif - if exists('w:'.a:name) - return w:{a:name} - elseif exists('b:'.a:name) - return b:{a:name} - elseif exists('g:'.a:name) - return g:{a:name} - else - return default - endif -endfunction " }}} - -" ============================================================================== -" A bonus function: Snip() -" ============================================================================== -" Snip: puts a scissor string above and below block of text {{{ -" Desciption: -"-------------------------------------%<------------------------------------- -" this puts a the string "--------%<---------" above and below the visually -" selected block of lines. the length of the 'tearoff' string depends on the -" maximum string length in the selected range. this is an aesthetically more -" pleasing alternative instead of hardcoding a length. -"-------------------------------------%<------------------------------------- -function! <SID>Snip() range - let i = a:firstline - let maxlen = -2 - " find out the maximum virtual length of each line. - while i <= a:lastline - exe i - let length = virtcol('$') - let maxlen = (length > maxlen ? length : maxlen) - let i = i + 1 - endwhile - let maxlen = (maxlen > &tw && &tw != 0 ? &tw : maxlen) - let half = maxlen/2 - exe a:lastline - " put a string below - exe "norm! o\<esc>".(half - 1)."a-\<esc>A%<\<esc>".(half - 1)."a-" - " and above. its necessary to put the string below the block of lines - " first because that way the first line number doesnt change... - exe a:firstline - exe "norm! O\<esc>".(half - 1)."a-\<esc>A%<\<esc>".(half - 1)."a-" -endfunction - -com! -nargs=0 -range Snip :<line1>,<line2>call <SID>Snip() -" }}} - -let &cpo = s:save_cpo - -" vim:ft=vim:ts=4:sw=4:noet:fdm=marker:commentstring=\"\ %s:nowrap diff --git a/files/.vim/plugin/libList.vim b/files/.vim/plugin/libList.vim deleted file mode 100644 index 7d72c3e..0000000 --- a/files/.vim/plugin/libList.vim +++ /dev/null @@ -1,249 +0,0 @@ -" File: libList.vim -" Last Change: 2001 Dec 10 -" Maintainer: Gontran BAERTS <gbcreation@free.fr> -" Version: 0.1 -" -" Please don't hesitate to correct my english :) -" Send corrections to <gbcreation@free.fr> -" -"----------------------------------------------------------------------------- -" Description: libList.vim is a set of functions to work with lists or one -" level arrays. -" -"----------------------------------------------------------------------------- -" To Enable: Normally, this file will reside in your plugins directory and be -" automatically sourced. -" -"----------------------------------------------------------------------------- -" Usage: Lists are strings variable with values separated by g:listSep -" character (comma" by default). You may redefine g:listSep variable as you -" wish. -" -" Here are available functions : -" -" - AddListItem( array, newItem, index ) : -" Add item "newItem" to array "array" at "index" position -" - GetListItem( array, index ) : -" Return item at "index" position in array "array" -" - GetListMatchItem( array, pattern ) : -" Return item matching "pattern" in array "array" -" - GetListCount( array ) : -" Return the number of items in array "array" -" - RemoveListItem( array, index ) : -" Remove item at "index" position from array "array" -" - ReplaceListItem( array, index, item ) : -" Remove item at "index" position by "item" in array "array" -" - ExchangeListItems( array, item1Index, item2Index ) : -" Exchange item "item1Index" with item "item2Index" in array "array" -" - QuickSortList( array, beg, end ) : -" Return array "array" with items between "beg" and "end" sorted -" -" Example: -" let mylist="" -" echo GetListCount( mylist ) " --> 0 -" let mylist = AddListItem( mylist, "One", 0 ) " mylist == "One" -" let mylist = AddListItem( mylist, "Three", 1 ) " mylist == "One,Three" -" let mylist = AddListItem( mylist, "Two", 1 ) " mylist == "One,Two,Three" -" echo GetListCount( mylist ) " --> 3 -" echo GetListItem( mylist, 2 ) " --> Three -" echo GetListMatchItem( mylist, "w" ) " --> two -" echo GetListMatchItem( mylist, "e" ) " --> One -" let mylist = RemoveListItem( mylist, 2 ) " mylist == "One,Two" -" echo GetListCount( mylist ) " --> 2 -" let mylist = ReplaceListItem( mylist, 0, "Three" ) " mylist == "Three,Two" -" let mylist = ExchangeListItems( mylist, 0, 1 ) " mylist == "Two,Three" -" let mylist = AddListItem( mylist, "One", 0 ) " mylist == "One,Two,Three" -" let mylist = QuickSortList( mylist, 0, GetListCount(mylist)-1 ) -" " mylist == "One,Three,Two" -" -"----------------------------------------------------------------------------- -" Updates: -" in version 0.1 -" - First version - -" Has this already been loaded ? -if exists("loaded_libList") - finish -endif -let loaded_libList=1 - -"** -" Separator: -" You may change the separator character et any time. -"** -let g:listSep = "," - -"** -"AddListItem: -" Add new item at given position. -" First item index is 0 (zero). -"Parameters: -" - array : Array/List (string of values) which receives the new item. -" - newItem : String containing the item value to add. -" - index : Integer indicating the position at which the new item is added. -" It must be greater than or equals to 0 (zero). -"Return: -"String containing array values, including newItem. -"** -function AddListItem( array, newItem, index ) - if a:index == 0 - if a:array == "" - return a:newItem - endif - return a:newItem . g:listSep . a:array - endif - return substitute( a:array, '\(\%(^\|' . g:listSep . '\)[^' . g:listSep . ']\+\)\{' . a:index . '\}', '\0' . g:listSep . a:newItem , "" ) -endfunction - -"** -"GetListItem: -" Get item at given position. -"Parameters: -" - array : Array/List (string of values). -" - index : Integer indicating the position of item to return. -" It must be greater than or equals to 0 (zero). -"Return: -"String representing the item. -"** -function GetListItem( array, index ) - if a:index == 0 - return matchstr( a:array, '^[^' . g:listSep . ']\+' ) - else - return matchstr( a:array, "[^" . g:listSep . "]\\+", matchend( a:array, '\(\%(^\|' . g:listSep . '\)[^' . g:listSep . ']\+\)\{' . a:index . '\}' . g:listSep ) ) - endif -endfunction - -"** -"GetListMatchItem: -" Get the first item matching given pattern. -"Parameters: -" - array : Array/List (string of values). -" - pattern : Regular expression to match with items. -" Avoid to use ^, $ and listSep characters in pattern, unless you -" know what you do. -"Return: -"String representing the first item that matches the pattern. -"** -function GetListMatchItem( array, pattern ) - return matchstr( a:array, '[^' . g:listSep . ']*' . a:pattern . '[^' . g:listSep . ']*' ) -endfunction - -"** -"ReplaceListItem: -" Replace item at given position by a new one. -"Parameters: -" - array : Array/List (string of values). -" - index : Integer indicating the position of item to replace. -" It must be greater than or equals to 0 (zero). -" - item : String containing the new value of the replaced item. -"Return: -"String containing array values. -"** -function ReplaceListItem( array, index, item ) - if a:index == 0 - return substitute( a:array, '^[^' .g:listSep. ']\+', a:item, "" ) - else - return substitute( a:array, '\(\%(\%(^\|' . g:listSep . '\)[^' . g:listSep . ']\+\)\{' . a:index . '\}\)' . g:listSep . '[^' . g:listSep . ']\+', '\1' . g:listSep . a:item , "" ) - endif -endfunction - -"** -"RemoveListItem: -" Remove item at given position. -"Parameters: -" - array : Array/List (string of values) from which remove an item. -" - index : Integer indicating the position of item to remove. -" It must be greater than or equals to 0 (zero). -"Return: -"String containing array values, except the removed one. -"** -function RemoveListItem( array, index ) - if a:index == 0 - return substitute( a:array, '^[^' .g:listSep. ']\+\(' . g:listSep . '\|$\)', "", "" ) - else - return substitute( a:array, '\(\%(\%(^\|' . g:listSep . '\)[^' . g:listSep . ']\+\)\{' . a:index . '\}\)' . g:listSep . '[^' . g:listSep . ']\+', '\1', "" ) - endif -endfunction - -"** -"ExchangeListItems: -" Exchange item at position item1Index with item at position item2Index. -"Parameters: -" - array : Array/List (string of values). -" - item1index : Integer indicating the position of the first item to exchange. -" It must be greater than or equals to 0 (zero). -" - item2index : Integer indicating the position of the second item to -" exchange. It must be greater than or equals to 0 (zero). -"Return: -"String containing array values. -"** -function ExchangeListItems( array, item1Index, item2Index ) - let item1 = GetListItem( a:array, a:item1Index ) - let array = ReplaceListItem( a:array, a:item1Index, GetListItem( a:array, a:item2Index ) ) - return ReplaceListItem( array, a:item2Index, item1 ) -endfunction - -"** -"GetListCount: -" Number of items in array. -"Parameters: -" - array : Array/List (string of values). -"Return: -"Integer representing the number of items in array. -"Index of last item is GetListCount(array)-1. -"** -function GetListCount( array ) - if a:array == "" | return 0 | endif - let pos = 0 - let cnt = 0 - while pos != -1 - let pos = matchend( a:array, g:listSep, pos ) - let cnt = cnt + 1 - endwhile - return cnt -endfunction - -"** -"QuickSortList: -" Sort array. -"Parameters: -" - array : Array/List (string of values). -" - beg : Min index of the range of items to sort. -" - end : Max index of the range of items to sort. -"Return: -"String containing array values with indicated range of items sorted. -"** -function QuickSortList( array, beg, end ) - let array = a:array - let pivot = GetListItem( array, a:beg ) - let l = a:beg - let r = a:end - while l < r - while GetListItem( array, r ) > pivot - let r = r - 1 - endwhile - if l != r - let array = ReplaceListItem( array, l, GetListItem( array, r ) ) - let array = ReplaceListItem( array, r, pivot ) - let l = l + 1 - endif - - while GetListItem( array, l ) < pivot - let l = l + 1 - endwhile - if l != r - let array = ReplaceListItem( array, r, GetListItem( array, l ) ) - let array = ReplaceListItem( array, l, pivot ) - let r = r - 1 - endif - endwhile - if a:beg < l-1 - let array = QuickSortList( array, a:beg, l-1 ) - endif - if a:end > l+1 - let array = QuickSortList( array, l+1, a:end ) - endif - return array -endfunction - - diff --git a/files/.vim/plugin/matchit.vim b/files/.vim/plugin/matchit.vim deleted file mode 100644 index 549c26c..0000000 --- a/files/.vim/plugin/matchit.vim +++ /dev/null @@ -1,812 +0,0 @@ -" matchit.vim: (global plugin) Extended "%" matching -" Last Change: Fri Jan 25 10:00 AM 2008 EST -" Maintainer: Benji Fisher PhD <benji@member.AMS.org> -" Version: 1.13.2, for Vim 6.3+ -" URL: http://www.vim.org/script.php?script_id=39 - -" Documentation: -" The documentation is in a separate file, matchit.txt . - -" Credits: -" Vim editor by Bram Moolenaar (Thanks, Bram!) -" Original script and design by Raul Segura Acevedo -" Support for comments by Douglas Potts -" Support for back references and other improvements by Benji Fisher -" Support for many languages by Johannes Zellner -" Suggestions for improvement, bug reports, and support for additional -" languages by Jordi-Albert Batalla, Neil Bird, Servatius Brandt, Mark -" Collett, Stephen Wall, Dany St-Amant, Yuheng Xie, and Johannes Zellner. - -" Debugging: -" If you'd like to try the built-in debugging commands... -" :MatchDebug to activate debugging for the current buffer -" This saves the values of several key script variables as buffer-local -" variables. See the MatchDebug() function, below, for details. - -" TODO: I should think about multi-line patterns for b:match_words. -" This would require an option: how many lines to scan (default 1). -" This would be useful for Python, maybe also for *ML. -" TODO: Maybe I should add a menu so that people will actually use some of -" the features that I have implemented. -" TODO: Eliminate the MultiMatch function. Add yet another argument to -" Match_wrapper() instead. -" TODO: Allow :let b:match_words = '\(\(foo\)\(bar\)\):\3\2:end\1' -" TODO: Make backrefs safer by using '\V' (very no-magic). -" TODO: Add a level of indirection, so that custom % scripts can use my -" work but extend it. - -" allow user to prevent loading -" and prevent duplicate loading -if exists("loaded_matchit") || &cp - finish -endif -let loaded_matchit = 1 -let s:last_mps = "" -let s:last_words = ":" - -let s:save_cpo = &cpo -set cpo&vim - -nnoremap <silent> % :<C-U>call <SID>Match_wrapper('',1,'n') <CR> -nnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'n') <CR> -vnoremap <silent> % :<C-U>call <SID>Match_wrapper('',1,'v') <CR>m'gv`` -vnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'v') <CR>m'gv`` -onoremap <silent> % v:<C-U>call <SID>Match_wrapper('',1,'o') <CR> -onoremap <silent> g% v:<C-U>call <SID>Match_wrapper('',0,'o') <CR> - -" Analogues of [{ and ]} using matching patterns: -nnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "n") <CR> -nnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W", "n") <CR> -vmap [% <Esc>[%m'gv`` -vmap ]% <Esc>]%m'gv`` -" vnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "v") <CR>m'gv`` -" vnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W", "v") <CR>m'gv`` -onoremap <silent> [% v:<C-U>call <SID>MultiMatch("bW", "o") <CR> -onoremap <silent> ]% v:<C-U>call <SID>MultiMatch("W", "o") <CR> - -" text object: -vmap a% <Esc>[%v]% - -" Auto-complete mappings: (not yet "ready for prime time") -" TODO Read :help write-plugin for the "right" way to let the user -" specify a key binding. -" let g:match_auto = '<C-]>' -" let g:match_autoCR = '<C-CR>' -" if exists("g:match_auto") -" execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls' -" endif -" if exists("g:match_autoCR") -" execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>' -" endif -" if exists("g:match_gthhoh") -" execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>' -" endif " gthhoh = "Get the heck out of here!" - -let s:notslash = '\\\@<!\%(\\\\\)*' - -function! s:Match_wrapper(word, forward, mode) range - " In s:CleanUp(), :execute "set" restore_options . - let restore_options = (&ic ? " " : " no") . "ignorecase" - if exists("b:match_ignorecase") - let &ignorecase = b:match_ignorecase - endif - let restore_options = " ve=" . &ve . restore_options - set ve= - " If this function was called from Visual mode, make sure that the cursor - " is at the correct end of the Visual range: - if a:mode == "v" - execute "normal! gv\<Esc>" - endif - " In s:CleanUp(), we may need to check whether the cursor moved forward. - let startline = line(".") - let startcol = col(".") - " Use default behavior if called with a count. - if v:count - exe "normal! " . v:count . "%" - return s:CleanUp(restore_options, a:mode, startline, startcol) - end - - " First step: if not already done, set the script variables - " s:do_BR flag for whether there are backrefs - " s:pat parsed version of b:match_words - " s:all regexp based on s:pat and the default groups - " - if !exists("b:match_words") || b:match_words == "" - let match_words = "" - " Allow b:match_words = "GetVimMatchWords()" . - elseif b:match_words =~ ":" - let match_words = b:match_words - else - execute "let match_words =" b:match_words - endif -" Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion! - if (match_words != s:last_words) || (&mps != s:last_mps) || - \ exists("b:match_debug") - let s:last_words = match_words - let s:last_mps = &mps - " The next several lines were here before - " BF started messing with this script. - " quote the special chars in 'matchpairs', replace [,:] with \| and then - " append the builtin pairs (/*, */, #if, #ifdef, #else, #elif, #endif) - " let default = substitute(escape(&mps, '[$^.*~\\/?]'), '[,:]\+', - " \ '\\|', 'g').'\|\/\*\|\*\/\|#if\>\|#ifdef\>\|#else\>\|#elif\>\|#endif\>' - let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") . - \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>' - " s:all = pattern with all the keywords - let match_words = match_words . (strlen(match_words) ? "," : "") . default - if match_words !~ s:notslash . '\\\d' - let s:do_BR = 0 - let s:pat = match_words - else - let s:do_BR = 1 - let s:pat = s:ParseWords(match_words) - endif - let s:all = substitute(s:pat, s:notslash . '\zs[,:]\+', '\\|', 'g') - let s:all = '\%(' . s:all . '\)' - " let s:all = '\%(' . substitute(s:all, '\\\ze[,:]', '', 'g') . '\)' - if exists("b:match_debug") - let b:match_pat = s:pat - endif - endif - - " Second step: set the following local variables: - " matchline = line on which the cursor started - " curcol = number of characters before match - " prefix = regexp for start of line to start of match - " suffix = regexp for end of match to end of line - " Require match to end on or after the cursor and prefer it to - " start on or before the cursor. - let matchline = getline(startline) - if a:word != '' - " word given - if a:word !~ s:all - echohl WarningMsg|echo 'Missing rule for word:"'.a:word.'"'|echohl NONE - return s:CleanUp(restore_options, a:mode, startline, startcol) - endif - let matchline = a:word - let curcol = 0 - let prefix = '^\%(' - let suffix = '\)$' - " Now the case when "word" is not given - else " Find the match that ends on or after the cursor and set curcol. - let regexp = s:Wholematch(matchline, s:all, startcol-1) - let curcol = match(matchline, regexp) - " If there is no match, give up. - if curcol == -1 - return s:CleanUp(restore_options, a:mode, startline, startcol) - endif - let endcol = matchend(matchline, regexp) - let suf = strlen(matchline) - endcol - let prefix = (curcol ? '^.*\%' . (curcol + 1) . 'c\%(' : '^\%(') - let suffix = (suf ? '\)\%' . (endcol + 1) . 'c.*$' : '\)$') - endif - if exists("b:match_debug") - let b:match_match = matchstr(matchline, regexp) - let b:match_col = curcol+1 - endif - - " Third step: Find the group and single word that match, and the original - " (backref) versions of these. Then, resolve the backrefs. - " Set the following local variable: - " group = colon-separated list of patterns, one of which matches - " = ini:mid:fin or ini:fin - " - " Reconstruct the version with unresolved backrefs. - let patBR = substitute(match_words.',', - \ s:notslash.'\zs[,:]*,[,:]*', ',', 'g') - let patBR = substitute(patBR, s:notslash.'\zs:\{2,}', ':', 'g') - " Now, set group and groupBR to the matching group: 'if:endif' or - " 'while:endwhile' or whatever. A bit of a kluge: s:Choose() returns - " group . "," . groupBR, and we pick it apart. - let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR) - let i = matchend(group, s:notslash . ",") - let groupBR = strpart(group, i) - let group = strpart(group, 0, i-1) - " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix - if s:do_BR " Do the hard part: resolve those backrefs! - let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline) - endif - if exists("b:match_debug") - let b:match_wholeBR = groupBR - let i = matchend(groupBR, s:notslash . ":") - let b:match_iniBR = strpart(groupBR, 0, i-1) - endif - - " Fourth step: Set the arguments for searchpair(). - let i = matchend(group, s:notslash . ":") - let j = matchend(group, '.*' . s:notslash . ":") - let ini = strpart(group, 0, i-1) - let mid = substitute(strpart(group, i,j-i-1), s:notslash.'\zs:', '\\|', 'g') - let fin = strpart(group, j) - "Un-escape the remaining , and : characters. - let ini = substitute(ini, s:notslash . '\zs\\\(:\|,\)', '\1', 'g') - let mid = substitute(mid, s:notslash . '\zs\\\(:\|,\)', '\1', 'g') - let fin = substitute(fin, s:notslash . '\zs\\\(:\|,\)', '\1', 'g') - " searchpair() requires that these patterns avoid \(\) groups. - let ini = substitute(ini, s:notslash . '\zs\\(', '\\%(', 'g') - let mid = substitute(mid, s:notslash . '\zs\\(', '\\%(', 'g') - let fin = substitute(fin, s:notslash . '\zs\\(', '\\%(', 'g') - " Set mid. This is optimized for readability, not micro-efficiency! - if a:forward && matchline =~ prefix . fin . suffix - \ || !a:forward && matchline =~ prefix . ini . suffix - let mid = "" - endif - " Set flag. This is optimized for readability, not micro-efficiency! - if a:forward && matchline =~ prefix . fin . suffix - \ || !a:forward && matchline !~ prefix . ini . suffix - let flag = "bW" - else - let flag = "W" - endif - " Set skip. - if exists("b:match_skip") - let skip = b:match_skip - elseif exists("b:match_comment") " backwards compatibility and testing! - let skip = "r:" . b:match_comment - else - let skip = 's:comment\|string' - endif - let skip = s:ParseSkip(skip) - if exists("b:match_debug") - let b:match_ini = ini - let b:match_tail = (strlen(mid) ? mid.'\|' : '') . fin - endif - - " Fifth step: actually start moving the cursor and call searchpair(). - " Later, :execute restore_cursor to get to the original screen. - let restore_cursor = virtcol(".") . "|" - normal! g0 - let restore_cursor = line(".") . "G" . virtcol(".") . "|zs" . restore_cursor - normal! H - let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor - execute restore_cursor - call cursor(0, curcol + 1) - " normal! 0 - " if curcol - " execute "normal!" . curcol . "l" - " endif - if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on")) - let skip = "0" - else - execute "if " . skip . "| let skip = '0' | endif" - endif - let sp_return = searchpair(ini, mid, fin, flag, skip) - let final_position = "call cursor(" . line(".") . "," . col(".") . ")" - " Restore cursor position and original screen. - execute restore_cursor - normal! m' - if sp_return > 0 - execute final_position - endif - return s:CleanUp(restore_options, a:mode, startline, startcol, mid.'\|'.fin) -endfun - -" Restore options and do some special handling for Operator-pending mode. -" The optional argument is the tail of the matching group. -fun! s:CleanUp(options, mode, startline, startcol, ...) - execute "set" a:options - " Open folds, if appropriate. - if a:mode != "o" - if &foldopen =~ "percent" - normal! zv - endif - " In Operator-pending mode, we want to include the whole match - " (for example, d%). - " This is only a problem if we end up moving in the forward direction. - elseif (a:startline < line(".")) || - \ (a:startline == line(".") && a:startcol < col(".")) - if a:0 - " Check whether the match is a single character. If not, move to the - " end of the match. - let matchline = getline(".") - let currcol = col(".") - let regexp = s:Wholematch(matchline, a:1, currcol-1) - let endcol = matchend(matchline, regexp) - if endcol > currcol " This is NOT off by one! - execute "normal!" . (endcol - currcol) . "l" - endif - endif " a:0 - endif " a:mode != "o" && etc. - return 0 -endfun - -" Example (simplified HTML patterns): if -" a:groupBR = '<\(\k\+\)>:</\1>' -" a:prefix = '^.\{3}\(' -" a:group = '<\(\k\+\)>:</\(\k\+\)>' -" a:suffix = '\).\{2}$' -" a:matchline = "123<tag>12" or "123</tag>12" -" then extract "tag" from a:matchline and return "<tag>:</tag>" . -fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline) - if a:matchline !~ a:prefix . - \ substitute(a:group, s:notslash . '\zs:', '\\|', 'g') . a:suffix - return a:group - endif - let i = matchend(a:groupBR, s:notslash . ':') - let ini = strpart(a:groupBR, 0, i-1) - let tailBR = strpart(a:groupBR, i) - let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix, - \ a:groupBR) - let i = matchend(word, s:notslash . ":") - let wordBR = strpart(word, i) - let word = strpart(word, 0, i-1) - " Now, a:matchline =~ a:prefix . word . a:suffix - if wordBR != ini - let table = s:Resolve(ini, wordBR, "table") - else - " let table = "----------" - let table = "" - let d = 0 - while d < 10 - if tailBR =~ s:notslash . '\\' . d - " let table[d] = d - let table = table . d - else - let table = table . "-" - endif - let d = d + 1 - endwhile - endif - let d = 9 - while d - if table[d] != "-" - let backref = substitute(a:matchline, a:prefix.word.a:suffix, - \ '\'.table[d], "") - " Are there any other characters that should be escaped? - let backref = escape(backref, '*,:') - execute s:Ref(ini, d, "start", "len") - let ini = strpart(ini, 0, start) . backref . strpart(ini, start+len) - let tailBR = substitute(tailBR, s:notslash . '\zs\\' . d, - \ escape(backref, '\\&'), 'g') - endif - let d = d-1 - endwhile - if exists("b:match_debug") - if s:do_BR - let b:match_table = table - let b:match_word = word - else - let b:match_table = "" - let b:match_word = "" - endif - endif - return ini . ":" . tailBR -endfun - -" Input a comma-separated list of groups with backrefs, such as -" a:groups = '\(foo\):end\1,\(bar\):end\1' -" and return a comma-separated list of groups with backrefs replaced: -" return '\(foo\):end\(foo\),\(bar\):end\(bar\)' -fun! s:ParseWords(groups) - let groups = substitute(a:groups.",", s:notslash.'\zs[,:]*,[,:]*', ',', 'g') - let groups = substitute(groups, s:notslash . '\zs:\{2,}', ':', 'g') - let parsed = "" - while groups =~ '[^,:]' - let i = matchend(groups, s:notslash . ':') - let j = matchend(groups, s:notslash . ',') - let ini = strpart(groups, 0, i-1) - let tail = strpart(groups, i, j-i-1) . ":" - let groups = strpart(groups, j) - let parsed = parsed . ini - let i = matchend(tail, s:notslash . ':') - while i != -1 - " In 'if:else:endif', ini='if' and word='else' and then word='endif'. - let word = strpart(tail, 0, i-1) - let tail = strpart(tail, i) - let i = matchend(tail, s:notslash . ':') - let parsed = parsed . ":" . s:Resolve(ini, word, "word") - endwhile " Now, tail has been used up. - let parsed = parsed . "," - endwhile " groups =~ '[^,:]' - let parsed = substitute(parsed, ',$', '', '') - return parsed -endfun - -" TODO I think this can be simplified and/or made more efficient. -" TODO What should I do if a:start is out of range? -" Return a regexp that matches all of a:string, such that -" matchstr(a:string, regexp) represents the match for a:pat that starts -" as close to a:start as possible, before being preferred to after, and -" ends after a:start . -" Usage: -" let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1) -" let i = match(getline("."), regexp) -" let j = matchend(getline("."), regexp) -" let match = matchstr(getline("."), regexp) -fun! s:Wholematch(string, pat, start) - let group = '\%(' . a:pat . '\)' - let prefix = (a:start ? '\(^.*\%<' . (a:start + 2) . 'c\)\zs' : '^') - let len = strlen(a:string) - let suffix = (a:start+1 < len ? '\(\%>'.(a:start+1).'c.*$\)\@=' : '$') - if a:string !~ prefix . group . suffix - let prefix = '' - endif - return prefix . group . suffix -endfun - -" No extra arguments: s:Ref(string, d) will -" find the d'th occurrence of '\(' and return it, along with everything up -" to and including the matching '\)'. -" One argument: s:Ref(string, d, "start") returns the index of the start -" of the d'th '\(' and any other argument returns the length of the group. -" Two arguments: s:Ref(string, d, "foo", "bar") returns a string to be -" executed, having the effect of -" :let foo = s:Ref(string, d, "start") -" :let bar = s:Ref(string, d, "len") -fun! s:Ref(string, d, ...) - let len = strlen(a:string) - if a:d == 0 - let start = 0 - else - let cnt = a:d - let match = a:string - while cnt - let cnt = cnt - 1 - let index = matchend(match, s:notslash . '\\(') - if index == -1 - return "" - endif - let match = strpart(match, index) - endwhile - let start = len - strlen(match) - if a:0 == 1 && a:1 == "start" - return start - 2 - endif - let cnt = 1 - while cnt - let index = matchend(match, s:notslash . '\\(\|\\)') - 1 - if index == -2 - return "" - endif - " Increment if an open, decrement if a ')': - let cnt = cnt + (match[index]=="(" ? 1 : -1) " ')' - " let cnt = stridx('0(', match[index]) + cnt - let match = strpart(match, index+1) - endwhile - let start = start - 2 - let len = len - start - strlen(match) - endif - if a:0 == 1 - return len - elseif a:0 == 2 - return "let " . a:1 . "=" . start . "| let " . a:2 . "=" . len - else - return strpart(a:string, start, len) - endif -endfun - -" Count the number of disjoint copies of pattern in string. -" If the pattern is a literal string and contains no '0' or '1' characters -" then s:Count(string, pattern, '0', '1') should be faster than -" s:Count(string, pattern). -fun! s:Count(string, pattern, ...) - let pat = escape(a:pattern, '\\') - if a:0 > 1 - let foo = substitute(a:string, '[^'.a:pattern.']', "a:1", "g") - let foo = substitute(a:string, pat, a:2, "g") - let foo = substitute(foo, '[^' . a:2 . ']', "", "g") - return strlen(foo) - endif - let result = 0 - let foo = a:string - let index = matchend(foo, pat) - while index != -1 - let result = result + 1 - let foo = strpart(foo, index) - let index = matchend(foo, pat) - endwhile - return result -endfun - -" s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where -" word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'. That is, the first -" '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this -" indicates that all other instances of '\1' in target are to be replaced -" by '\3'. The hard part is dealing with nesting... -" Note that ":" is an illegal character for source and target, -" unless it is preceded by "\". -fun! s:Resolve(source, target, output) - let word = a:target - let i = matchend(word, s:notslash . '\\\d') - 1 - let table = "----------" - while i != -2 " There are back references to be replaced. - let d = word[i] - let backref = s:Ref(a:source, d) - " The idea is to replace '\d' with backref. Before we do this, - " replace any \(\) groups in backref with :1, :2, ... if they - " correspond to the first, second, ... group already inserted - " into backref. Later, replace :1 with \1 and so on. The group - " number w+b within backref corresponds to the group number - " s within a:source. - " w = number of '\(' in word before the current one - let w = s:Count( - \ substitute(strpart(word, 0, i-1), '\\\\', '', 'g'), '\(', '1') - let b = 1 " number of the current '\(' in backref - let s = d " number of the current '\(' in a:source - while b <= s:Count(substitute(backref, '\\\\', '', 'g'), '\(', '1') - \ && s < 10 - if table[s] == "-" - if w + b < 10 - " let table[s] = w + b - let table = strpart(table, 0, s) . (w+b) . strpart(table, s+1) - endif - let b = b + 1 - let s = s + 1 - else - execute s:Ref(backref, b, "start", "len") - let ref = strpart(backref, start, len) - let backref = strpart(backref, 0, start) . ":". table[s] - \ . strpart(backref, start+len) - let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1') - endif - endwhile - let word = strpart(word, 0, i-1) . backref . strpart(word, i+1) - let i = matchend(word, s:notslash . '\\\d') - 1 - endwhile - let word = substitute(word, s:notslash . '\zs:', '\\', 'g') - if a:output == "table" - return table - elseif a:output == "word" - return word - else - return table . word - endif -endfun - -" Assume a:comma = ",". Then the format for a:patterns and a:1 is -" a:patterns = "<pat1>,<pat2>,..." -" a:1 = "<alt1>,<alt2>,..." -" If <patn> is the first pattern that matches a:string then return <patn> -" if no optional arguments are given; return <patn>,<altn> if a:1 is given. -fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...) - let tail = (a:patterns =~ a:comma."$" ? a:patterns : a:patterns . a:comma) - let i = matchend(tail, s:notslash . a:comma) - if a:0 - let alttail = (a:1 =~ a:comma."$" ? a:1 : a:1 . a:comma) - let j = matchend(alttail, s:notslash . a:comma) - endif - let current = strpart(tail, 0, i-1) - if a:branch == "" - let currpat = current - else - let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g') - endif - while a:string !~ a:prefix . currpat . a:suffix - let tail = strpart(tail, i) - let i = matchend(tail, s:notslash . a:comma) - if i == -1 - return -1 - endif - let current = strpart(tail, 0, i-1) - if a:branch == "" - let currpat = current - else - let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g') - endif - if a:0 - let alttail = strpart(alttail, j) - let j = matchend(alttail, s:notslash . a:comma) - endif - endwhile - if a:0 - let current = current . a:comma . strpart(alttail, 0, j-1) - endif - return current -endfun - -" Call this function to turn on debugging information. Every time the main -" script is run, buffer variables will be saved. These can be used directly -" or viewed using the menu items below. -if !exists(":MatchDebug") - command! -nargs=0 MatchDebug call s:Match_debug() -endif - -fun! s:Match_debug() - let b:match_debug = 1 " Save debugging information. - " pat = all of b:match_words with backrefs parsed - amenu &Matchit.&pat :echo b:match_pat<CR> - " match = bit of text that is recognized as a match - amenu &Matchit.&match :echo b:match_match<CR> - " curcol = cursor column of the start of the matching text - amenu &Matchit.&curcol :echo b:match_col<CR> - " wholeBR = matching group, original version - amenu &Matchit.wh&oleBR :echo b:match_wholeBR<CR> - " iniBR = 'if' piece, original version - amenu &Matchit.ini&BR :echo b:match_iniBR<CR> - " ini = 'if' piece, with all backrefs resolved from match - amenu &Matchit.&ini :echo b:match_ini<CR> - " tail = 'else\|endif' piece, with all backrefs resolved from match - amenu &Matchit.&tail :echo b:match_tail<CR> - " fin = 'endif' piece, with all backrefs resolved from match - amenu &Matchit.&word :echo b:match_word<CR> - " '\'.d in ini refers to the same thing as '\'.table[d] in word. - amenu &Matchit.t&able :echo '0:' . b:match_table . ':9'<CR> -endfun - -" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW" -" or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W". -" Return a "mark" for the original position, so that -" let m = MultiMatch("bW", "n") ... execute m -" will return to the original position. If there is a problem, do not -" move the cursor and return "", unless a count is given, in which case -" go up or down as many levels as possible and again return "". -" TODO This relies on the same patterns as % matching. It might be a good -" idea to give it its own matching patterns. -fun! s:MultiMatch(spflag, mode) - if !exists("b:match_words") || b:match_words == "" - return "" - end - let restore_options = (&ic ? "" : "no") . "ignorecase" - if exists("b:match_ignorecase") - let &ignorecase = b:match_ignorecase - endif - let startline = line(".") - let startcol = col(".") - - " First step: if not already done, set the script variables - " s:do_BR flag for whether there are backrefs - " s:pat parsed version of b:match_words - " s:all regexp based on s:pat and the default groups - " This part is copied and slightly modified from s:Match_wrapper(). - let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") . - \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>' - " Allow b:match_words = "GetVimMatchWords()" . - if b:match_words =~ ":" - let match_words = b:match_words - else - execute "let match_words =" b:match_words - endif - if (match_words != s:last_words) || (&mps != s:last_mps) || - \ exists("b:match_debug") - let s:last_words = match_words - let s:last_mps = &mps - if match_words !~ s:notslash . '\\\d' - let s:do_BR = 0 - let s:pat = match_words - else - let s:do_BR = 1 - let s:pat = s:ParseWords(match_words) - endif - let s:all = '\%(' . substitute(s:pat . (strlen(s:pat)?",":"") . default, - \ '[,:]\+','\\|','g') . '\)' - if exists("b:match_debug") - let b:match_pat = s:pat - endif - endif - - " Second step: figure out the patterns for searchpair() - " and save the screen, cursor position, and 'ignorecase'. - " - TODO: A lot of this is copied from s:Match_wrapper(). - " - maybe even more functionality should be split off - " - into separate functions! - let cdefault = (s:pat =~ '[^,]$' ? "," : "") . default - let open = substitute(s:pat . cdefault, - \ s:notslash . '\zs:.\{-}' . s:notslash . ',', '\\),\\(', 'g') - let open = '\(' . substitute(open, s:notslash . '\zs:.*$', '\\)', '') - let close = substitute(s:pat . cdefault, - \ s:notslash . '\zs,.\{-}' . s:notslash . ':', '\\),\\(', 'g') - let close = substitute(close, '^.\{-}' . s:notslash . ':', '\\(', '') . '\)' - if exists("b:match_skip") - let skip = b:match_skip - elseif exists("b:match_comment") " backwards compatibility and testing! - let skip = "r:" . b:match_comment - else - let skip = 's:comment\|string' - endif - let skip = s:ParseSkip(skip) - " let restore_cursor = line(".") . "G" . virtcol(".") . "|" - " normal! H - " let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor - let restore_cursor = virtcol(".") . "|" - normal! g0 - let restore_cursor = line(".") . "G" . virtcol(".") . "|zs" . restore_cursor - normal! H - let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor - execute restore_cursor - - " Third step: call searchpair(). - " Replace '\('--but not '\\('--with '\%(' and ',' with '\|'. - let openpat = substitute(open, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g') - let openpat = substitute(openpat, ',', '\\|', 'g') - let closepat = substitute(close, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g') - let closepat = substitute(closepat, ',', '\\|', 'g') - if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on")) - let skip = '0' - else - execute "if " . skip . "| let skip = '0' | endif" - endif - mark ' - let level = v:count1 - while level - if searchpair(openpat, '', closepat, a:spflag, skip) < 1 - call s:CleanUp(restore_options, a:mode, startline, startcol) - return "" - endif - let level = level - 1 - endwhile - - " Restore options and return a string to restore the original position. - call s:CleanUp(restore_options, a:mode, startline, startcol) - return restore_cursor -endfun - -" Search backwards for "if" or "while" or "<tag>" or ... -" and return "endif" or "endwhile" or "</tag>" or ... . -" For now, this uses b:match_words and the same script variables -" as s:Match_wrapper() . Later, it may get its own patterns, -" either from a buffer variable or passed as arguments. -" fun! s:Autocomplete() -" echo "autocomplete not yet implemented :-(" -" if !exists("b:match_words") || b:match_words == "" -" return "" -" end -" let startpos = s:MultiMatch("bW") -" -" if startpos == "" -" return "" -" endif -" " - TODO: figure out whether 'if' or '<tag>' matched, and construct -" " - the appropriate closing. -" let matchline = getline(".") -" let curcol = col(".") - 1 -" " - TODO: Change the s:all argument if there is a new set of match pats. -" let regexp = s:Wholematch(matchline, s:all, curcol) -" let suf = strlen(matchline) - matchend(matchline, regexp) -" let prefix = (curcol ? '^.\{' . curcol . '}\%(' : '^\%(') -" let suffix = (suf ? '\).\{' . suf . '}$' : '\)$') -" " Reconstruct the version with unresolved backrefs. -" let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g') -" let patBR = substitute(patBR, ':\{2,}', ':', "g") -" " Now, set group and groupBR to the matching group: 'if:endif' or -" " 'while:endwhile' or whatever. -" let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR) -" let i = matchend(group, s:notslash . ",") -" let groupBR = strpart(group, i) -" let group = strpart(group, 0, i-1) -" " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix -" if s:do_BR -" let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline) -" endif -" " let g:group = group -" -" " - TODO: Construct the closing from group. -" let fake = "end" . expand("<cword>") -" execute startpos -" return fake -" endfun - -" Close all open structures. "Get the heck out of here!" -" fun! s:Gthhoh() -" let close = s:Autocomplete() -" while strlen(close) -" put=close -" let close = s:Autocomplete() -" endwhile -" endfun - -" Parse special strings as typical skip arguments for searchpair(): -" s:foo becomes (current syntax item) =~ foo -" S:foo becomes (current syntax item) !~ foo -" r:foo becomes (line before cursor) =~ foo -" R:foo becomes (line before cursor) !~ foo -fun! s:ParseSkip(str) - let skip = a:str - if skip[1] == ":" - if skip[0] == "s" - let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" . - \ strpart(skip,2) . "'" - elseif skip[0] == "S" - let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" . - \ strpart(skip,2) . "'" - elseif skip[0] == "r" - let skip = "strpart(getline('.'),0,col('.'))=~'" . strpart(skip,2). "'" - elseif skip[0] == "R" - let skip = "strpart(getline('.'),0,col('.'))!~'" . strpart(skip,2). "'" - endif - endif - return skip -endfun - -let &cpo = s:save_cpo - -" vim:sts=2:sw=2: diff --git a/files/.vim/plugin/project.vim b/files/.vim/plugin/project.vim deleted file mode 100644 index 47bd379..0000000 --- a/files/.vim/plugin/project.vim +++ /dev/null @@ -1,1293 +0,0 @@ -"============================================================================= -" File: project.vim -" Author: Aric Blumer (Aric.Blumer at aricvim@charter.net) -" Last Change: Fri 13 Oct 2006 09:47:08 AM EDT -" Version: 1.4.1 -"============================================================================= -" See documentation in accompanying help file -" You may use this code in whatever way you see fit. - -if exists('loaded_project') || &cp - finish -endif -let loaded_project=1 - -function! s:Project(filename) " <<< - " Initialization <<< - if exists("g:proj_running") - if strlen(a:filename) != 0 - call confirm('Project already loaded; ignoring filename "'.a:filename."\".\n".'See ":help project-invoking" for information about changing project files.', "&OK", 1) - endif - let filename=bufname(g:proj_running) - else - if strlen(a:filename) == 0 - let filename ='~/.vimprojects' " Default project filename - else - let filename = a:filename - endif - endif - if !exists('g:proj_window_width') - let g:proj_window_width=24 " Default project window width - endif - if !exists('g:proj_window_increment') - let g:proj_window_increment=100 " Project Window width increment - endif - if !exists('g:proj_flags') - if has("win32") || has("mac") - let g:proj_flags='imst' " Project default flags for windows/mac - else - let g:proj_flags='imstb' " Project default flags for everything else - endif - endif - if !exists("g:proj_running") || (bufwinnr(g:proj_running) == -1) " Open the Project Window - exec 'silent vertical new '.filename - if match(g:proj_flags, '\CF') == -1 " We're floating - silent! wincmd H - exec 'vertical resize '.g:proj_window_width - endif - setlocal nomodeline - else - silent! 99wincmd h - if bufwinnr(g:proj_running) == -1 - vertical split - let v:errmsg="nothing" - silent! bnext - if 'nothing' != v:errmsg - enew - endif - endif - return - endif - " Process the flags - let b:proj_cd_cmd='cd' - if match(g:proj_flags, '\Cl') != -1 - let b:proj_cd_cmd = 'lcd' - endif - - let b:proj_locate_command='silent! wincmd H' - let b:proj_resize_command='exec ''vertical resize ''.g:proj_window_width' - if match(g:proj_flags, '\CF') != -1 " Set the resize commands to nothing - let b:proj_locate_command='' - let b:proj_resize_command='' - endif - - let g:proj_last_buffer = -1 - ">>> - " ProjFoldText() <<< - " The foldtext function for displaying just the description. - function! ProjFoldText() - let line=substitute(getline(v:foldstart),'^[ \t#]*\([^=]*\).*', '\1', '') - let line=strpart(' ', 0, (v:foldlevel - 1)).substitute(line,'\s*{\+\s*', '', '') - return line - endfunction ">>> - " s:DoSetup() <<< - " Ensure everything is set up - function! s:DoSetup() - setlocal foldenable foldmethod=marker foldmarker={,} commentstring=%s foldcolumn=0 nonumber noswapfile shiftwidth=1 - setlocal foldtext=ProjFoldText() nobuflisted nowrap - setlocal winwidth=1 - if match(g:proj_flags, '\Cn') != -1 - setlocal number - endif - endfunction ">>> - call s:DoSetup() - " Syntax Stuff <<< - if match(g:proj_flags, '\Cs')!=-1 && has('syntax') && exists('g:syntax_on') && !has('syntax_items') - syntax match projectDescriptionDir '^\s*.\{-}=\s*\(\\ \|\f\|:\|"\)\+' contains=projectDescription,projectWhiteError - syntax match projectDescription '\<.\{-}='he=e-1,me=e-1 contained nextgroup=projectDirectory contains=projectWhiteError - syntax match projectDescription '{\|}' - syntax match projectDirectory '=\(\\ \|\f\|:\)\+' contained - syntax match projectDirectory '=".\{-}"' contained - syntax match projectScriptinout '\<in\s*=\s*\(\\ \|\f\|:\|"\)\+' contains=projectDescription,projectWhiteError - syntax match projectScriptinout '\<out\s*=\s*\(\\ \|\f\|:\|"\)\+' contains=projectDescription,projectWhiteError - syntax match projectComment '#.*' - syntax match projectCD '\<CD\s*=\s*\(\\ \|\f\|:\|"\)\+' contains=projectDescription,projectWhiteError - syntax match projectFilterEntry '\<filter\s*=.*"' contains=projectWhiteError,projectFilterError,projectFilter,projectFilterRegexp - syntax match projectFilter '\<filter='he=e-1,me=e-1 contained nextgroup=projectFilterRegexp,projectFilterError,projectWhiteError - syntax match projectFlagsEntry '\<flags\s*=\( \|[^ ]*\)' contains=projectFlags,projectWhiteError - syntax match projectFlags '\<flags' contained nextgroup=projectFlagsValues,projectWhiteError - syntax match projectFlagsValues '=[^ ]* 'hs=s+1,me=e-1 contained contains=projectFlagsError - syntax match projectFlagsError '[^rtTsSwl= ]\+' contained - syntax match projectWhiteError '=\s\+'hs=s+1 contained - syntax match projectWhiteError '\s\+='he=e-1 contained - syntax match projectFilterError '=[^"]'hs=s+1 contained - syntax match projectFilterRegexp '=".*"'hs=s+1 contained - syntax match projectFoldText '^[^=]\+{' - - highlight def link projectDescription Identifier - highlight def link projectScriptinout Identifier - highlight def link projectFoldText Identifier - highlight def link projectComment Comment - highlight def link projectFilter Identifier - highlight def link projectFlags Identifier - highlight def link projectDirectory Constant - highlight def link projectFilterRegexp String - highlight def link projectFlagsValues String - highlight def link projectWhiteError Error - highlight def link projectFlagsError Error - highlight def link projectFilterError Error - endif ">>> - " s:SortR(start, end) <<< - " Sort lines. SortR() is called recursively. - " from ":help eval-examples" by Robert Webb, slightly modified - function! s:SortR(start, end) - if (a:start >= a:end) - return - endif - let partition = a:start - 1 - let middle = partition - let partStr = getline((a:start + a:end) / 2) - let i = a:start - while (i <= a:end) - let str = getline(i) - if str < partStr - let result = -1 - elseif str > partStr - let result = 1 - else - let result = 0 - endif - if (result <= 0) - let partition = partition + 1 - if (result == 0) - let middle = partition - endif - if (i != partition) - let str2 = getline(partition) - call setline(i, str2) - call setline(partition, str) - endif - endif - let i = i + 1 - endwhile - if (middle != partition) - let str = getline(middle) - let str2 = getline(partition) - call setline(middle, str2) - call setline(partition, str) - endif - call s:SortR(a:start, partition - 1) - call s:SortR(partition + 1, a:end) - endfunc ">>> - " s:IsAbsolutePath(path) <<< - " Returns true if filename has an absolute path. - function! s:IsAbsolutePath(path) - if a:path =~ '^ftp:' || a:path =~ '^rcp:' || a:path =~ '^scp:' || a:path =~ '^http:' - return 2 - endif - if a:path =~ '\$' - let path=expand(a:path) " Expand any environment variables that might be in the path - else - let path=a:path - endif - if path[0] == '/' || path[0] == '~' || path[0] == '\\' || path[1] == ':' - return 1 - endif - return 0 - endfunction " >>> - " s:DoSetupAndSplit() <<< - " Call DoSetup to ensure the settings are correct. Split to the next - " file. - function! s:DoSetupAndSplit() - call s:DoSetup() " Ensure that all the settings are right - let n = winnr() " Determine if there is a CTRL_W-p window - silent! wincmd p - if n == winnr() - silent! wincmd l - endif - if n == winnr() - " If n == winnr(), then there is no CTRL_W-p window - " So we have to create a new one - if bufnr('%') == g:proj_running - exec 'silent vertical new' - else - exec 'silent vertical split | silent! bnext' - endif - wincmd p " Go back to the Project Window and ensure it is the right width - exec b:proj_locate_command - exec b:proj_resize_command - wincmd p - endif - endfunction ">>> - " s:DoSetupAndSplit_au() <<< - " Same as above but ensure that the Project window is the current - " window. Only called from an autocommand - function! s:DoSetupAndSplit_au() - if winbufnr(0) != g:proj_running - return - endif - call s:DoSetup() " Ensure that all the settings are right - if winbufnr(2) == -1 " We're the only window right now. - exec 'silent vertical split | bnext' - if bufnr('%') == g:proj_running - enew - endif - if bufnr('%') == g:proj_last_buffer | bnext | bprev | bnext | endif - wincmd p " Go back to the Project Window and ensure it is the right width - exec b:proj_locate_command - exec b:proj_resize_command - elseif(winnr() != 1) - exec b:proj_locate_command - exec b:proj_resize_command - endif - endfunction - function! s:RecordPrevBuffer_au() - let g:proj_last_buffer = bufnr('%') - endfunction ">>> - " s:RecursivelyConstructDirectives(lineno) <<< - " Construct the inherited directives - function! s:RecursivelyConstructDirectives(lineno) - let lineno=s:FindFoldTop(a:lineno) - let foldlineno = lineno - let foldlev=foldlevel(lineno) - let parent_infoline = '' - if foldlev > 1 - while foldlevel(lineno) >= foldlev " Go to parent fold - if lineno < 1 - echoerr 'Some kind of fold error. Check your syntax.' - return - endif - let lineno = lineno - 1 - endwhile - let parent_infoline = s:RecursivelyConstructDirectives(lineno) - endif - let parent_home = s:GetHome(parent_infoline, '') - let parent_c_d = s:GetCd(parent_infoline, parent_home) - let parent_scriptin = s:GetScriptin(parent_infoline, parent_home) - let parent_scriptout = s:GetScriptout(parent_infoline, parent_home) - let parent_filter = s:GetFilter(parent_infoline, '*') - let infoline = getline(foldlineno) - " Extract the home directory of this fold - let home=s:GetHome(infoline, parent_home) - if home != '' - if (foldlevel(foldlineno) == 1) && !s:IsAbsolutePath(home) - call confirm('Outermost Project Fold must have absolute path! Or perhaps the path does not exist.', "&OK", 1) - let home = '~' " Some 'reasonable' value - endif - endif - " Extract any CD information - let c_d = s:GetCd(infoline, home) - if c_d != '' - if (foldlevel(foldlineno) == 1) && !s:IsAbsolutePath(c_d) - call confirm('Outermost Project Fold must have absolute CD path! Or perhaps the path does not exist.', "&OK", 1) - let c_d = '.' " Some 'reasonable' value - endif - else - let c_d=parent_c_d - endif - " Extract scriptin - let scriptin = s:GetScriptin(infoline, home) - if scriptin == '' - let scriptin = parent_scriptin - endif - " Extract scriptout - let scriptout = s:GetScriptout(infoline, home) - if scriptout == '' - let scriptout = parent_scriptout - endif - " Extract filter - let filter = s:GetFilter(infoline, parent_filter) - if filter == '' | let filter = parent_filter | endif - return s:ConstructInfo(home, c_d, scriptin, scriptout, '', filter) - endfunction ">>> - " s:ConstructInfo(home, c_d, scriptin, scriptout, flags, filter) <<< - function! s:ConstructInfo(home, c_d, scriptin, scriptout, flags, filter) - let retval='Directory='.a:home - if a:c_d[0] != '' - let retval=retval.' CD='.a:c_d - endif - if a:scriptin[0] != '' - let retval=retval.' in='.a:scriptin - endif - if a:scriptout[0] != '' - let retval=retval.' out='.a:scriptout - endif - if a:filter[0] != '' - let retval=retval.' filter="'.a:filter.'"' - endif - return retval - endfunction ">>> - " s:OpenEntry(line, precmd, editcmd) <<< - " Get the filename under the cursor, and open a window with it. - function! s:OpenEntry(line, precmd, editcmd, dir) - silent exec a:precmd - if (a:editcmd[0] != '') - if a:dir - let fname='.' - else - if (foldlevel(a:line) == 0) && (a:editcmd[0] != '') - return 0 " If we're outside a fold, do nothing - endif - let fname=substitute(getline(a:line), '\s*#.*', '', '') " Get rid of comments and whitespace before comment - let fname=substitute(fname, '^\s*\(.*\)', '\1', '') " Get rid of leading whitespace - if strlen(fname) == 0 - return 0 " The line is blank. Do nothing. - endif - endif - else - let fname='.' - endif - let infoline = s:RecursivelyConstructDirectives(a:line) - let retval=s:OpenEntry2(a:line, infoline, fname, a:editcmd) - call s:DisplayInfo() - return retval - endfunction - ">>> - " s:OpenEntry2(line, infoline, precmd, editcmd) <<< - " Get the filename under the cursor, and open a window with it. - function! s:OpenEntry2(line, infoline, fname, editcmd) - let fname=escape(a:fname, ' %#') " Thanks to Thomas Link for cluing me in on % and # - let home=s:GetHome(a:infoline, '').'/' - if home=='/' - echoerr 'Project structure error. Check your syntax.' - return - endif - "Save the cd command - let cd_cmd = b:proj_cd_cmd - if a:editcmd[0] != '' " If editcmd is '', then just set up the environment in the Project Window - call s:DoSetupAndSplit() - " If it is an absolute path, don't prepend home - if !s:IsAbsolutePath(fname) - let fname=home.fname - endif - if s:IsAbsolutePath(fname) == 2 - exec a:editcmd.' '.fname - else - silent exec 'silent '.a:editcmd.' '.fname - endif - else " only happens in the Project File - exec 'au! BufEnter,BufLeave '.expand('%:p') - endif - " Extract any CD information - let c_d = s:GetCd(a:infoline, home) - if c_d != '' && (s:IsAbsolutePath(home) != 2) - if match(g:proj_flags, '\CL') != -1 - call s:SetupAutoCommand(c_d) - endif - if !isdirectory(glob(c_d)) - call confirm("From this fold's entry,\nCD=".'"'.c_d.'" is not a valid directory.', "&OK", 1) - else - silent exec cd_cmd.' '.c_d - endif - endif - " Extract any scriptin information - let scriptin = s:GetScriptin(a:infoline, home) - if scriptin != '' - if !filereadable(glob(scriptin)) - call confirm('"'.scriptin.'" not found. Ignoring.', "&OK", 1) - else - call s:SetupScriptAutoCommand('BufEnter', scriptin) - exec 'source '.scriptin - endif - endif - let scriptout = s:GetScriptout(a:infoline, home) - if scriptout != '' - if !filereadable(glob(scriptout)) - call confirm('"'.scriptout.'" not found. Ignoring.', "&OK", 1) - else - call s:SetupScriptAutoCommand('BufLeave', scriptout) - endif - endif - return 1 - endfunction - ">>> - " s:DoFoldOrOpenEntry(cmd0, cmd1) <<< - " Used for double clicking. If the mouse is on a fold, open/close it. If - " not, try to open the file. - function! s:DoFoldOrOpenEntry(cmd0, cmd1) - if getline('.')=~'{\|}' || foldclosed('.') != -1 - normal! za - else - call s:DoEnsurePlacementSize_au() - call s:OpenEntry(line('.'), a:cmd0, a:cmd1, 0) - if (match(g:proj_flags, '\Cc') != -1) - let g:proj_mywinnumber = winbufnr(0) - Project - hide - if(g:proj_mywinnumber != winbufnr(0)) - wincmd p - endif - wincmd = - endif - endif - endfunction ">>> - " s:VimDirListing(filter, padding, separator, filevariable, filecount, dirvariable, dircount) <<< - function! s:VimDirListing(filter, padding, separator, filevariable, filecount, dirvariable, dircount) - let end = 0 - let files='' - let filter = a:filter - " Chop up the filter - " Apparently glob() cannot take something like this: glob('*.c *.h') - let while_var = 1 - while while_var - let end = stridx(filter, ' ') - if end == -1 - let end = strlen(filter) - let while_var = 0 - endif - let single=glob(strpart(filter, 0, end)) - if strlen(single) != 0 - let files = files.single."\010" - endif - let filter = strpart(filter, end + 1) - endwhile - " files now contains a list of everything in the directory. We need to - " weed out the directories. - let fnames=files - let {a:filevariable}='' - let {a:dirvariable}='' - let {a:filecount}=0 - let {a:dircount}=0 - while strlen(fnames) > 0 - let fname = substitute(fnames, '\(\(\f\|[ :\[\]]\)*\).*', '\1', '') - let fnames = substitute(fnames, '\(\f\|[ :\[\]]\)*.\(.*\)', '\2', '') - if isdirectory(glob(fname)) - let {a:dirvariable}={a:dirvariable}.a:padding.fname.a:separator - let {a:dircount}={a:dircount} + 1 - else - let {a:filevariable}={a:filevariable}.a:padding.fname.a:separator - let {a:filecount}={a:filecount} + 1 - endif - endwhile - endfunction ">>> - " s:GenerateEntry(recursive, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) <<< - function! s:GenerateEntry(recursive, line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) - let line=a:line - if a:dir =~ '\\ ' - let dir='"'.substitute(a:dir, '\\ ', ' ', 'g').'"' - else - let dir=a:dir - endif - let spaces=strpart(' ', 0, a:foldlev) - let c_d=(strlen(a:c_d) > 0) ? 'CD='.a:c_d.' ' : '' - let c_d=(strlen(a:filter_directive) > 0) ? c_d.'filter="'.a:filter_directive.'" ': c_d - call append(line, spaces.'}') - call append(line, spaces.a:name.'='.dir.' '.c_d.'{') - if a:recursive - exec 'cd '.a:absolute_dir - call s:VimDirListing("*", '', "\010", 'b:files', 'b:filecount', 'b:dirs', 'b:dircount') - cd - - let dirs=b:dirs - let dcount=b:dircount - unlet b:files b:filecount b:dirs b:dircount - while dcount > 0 - let dname = substitute(dirs, '\(\( \|\f\|:\)*\).*', '\1', '') - let edname = escape(dname, ' ') - let dirs = substitute(dirs, '\( \|\f\|:\)*.\(.*\)', '\2', '') - let line=s:GenerateEntry(1, line + 1, dname, a:absolute_dir.'/'.edname, edname, '', '', a:filter, a:foldlev+1, a:sort) - let dcount=dcount-1 - endwhile - endif - return line+1 - endfunction " >>> - " s:DoEntryFromDir(line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) <<< - " Generate the fold from the directory hierarchy (if recursive), then - " fill it in with RefreshEntriesFromDir() - function! s:DoEntryFromDir(recursive, line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) - call s:GenerateEntry(a:recursive, a:line, a:name, escape(a:absolute_dir, ' '), escape(a:dir, ' '), escape(a:c_d, ' '), a:filter_directive, a:filter, a:foldlev, a:sort) - normal! j - call s:RefreshEntriesFromDir(1) - endfunction ">>> - " s:CreateEntriesFromDir(recursive) <<< - " Prompts user for information and then calls s:DoEntryFromDir() - function! s:CreateEntriesFromDir(recursive) - " Save a mark for the current cursor position - normal! mk - let line=line('.') - let name = inputdialog('Enter the Name of the Entry: ') - if strlen(name) == 0 - return - endif - let foldlev=foldlevel(line) - if (foldclosed(line) != -1) || (getline(line) =~ '}') - let foldlev=foldlev - 1 - endif - let absolute = (foldlev <= 0)?'Absolute ': '' - let home='' - let filter='*' - if (match(g:proj_flags, '\Cb') != -1) && has('browse') - " Note that browse() is inconsistent: On Win32 you can't select a - " directory, and it gives you a relative path. - let dir = browse(0, 'Enter the '.absolute.'Directory to Load: ', '', '') - let dir = fnamemodify(dir, ':p') - else - let dir = inputdialog('Enter the '.absolute.'Directory to Load: ', '') - endif - if (dir[strlen(dir)-1] == '/') || (dir[strlen(dir)-1] == '\\') - let dir=strpart(dir, 0, strlen(dir)-1) " Remove trailing / or \ - endif - let dir = substitute(dir, '^\~', $HOME, 'g') - if (foldlev > 0) - let parent_directive=s:RecursivelyConstructDirectives(line) - let filter = s:GetFilter(parent_directive, '*') - let home=s:GetHome(parent_directive, '') - if home[strlen(home)-1] != '/' && home[strlen(home)-1] != '\\' - let home=home.'/' - endif - unlet parent_directive - if s:IsAbsolutePath(dir) - " It is not a relative path Try to make it relative - let hend=matchend(dir, '\C'.glob(home)) - if hend != -1 - let dir=strpart(dir, hend) " The directory can be a relative path - else - let home="" - endif - endif - endif - if strlen(home.dir) == 0 - return - endif - if !isdirectory(home.dir) - if has("unix") - silent exec '!mkdir '.home.dir.' > /dev/null' - else - call confirm('"'.home.dir.'" is not a valid directory.', "&OK", 1) - return - endif - endif - let c_d = inputdialog('Enter the CD parameter: ', '') - let filter_directive = inputdialog('Enter the File Filter: ', '') - if strlen(filter_directive) != 0 - let filter = filter_directive - endif - " If I'm on a closed fold, go to the bottom of it - if foldclosedend(line) != -1 - let line = foldclosedend(line) - endif - let foldlev = foldlevel(line) - " If we're at the end of a fold . . . - if getline(line) =~ '}' - let foldlev = foldlev - 1 " . . . decrease the indentation by 1. - endif - " Do the work - call s:DoEntryFromDir(a:recursive, line, name, home.dir, dir, c_d, filter_directive, filter, foldlev, 0) - " Restore the cursor position - normal! `k - endfunction ">>> - " s:RefreshEntriesFromDir(recursive) <<< - " Finds metadata at the top of the fold, and then replaces all files - " with the contents of the directory. Works recursively if recursive is 1. - function! s:RefreshEntriesFromDir(recursive) - if foldlevel('.') == 0 - echo 'Nothing to refresh.' - return - endif - " Open the fold. - if getline('.') =~ '}' - normal! zo[z - else - normal! zo]z[z - endif - let just_a_fold=0 - let infoline = s:RecursivelyConstructDirectives(line('.')) - let immediate_infoline = getline('.') - if strlen(substitute(immediate_infoline, '[^=]*=\(\(\f\|:\|\\ \)*\).*', '\1', '')) == strlen(immediate_infoline) - let just_a_fold = 1 - endif - " Extract the home directory of the fold - let home = s:GetHome(infoline, '') - if home == '' - " No Match. This means that this is just a label with no - " directory entry. - if a:recursive == 0 - return " We're done--nothing to do - endif - " Mark that it is just a fold, so later we don't delete filenames - " that aren't there. - let just_a_fold = 1 - endif - if just_a_fold == 0 - " Extract the filter between quotes (we don't care what CD is). - let filter = s:GetFilter(infoline, '*') - " Extract the description (name) of the fold - let name = substitute(infoline, '^[#\t ]*\([^=]*\)=.*', '\1', '') - if strlen(name) == strlen(infoline) - return " If there's no name, we're done. - endif - if (home == '') || (name == '') - return - endif - " Extract the flags - let flags = s:GetFlags(immediate_infoline) - let sort = (match(g:proj_flags, '\CS') != -1) - if flags != '' - if match(flags, '\Cr') != -1 - " If the flags do not contain r (refresh), then treat it just - " like a fold - let just_a_fold = 1 - endif - if match(flags, '\CS') != -1 - let sort = 1 - endif - if match(flags, '\Cs') != -1 - let sort = 0 - endif - else - let flags='' - endif - endif - " Move to the first non-fold boundary line - normal! j - " Delete filenames until we reach the end of the fold - while getline('.') !~ '}' - if line('.') == line('$') - break - endif - if getline('.') !~ '{' - " We haven't reached a sub-fold, so delete what's there. - if (just_a_fold == 0) && (getline('.') !~ '^\s*#') && (getline('.') !~ '#.*pragma keep') - d _ - else - " Skip lines only in a fold and comment lines - normal! j - endif - else - " We have reached a sub-fold. If we're doing recursive, then - " call this function again. If not, find the end of the fold. - if a:recursive == 1 - call s:RefreshEntriesFromDir(1) - normal! ]zj - else - if foldclosed('.') == -1 - normal! zc - endif - normal! j - endif - endif - endwhile - if just_a_fold == 0 - " We're not just in a fold, and we have deleted all the filenames. - " Now it is time to regenerate what is in the directory. - if !isdirectory(glob(home)) - call confirm('"'.home.'" is not a valid directory.', "&OK", 1) - else - let foldlev=foldlevel('.') - " T flag. Thanks Tomas Z. - if (match(flags, '\Ct') != -1) || ((match(g:proj_flags, '\CT') == -1) && (match(flags, '\CT') == -1)) - " Go to the top of the fold (force other folds to the - " bottom) - normal! [z - normal! j - " Skip any comments - while getline('.') =~ '^\s*#' - normal! j - endwhile - endif - normal! k - let cwd=getcwd() - let spaces=strpart(' ', 0, foldlev) - exec 'cd '.home - if match(g:proj_flags, '\Ci') != -1 - echon home."\r" - endif - call s:VimDirListing(filter, spaces, "\n", 'b:files', 'b:filecount', 'b:dirs', 'b:dircount') - if b:filecount > 0 - normal! mk - silent! put =b:files - normal! `kj - if sort - call s:SortR(line('.'), line('.') + b:filecount - 1) - endif - else - normal! j - endif - unlet b:files b:filecount b:dirs b:dircount - exec 'cd '.cwd - endif - endif - " Go to the top of the refreshed fold. - normal! [z - endfunction ">>> - " s:MoveUp() <<< - " Moves the entity under the cursor up a line. - function! s:MoveUp() - let lineno=line('.') - if lineno == 1 - return - endif - let fc=foldclosed('.') - let a_reg=@a - if lineno == line('$') - normal! "add"aP - else - normal! "addk"aP - endif - let @a=a_reg - if fc != -1 - normal! zc - endif - endfunction ">>> - " s:MoveDown() <<< - " Moves the entity under the cursor down a line. - function! s:MoveDown() - let fc=foldclosed('.') - let a_reg=@a - normal! "add"ap - let @a=a_reg - if (fc != -1) && (foldclosed('.') == -1) - normal! zc - endif - endfunction " >>> - " s:DisplayInfo() <<< - " Displays filename and current working directory when i (info) is in - " the flags. - function! s:DisplayInfo() - if match(g:proj_flags, '\Ci') != -1 - echo 'file: '.expand('%').', cwd: '.getcwd().', lines: '.line('$') - endif - endfunction ">>> - " s:SetupAutoCommand(cwd) <<< - " Sets up an autocommand to ensure that the cwd is set to the one - " desired for the fold regardless. :lcd only does this on a per-window - " basis, not a per-buffer basis. - function! s:SetupAutoCommand(cwd) - if !exists("b:proj_has_autocommand") - let b:proj_cwd_save = escape(getcwd(), ' ') - let b:proj_has_autocommand = 1 - let bufname=escape(substitute(expand('%:p', 0), '\\', '/', 'g'), ' ') - exec 'au BufEnter '.bufname." let b:proj_cwd_save=escape(getcwd(), ' ') | cd ".a:cwd - exec 'au BufLeave '.bufname.' exec "cd ".b:proj_cwd_save' - exec 'au BufWipeout '.bufname.' au! * '.bufname - endif - endfunction ">>> - " s:SetupScriptAutoCommand(bufcmd, script) <<< - " Sets up an autocommand to run the scriptin script. - function! s:SetupScriptAutoCommand(bufcmd, script) - if !exists("b:proj_has_".a:bufcmd) - let b:proj_has_{a:bufcmd} = 1 - exec 'au '.a:bufcmd.' '.escape(substitute(expand('%:p', 0), '\\', '/', 'g'), ' ').' source '.a:script - endif - endfunction " >>> - " s:DoEnsurePlacementSize_au() <<< - " Ensure that the Project window is on the left of the window and has - " the correct size. Only called from an autocommand - function! s:DoEnsurePlacementSize_au() - if (winbufnr(0) != g:proj_running) || (winnr() != 1) - if exists("g:proj_doinghelp") - if g:proj_doinghelp > 0 - let g:proj_doinghelp = g:proj_doinghelp - 1 - return - endif - unlet g:proj_doinghelp - return - endif - exec b:proj_locate_command - endif - exec b:proj_resize_command - endfunction ">>> - " s:Spawn(number) <<< - " Spawn an external command on the file - function! s:Spawn(number) - echo | if exists("g:proj_run".a:number) - let fname=getline('.') - if fname!~'{\|}' - let fname=substitute(fname, '\s*#.*', '', '') - let fname=substitute(fname, '^\s*\(.*\)\s*', '\1', '') - if fname == '' | return | endif - let parent_infoline = s:RecursivelyConstructDirectives(line('.')) - let home=expand(s:GetHome(parent_infoline, '')) - let c_d=expand(s:GetCd(parent_infoline, '')) - let command=substitute(g:proj_run{a:number}, '%%', "\010", 'g') - let command=substitute(command, '%f', escape(home.'/'.fname, '\'), 'g') - let command=substitute(command, '%F', substitute(escape(home.'/'.fname, '\'), ' ', '\\\\ ', 'g'), 'g') - let command=substitute(command, '%s', escape(home.'/'.fname, '\'), 'g') - let command=substitute(command, '%n', escape(fname, '\'), 'g') - let command=substitute(command, '%N', substitute(fname, ' ', '\\\\ ', 'g'), 'g') - let command=substitute(command, '%h', escape(home, '\'), 'g') - let command=substitute(command, '%H', substitute(escape(home, '\'), ' ', '\\\\ ', 'g'), 'g') - if c_d != '' - if c_d == home - let percent_r='.' - else - let percent_r=substitute(home, escape(c_d.'/', '\'), '', 'g') - endif - else - let percent_r=home - endif - let command=substitute(command, '%r', percent_r, 'g') - let command=substitute(command, '%R', substitute(percent_r, ' ', '\\\\ ', 'g'), 'g') - let command=substitute(command, '%d', escape(c_d, '\'), 'g') - let command=substitute(command, '%D', substitute(escape(c_d, '\'), ' ', '\\\\ ', 'g'), 'g') - let command=substitute(command, "\010", '%', 'g') - exec command - endif - endif - endfunction ">>> - " s:ListSpawn(varnamesegment) <<< - " List external commands - function! s:ListSpawn(varnamesegment) - let number = 1 - while number < 10 - if exists("g:proj_run".a:varnamesegment.number) - echohl LineNr | echo number.':' | echohl None | echon ' '.substitute(escape(g:proj_run{a:varnamesegment}{number}, '\'), "\n", '\\n', 'g') - else - echohl LineNr | echo number.':' | echohl None - endif - let number=number + 1 - endwhile - endfunction ">>> - " s:FindFoldTop(line) <<< - " Return the line number of the directive line - function! s:FindFoldTop(line) - let lineno=a:line - if getline(lineno) =~ '}' - let lineno = lineno - 1 - endif - while getline(lineno) !~ '{' && lineno > 1 - if getline(lineno) =~ '}' - let lineno=s:FindFoldTop(lineno) - endif - let lineno = lineno - 1 - endwhile - return lineno - endfunction ">>> - " s:FindFoldBottom(line) <<< - " Return the line number of the directive line - function! s:FindFoldBottom(line) - let lineno=a:line - if getline(lineno) =~ '{' - let lineno=lineno + 1 - endif - while getline(lineno) !~ '}' && lineno < line('$') - if getline(lineno) =~ '{' - let lineno=s:FindFoldBottom(lineno) - endif - let lineno = lineno + 1 - endwhile - return lineno - endfunction ">>> - " s:LoadAll(recurse, line) <<< - " Load all files in a project - function! s:LoadAll(recurse, line) - let b:loadcount=0 - function! s:SpawnExec(infoline, fname, lineno, data) - if s:OpenEntry2(a:lineno, a:infoline, a:fname, 'e') - wincmd p - let b:loadcount=b:loadcount+1 - echon b:loadcount."\r" - if getchar(0) != 0 - let b:stop_everything=1 - endif - endif - endfunction - call Project_ForEach(a:recurse, line('.'), "*<SID>SpawnExec", 0, '^\(.*l\)\@!') - delfunction s:SpawnExec - echon b:loadcount." Files Loaded\r" - unlet b:loadcount - if exists("b:stop_everything") | unlet b:stop_everything | endif - endfunction ">>> - " s:WipeAll(recurse, line) <<< - " Wipe all files in a project - function! s:WipeAll(recurse, line) - let b:wipecount=0 - let b:totalcount=0 - function! s:SpawnExec(home, c_d, fname, lineno, data) - let fname=escape(a:fname, ' ') - if s:IsAbsolutePath(fname) - let fname=fnamemodify(fname, ':n') " :n is coming, won't break anything now - else - let fname=fnamemodify(a:home.'/'.fname, ':n') " :n is coming, won't break anything now - endif - let b:totalcount=b:totalcount+1 - let fname=substitute(fname, '^\~', $HOME, 'g') - if bufloaded(substitute(fname, '\\ ', ' ', 'g')) - if getbufvar(fname.'\>', '&modified') == 1 - exec 'sb '.fname - wincmd L - w - wincmd p - endif - let b:wipecount=b:wipecount+1 - exec 'bwipe! '.fname - endif - if b:totalcount % 5 == 0 - echon b:wipecount.' of '.b:totalcount."\r" - redraw - endif - if getchar(0) != 0 - let b:stop_everything=1 - endif - endfunction - call Project_ForEach(a:recurse, line('.'), "<SID>SpawnExec", 0, '^\(.*w\)\@!') - delfunction s:SpawnExec - echon b:wipecount.' of '.b:totalcount." Files Wiped\r" - unlet b:wipecount b:totalcount - if exists("b:stop_everything") | unlet b:stop_everything | endif - endfunction ">>> - " s:LoadAllSplit(recurse, line) <<< - " Load all files in a project using split windows. - " Contributed by A. Harrison - function! s:LoadAllSplit(recurse, line) - let b:loadcount=0 - function! s:SpawnExec(infoline, fname, lineno, data) - let winNr = winnr() "get ProjectWindow number - if s:OpenEntry2(a:lineno, a:infoline, a:fname, 'sp') - exec winNr."wincmd w" - let b:loadcount=b:loadcount+1 - echon b:loadcount."\r" - if getchar(0) != 0 - let b:stop_everything=1 - endif - endif - endfunction - call Project_ForEach(a:recurse, line('.'), "*<SID>SpawnExec", 0, '^\(.*l\)\@!') - delfunction s:SpawnExec - echon b:loadcount." Files Loaded\r" - unlet b:loadcount - if exists("b:stop_everything") | unlet b:stop_everything | endif - endfunction ">>> - " s:GrepAll(recurse, lineno, pattern) <<< - " Grep all files in a project, optionally recursively - function! s:GrepAll(recurse, lineno, pattern) - cunmap <buffer> help - let pattern=(a:pattern[0] == '')?input("GREP options and pattern: "):a:pattern - cnoremap <buffer> help let g:proj_doinghelp = 1<CR>:help - if pattern[0] == '' - return - endif - let b:escape_spaces=1 - let fnames=Project_GetAllFnames(a:recurse, a:lineno, ' ') - unlet b:escape_spaces - cclose " Make sure grep window is closed - call s:DoSetupAndSplit() - if match(g:proj_flags, '\Cv') == -1 - silent! exec 'silent! grep '.pattern.' '.fnames - if v:shell_error != 0 - echo 'GREP error. Perhaps there are too many filenames.' - else - copen - endif - else - silent! exec 'silent! vimgrep '.pattern.' '.fnames - copen - endif - endfunction ">>> - " GetXXX Functions <<< - function! s:GetHome(info, parent_home) - " Thanks to Adam Montague for pointing out the need for @ in urls. - let home=substitute(a:info, '^[^=]*=\(\(\\ \|\f\|:\|@\)\+\).*', '\1', '') - if strlen(home) == strlen(a:info) - let home=substitute(a:info, '.\{-}"\(.\{-}\)".*', '\1', '') - if strlen(home) != strlen(a:info) | let home=escape(home, ' ') | endif - endif - if strlen(home) == strlen(a:info) - let home=a:parent_home - elseif home=='.' - let home=a:parent_home - elseif !s:IsAbsolutePath(home) - let home=a:parent_home.'/'.home - endif - return home - endfunction - function! s:GetFilter(info, parent_filter) - let filter = substitute(a:info, '.*\<filter="\([^"]*\).*', '\1', '') - if strlen(filter) == strlen(a:info) | let filter = a:parent_filter | endif - return filter - endfunction - function! s:GetCd(info, home) - let c_d=substitute(a:info, '.*\<CD=\(\(\\ \|\f\|:\)\+\).*', '\1', '') - if strlen(c_d) == strlen(a:info) - let c_d=substitute(a:info, '.*\<CD="\(.\{-}\)".*', '\1', '') - if strlen(c_d) != strlen(a:info) | let c_d=escape(c_d, ' ') | endif - endif - if strlen(c_d) == strlen(a:info) - let c_d='' - elseif c_d == '.' - let c_d = a:home - elseif !s:IsAbsolutePath(c_d) - let c_d = a:home.'/'.c_d - endif - return c_d - endfunction - function! s:GetScriptin(info, home) - let scriptin = substitute(a:info, '.*\<in=\(\(\\ \|\f\|:\)\+\).*', '\1', '') - if strlen(scriptin) == strlen(a:info) - let scriptin=substitute(a:info, '.*\<in="\(.\{-}\)".*', '\1', '') - if strlen(scriptin) != strlen(a:info) | let scriptin=escape(scriptin, ' ') | endif - endif - if strlen(scriptin) == strlen(a:info) | let scriptin='' | else - if !s:IsAbsolutePath(scriptin) | let scriptin=a:home.'/'.scriptin | endif | endif - return scriptin - endfunction - function! s:GetScriptout(info, home) - let scriptout = substitute(a:info, '.*\<out=\(\(\\ \|\f\|:\)\+\).*', '\1', '') - if strlen(scriptout) == strlen(a:info) - let scriptout=substitute(a:info, '.*\<out="\(.\{-}\)".*', '\1', '') - if strlen(scriptout) != strlen(a:info) | let scriptout=escape(scriptout, ' ') | endif - endif - if strlen(scriptout) == strlen(a:info) | let scriptout='' | else - if !s:IsAbsolutePath(scriptout) | let scriptout=a:home.'/'.scriptout | endif | endif - return scriptout - endfunction - function! s:GetFlags(info) - let flags=substitute(a:info, '.*\<flags=\([^ {]*\).*', '\1', '') - if (strlen(flags) == strlen(a:info)) - let flags='' - endif - return flags - endfunction ">>> - " Project_GetAllFnames(recurse, lineno, separator) <<< - " Grep all files in a project, optionally recursively - function! Project_GetAllFnames(recurse, lineno, separator) - let b:fnamelist='' - function! s:SpawnExec(home, c_d, fname, lineno, data) - if exists('b:escape_spaces') - let fname=escape(a:fname, ' ') - else - let fname=a:fname - endif - if !s:IsAbsolutePath(a:fname) - let fname=a:home.'/'.fname - endif - let b:fnamelist=b:fnamelist.a:data.fname - endfunction - call Project_ForEach(a:recurse, line('.'), "<SID>SpawnExec", a:separator, '') - delfunction s:SpawnExec - let retval=b:fnamelist - unlet b:fnamelist - return retval - endfunction ">>> - " Project_GetAllFnames(recurse, lineno, separator) <<< - " Grep all files in a project, optionally recursively - function! Project_GetFname(line) - if (foldlevel(a:line) == 0) - return '' - endif - let fname=substitute(getline(a:line), '\s*#.*', '', '') " Get rid of comments and whitespace before comment - let fname=substitute(fname, '^\s*\(.*\)', '\1', '') " Get rid of leading whitespace - if strlen(fname) == 0 - return '' " The line is blank. Do nothing. - endif - if s:IsAbsolutePath(fname) - return fname - endif - let infoline = s:RecursivelyConstructDirectives(a:line) - return s:GetHome(infoline, '').'/'.fname - endfunction ">>> - " Project_ForEach(recurse, lineno, cmd, data, match) <<< - " Grep all files in a project, optionally recursively - function! Project_ForEach(recurse, lineno, cmd, data, match) - let info=s:RecursivelyConstructDirectives(a:lineno) - let lineno=s:FindFoldTop(a:lineno) + 1 - let flags=s:GetFlags(getline(lineno - 1)) - if (flags == '') || (a:match=='') || (match(flags, a:match) != -1) - call s:Project_ForEachR(a:recurse, lineno, info, a:cmd, a:data, a:match) - endif - endfunction - function! s:Project_ForEachR(recurse, lineno, info, cmd, data, match) - let home=s:GetHome(a:info, '') - let c_d=s:GetCd(a:info, home) - let scriptin = s:GetScriptin(a:info, home) - let scriptout = s:GetScriptout(a:info, home) - let filter = s:GetFilter(a:info, '') - let lineno = a:lineno - let curline=getline(lineno) - while (curline !~ '}') && (curline < line('$')) - if exists("b:stop_everything") && b:stop_everything | return 0 | endif - if curline =~ '{' - if a:recurse - let flags=s:GetFlags(curline) - if (flags == '') || (a:match=='') || (match(flags, a:match) != -1) - let this_home=s:GetHome(curline, home) - let this_cd=s:GetCd(curline, this_home) - if this_cd=='' | let this_cd=c_d | endif - let this_scriptin=s:GetScriptin(curline, this_home) - if this_scriptin == '' | let this_scriptin=scriptin | endif - let this_scriptout=s:GetScriptin(curline, this_home) - if this_scriptout == '' | let this_scriptout=scriptout | endif - let this_filter=s:GetFilter(curline, filter) - let lineno=s:Project_ForEachR(1, lineno+1, - \s:ConstructInfo(this_home, this_cd, this_scriptin, this_scriptout, flags, this_filter), a:cmd, a:data, a:match) - else - let lineno=s:FindFoldBottom(lineno) - endif - else - let lineno=s:FindFoldBottom(lineno) - endif - else - let fname=substitute(curline, '\s*#.*', '', '') - let fname=substitute(fname, '^\s*\(.*\)', '\1', '') - if (strlen(fname) != strlen(curline)) && (fname[0] != '') - if a:cmd[0] == '*' - call {strpart(a:cmd, 1)}(a:info, fname, lineno, a:data) - else - call {a:cmd}(home, c_d, fname, lineno, a:data) - endif - endif - endif - let lineno=lineno + 1 - let curline=getline(lineno) - endwhile - return lineno - endfunction ">>> - " s:SpawnAll(recurse, number) <<< - " Spawn an external command on the files of a project - function! s:SpawnAll(recurse, number) - echo | if exists("g:proj_run_fold".a:number) - if g:proj_run_fold{a:number}[0] == '*' - function! s:SpawnExec(home, c_d, fname, lineno, data) - let command=substitute(strpart(g:proj_run_fold{a:data}, 1), '%s', escape(a:fname, ' \'), 'g') - let command=substitute(command, '%f', escape(a:fname, '\'), 'g') - let command=substitute(command, '%h', escape(a:home, '\'), 'g') - let command=substitute(command, '%d', escape(a:c_d, '\'), 'g') - let command=substitute(command, '%F', substitute(escape(a:fname, '\'), ' ', '\\\\ ', 'g'), 'g') - exec command - endfunction - call Project_ForEach(a:recurse, line('.'), "<SID>SpawnExec", a:number, '.') - delfunction s:SpawnExec - else - let info=s:RecursivelyConstructDirectives(line('.')) - let home=s:GetHome(info, '') - let c_d=s:GetCd(info, '') - let b:escape_spaces=1 - let fnames=Project_GetAllFnames(a:recurse, line('.'), ' ') - unlet b:escape_spaces - let command=substitute(g:proj_run_fold{a:number}, '%f', substitute(escape(fnames, '\'), '\\ ', ' ', 'g'), 'g') - let command=substitute(command, '%s', escape(fnames, '\'), 'g') - let command=substitute(command, '%h', escape(home, '\'), 'g') - let command=substitute(command, '%d', escape(c_d, '\'), 'g') - let command=substitute(command, '%F', escape(fnames, '\'), 'g') - exec command - if v:shell_error != 0 - echo 'Shell error. Perhaps there are too many filenames.' - endif - endif - endif - endfunction ">>> - if !exists("g:proj_running") - " s:DoProjectOnly(void) <<< - " Make the file window the only one. - function! s:DoProjectOnly() - if winbufnr(0) != g:proj_running - let lzsave=&lz - set lz - only - Project - silent! wincmd p - let &lz=lzsave - unlet lzsave - endif - endfunction - " >>> - - " Mappings <<< - nnoremap <buffer> <silent> <Return> \|:call <SID>DoFoldOrOpenEntry('', 'e')<CR> - nnoremap <buffer> <silent> <S-Return> \|:call <SID>DoFoldOrOpenEntry('', 'sp')<CR> - nnoremap <buffer> <silent> <C-Return> \|:call <SID>DoFoldOrOpenEntry('silent! only', 'e')<CR> - nnoremap <buffer> <silent> <LocalLeader>T \|:call <SID>DoFoldOrOpenEntry('', 'tabe')<CR> - nmap <buffer> <silent> <LocalLeader>s <S-Return> - nnoremap <buffer> <silent> <LocalLeader>S \|:call <SID>LoadAllSplit(0, line('.'))<CR> - nmap <buffer> <silent> <LocalLeader>o <C-Return> - nnoremap <buffer> <silent> <LocalLeader>i :echo <SID>RecursivelyConstructDirectives(line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>I :echo Project_GetFname(line('.'))<CR> - nmap <buffer> <silent> <M-CR> <Return><C-W>p - nmap <buffer> <silent> <LocalLeader>v <M-CR> - nnoremap <buffer> <silent> <LocalLeader>l \|:call <SID>LoadAll(0, line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>L \|:call <SID>LoadAll(1, line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>w \|:call <SID>WipeAll(0, line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>W \|:call <SID>WipeAll(1, line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>W \|:call <SID>WipeAll(1, line('.'))<CR> - nnoremap <buffer> <silent> <LocalLeader>g \|:call <SID>GrepAll(0, line('.'), "")<CR> - nnoremap <buffer> <silent> <LocalLeader>G \|:call <SID>GrepAll(1, line('.'), "")<CR> - nnoremap <buffer> <silent> <2-LeftMouse> \|:call <SID>DoFoldOrOpenEntry('', 'e')<CR> - nnoremap <buffer> <silent> <S-2-LeftMouse> \|:call <SID>DoFoldOrOpenEntry('', 'sp')<CR> - nnoremap <buffer> <silent> <M-2-LeftMouse> <M-CR> - nnoremap <buffer> <silent> <S-LeftMouse> <LeftMouse> - nmap <buffer> <silent> <C-2-LeftMouse> <C-Return> - nnoremap <buffer> <silent> <C-LeftMouse> <LeftMouse> - nnoremap <buffer> <silent> <3-LeftMouse> <Nop> - nmap <buffer> <silent> <RightMouse> <space> - nmap <buffer> <silent> <2-RightMouse> <space> - nmap <buffer> <silent> <3-RightMouse> <space> - nmap <buffer> <silent> <4-RightMouse> <space> - nnoremap <buffer> <silent> <space> \|:silent exec 'vertical resize '.(match(g:proj_flags, '\Ct')!=-1 && winwidth('.') > g:proj_window_width?(g:proj_window_width):(winwidth('.') + g:proj_window_increment))<CR> - nnoremap <buffer> <silent> <C-Up> \|:silent call <SID>MoveUp()<CR> - nnoremap <buffer> <silent> <C-Down> \|:silent call <SID>MoveDown()<CR> - nmap <buffer> <silent> <LocalLeader><Up> <C-Up> - nmap <buffer> <silent> <LocalLeader><Down> <C-Down> - let k=1 - while k < 10 - exec 'nnoremap <buffer> <LocalLeader>'.k.' \|:call <SID>Spawn('.k.')<CR>' - exec 'nnoremap <buffer> <LocalLeader>f'.k.' \|:call <SID>SpawnAll(0, '.k.')<CR>' - exec 'nnoremap <buffer> <LocalLeader>F'.k.' \|:call <SID>SpawnAll(1, '.k.')<CR>' - let k=k+1 - endwhile - nnoremap <buffer> <LocalLeader>0 \|:call <SID>ListSpawn("")<CR> - nnoremap <buffer> <LocalLeader>f0 \|:call <SID>ListSpawn("_fold")<CR> - nnoremap <buffer> <LocalLeader>F0 \|:call <SID>ListSpawn("_fold")<CR> - nnoremap <buffer> <silent> <LocalLeader>c :call <SID>CreateEntriesFromDir(0)<CR> - nnoremap <buffer> <silent> <LocalLeader>C :call <SID>CreateEntriesFromDir(1)<CR> - nnoremap <buffer> <silent> <LocalLeader>r :call <SID>RefreshEntriesFromDir(0)<CR> - nnoremap <buffer> <silent> <LocalLeader>R :call <SID>RefreshEntriesFromDir(1)<CR> - " For Windows users: same as \R - nnoremap <buffer> <silent> <F5> :call <SID>RefreshEntriesFromDir(1)<CR> - nnoremap <buffer> <silent> <LocalLeader>e :call <SID>OpenEntry(line('.'), '', '', 0)<CR> - nnoremap <buffer> <silent> <LocalLeader>E :call <SID>OpenEntry(line('.'), '', 'e', 1)<CR> - " The :help command stomps on the Project Window. Try to avoid that. - " This is not perfect, but it is alot better than without the mappings. - cnoremap <buffer> help let g:proj_doinghelp = 1<CR>:help - nnoremap <buffer> <F1> :let g:proj_doinghelp = 1<CR><F1> - " This is to avoid changing the buffer, but it is not fool-proof. - nnoremap <buffer> <silent> <C-^> <Nop> - "nnoremap <script> <Plug>ProjectOnly :let lzsave=&lz<CR>:set lz<CR><C-W>o:Project<CR>:silent! wincmd p<CR>:let &lz=lzsave<CR>:unlet lzsave<CR> - nnoremap <script> <Plug>ProjectOnly :call <SID>DoProjectOnly()<CR> - if match(g:proj_flags, '\Cm') != -1 - if !hasmapto('<Plug>ProjectOnly') - nmap <silent> <unique> <C-W>o <Plug>ProjectOnly - nmap <silent> <unique> <C-W><C-O> <C-W>o - endif - endif " >>> - if filereadable(glob('~/.vimproject_mappings')) | source ~/.vimproject_mappings | endif - " Autocommands <<< - " Autocommands to clean up if we do a buffer wipe - " These don't work unless we substitute \ for / for Windows - let bufname=escape(substitute(expand('%:p', 0), '\\', '/', 'g'), ' ') - exec 'au BufWipeout '.bufname.' au! * '.bufname - exec 'au BufWipeout '.bufname.' unlet g:proj_running' - exec 'au BufWipeout '.bufname.' nunmap <C-W>o' - exec 'au BufWipeout '.bufname.' nunmap <C-W><C-O>' - " Autocommands to keep the window the specified size - exec 'au WinLeave '.bufname.' call s:DoEnsurePlacementSize_au()' - exec 'au BufEnter '.bufname.' call s:DoSetupAndSplit_au()' - au WinLeave * call s:RecordPrevBuffer_au() - " >>> - setlocal buflisted - let g:proj_running = bufnr(bufname.'\>') - if g:proj_running == -1 - call confirm('Project/Vim error. Please Enter :Project again and report this bug.', "&OK", 1) - unlet g:proj_running - endif - setlocal nobuflisted - endif -endfunction " >>> - -if exists(':Project') != 2 - command -nargs=? -complete=file Project call <SID>Project('<args>') -endif -" Toggle Mapping -if !exists("*<SID>DoToggleProject()") "<<< - function! s:DoToggleProject() - if !exists('g:proj_running') || bufwinnr(g:proj_running) == -1 - Project - else - let g:proj_mywindow = winnr() - Project - hide - if(winnr() != g:proj_mywindow) - wincmd p - endif - unlet g:proj_mywindow - endif - endfunction -endif ">>> -nnoremap <script> <Plug>ToggleProject :call <SID>DoToggleProject()<CR> -if exists('g:proj_flags') && (match(g:proj_flags, '\Cg') != -1) - if !hasmapto('<Plug>ToggleProject') - nmap <silent> <F12> <Plug>ToggleProject - endif -endif - -finish - -" vim600: set foldmethod=marker foldmarker=<<<,>>> foldlevel=1: diff --git a/files/.vim/plugin/remoteOpen.vim b/files/.vim/plugin/remoteOpen.vim deleted file mode 100644 index cb550ff..0000000 --- a/files/.vim/plugin/remoteOpen.vim +++ /dev/null @@ -1,163 +0,0 @@ -" File: remoteOpen.vim -" Author: Srinath Avadhanula <srinath AT fastmail DOT fm> -" $Id: remoteOpen.vim 997 2006-03-20 09:45:45Z srinathava $ -" -" Description: -" Often times, an external program needs to open a file in gvim from the -" command line. However, it will not know if the file is already opened in a -" previous vim session. It is not sufficient to simply specify -" -" gvim --remote-silent <filename> -" -" because this simply opens up <filename> in the first remote gvim session it -" sees. This script provides a command RemoteOpen which is meant to be used -" from the command line as follows: -" -" gvim -c ":RemoteOpen +<lnum> <filename>" -" -" where <lnum> is the line-number you wish <filename> to open to. What will -" happen is that a new gvim will start up and enquire from all previous -" sessions if <filename> is already open in any of them. If it is, then it -" will edit the file in that session and bring it to the foreground and itself -" quit. Otherwise, it will not quit and instead open up the file for editing -" at <lnum>. -" -" This was mainly created to be used with Yap (the dvi previewer in miktex), -" so you can specify the program for "inverse search" as specified above. -" This ensures that the inverse search uses the correct gvim each time. -" -" Ofcourse, this requires vim with +clientserver. If not, then RemoteOpen just -" opens in the present session. - -" Enclose <args> in single quotes so it can be passed as a function argument. -com -nargs=1 RemoteOpen :call RemoteOpen('<args>') -com -nargs=? RemoteInsert :call RemoteInsert('<args>') - -" RemoteOpen: open a file remotely (if possible) {{{ -" Description: checks all open vim windows to see if this file has been opened -" anywhere and if so, opens it there instead of in this session. -function! RemoteOpen(arglist) - - " First construct line number and filename from argument. a:arglist is of - " the form: - " +10 c:\path\to\file - " or just - " c:\path\to\file - if a:arglist =~ '^\s*+\d\+' - let linenum = matchstr(a:arglist, '^\s*+\zs\d\+\ze') - let filename = matchstr(a:arglist, '^\s*+\d\+\s*\zs.*\ze') - else - let linenum = 1 - let filename = matchstr(a:arglist, '^\s*\zs.*\ze') - endif - let filename = escape(filename, ' ') - call Tex_Debug("linenum = ".linenum.', filename = '.filename, "ropen") - - " If there is no clientserver functionality, then just open in the present - " session and return - if !has('clientserver') - call Tex_Debug("-clientserver, opening locally and returning", "ropen") - exec "e ".filename - exec linenum - normal! zv - return - endif - - " Otherwise, loop through all available servers - let servers = serverlist() - " If there are no servers, open file locally. - if servers == '' - call Tex_Debug("no open servers, opening locally", "ropen") - exec "e ".filename - exec linenum - let g:Remote_Server = 1 - normal! zv - return - endif - - let i = 1 - let server = s:Strntok(servers, "\n", i) - let targetServer = v:servername - - while server != '' - " Find out if there was any server which was used by remoteOpen before - " this. If a new gvim session was ever started via remoteOpen, then - " g:Remote_Server will be set. - if remote_expr(server, 'exists("g:Remote_Server")') - let targetServer = server - endif - - " Ask each server if that file is being edited by them. - let bufnum = remote_expr(server, "bufnr('".filename."')") - " If it is... - if bufnum != -1 - " ask the server to edit that file and come to the foreground. - " set a variable g:Remote_Server to indicate that this server - " session has at least one file opened via RemoteOpen - let targetServer = server - break - end - - let i = i + 1 - let server = s:Strntok(servers, "\n", i) - endwhile - - " If none of the servers have the file open, then open this file in the - " first server. This has the advantage if yap tries to make vim open - " multiple vims, then at least they will all be opened by the same gvim - " server. - call remote_send(targetServer, - \ "\<C-\>\<C-n>". - \ ":let g:Remote_Server = 1\<CR>". - \ ":drop ".filename."\<CR>". - \ ":".linenum."\<CR>zv" - \ ) - call remote_foreground(targetServer) - " quit this vim session - if v:servername != targetServer - q - endif -endfunction " }}} -" RemoteInsert: inserts a \cite'ation remotely (if possible) {{{ -" Description: -function! RemoteInsert(...) - - let citation = matchstr(argv(0), "\\[InsText('.cite{\\zs.\\{-}\\ze}');\\]") - if citation == "" - q - endif - - " Otherwise, loop through all available servers - let servers = serverlist() - - let i = 1 - let server = s:Strntok(servers, "\n", i) - let targetServer = v:servername - - while server != '' - if remote_expr(server, 'exists("g:Remote_WaitingForCite")') - call remote_send(server, citation . "\<CR>") - call remote_foreground(server) - if v:servername != server - q - else - return - endif - endif - - let i = i + 1 - let server = s:Strntok(servers, "\n", i) - endwhile - - q - -endfunction " }}} -" Strntok: extract the n^th token from a list {{{ -" example: Strntok('1,23,3', ',', 2) = 23 -fun! <SID>Strntok(s, tok, n) - return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') -endfun - -" }}} - -" vim:ft=vim:ts=4:sw=4:noet:fdm=marker:commentstring=\"\ %s:nowrap |
