Thread: [Assorted-commits] SF.net SVN: assorted:[963] configs/trunk/src/vim
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-09-11 07:11:02
|
Revision: 963 http://assorted.svn.sourceforge.net/assorted/?rev=963&view=rev Author: yangzhang Date: 2008-09-11 07:11:12 +0000 (Thu, 11 Sep 2008) Log Message: ----------- added mako vim support Modified Paths: -------------- configs/trunk/src/vim/syntax/mako.vim Added Paths: ----------- configs/trunk/src/vim/ftdetect/mako.vim Added: configs/trunk/src/vim/ftdetect/mako.vim =================================================================== --- configs/trunk/src/vim/ftdetect/mako.vim (rev 0) +++ configs/trunk/src/vim/ftdetect/mako.vim 2008-09-11 07:11:12 UTC (rev 963) @@ -0,0 +1 @@ +au BufRead,BufNewFile *.mako set filetype=mako Modified: configs/trunk/src/vim/syntax/mako.vim =================================================================== --- configs/trunk/src/vim/syntax/mako.vim 2008-09-11 07:08:52 UTC (rev 962) +++ configs/trunk/src/vim/syntax/mako.vim 2008-09-11 07:11:12 UTC (rev 963) @@ -80,4 +80,4 @@ delc HiLink endif -let b:current_syntax = "eruby" +let b:current_syntax = "mako" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-12-03 18:52:46
|
Revision: 1089 http://assorted.svn.sourceforge.net/assorted/?rev=1089&view=rev Author: yangzhang Date: 2008-12-03 18:52:39 +0000 (Wed, 03 Dec 2008) Log Message: ----------- added syntax files: thrift, proto, pandoc, javafx Modified Paths: -------------- configs/trunk/src/vim/plugin/_yang.vim Added Paths: ----------- configs/trunk/src/vim/ftplugin/proto.vim configs/trunk/src/vim/syntax/fx.vim configs/trunk/src/vim/syntax/pdc.vim configs/trunk/src/vim/syntax/proto.vim configs/trunk/src/vim/syntax/thrift.vim Added: configs/trunk/src/vim/ftplugin/proto.vim =================================================================== --- configs/trunk/src/vim/ftplugin/proto.vim (rev 0) +++ configs/trunk/src/vim/ftplugin/proto.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -0,0 +1,4 @@ +augroup filetype + au BufRead,BufNewFile *.proto setfiletype proto +augroup end + Modified: configs/trunk/src/vim/plugin/_yang.vim =================================================================== --- configs/trunk/src/vim/plugin/_yang.vim 2008-12-03 18:39:47 UTC (rev 1088) +++ configs/trunk/src/vim/plugin/_yang.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -186,6 +186,12 @@ au BufWritePost *.bin set nomod | endif augroup END +augroup filetype + au BufRead,BufNewFile *.proto setf proto + au BufRead,BufNewFile *.thrift set ft=thrift + au BufRead,BufNewFile *.pandoc setf pdc +augroup end + au BufNewFile,BufRead *.fx setf fx " Java/Eclim "au BufNewFile,BufRead *.java iunmap <tab> Added: configs/trunk/src/vim/syntax/fx.vim =================================================================== --- configs/trunk/src/vim/syntax/fx.vim (rev 0) +++ configs/trunk/src/vim/syntax/fx.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -0,0 +1,90 @@ +" Vim syntax file +" Language: JavaFX Script +" Maintainer: Yang Zhang <com.gmail@yaaang> +" URL: http://assorted.sf.net/jfx-vim +" Last Change: 2007 Jun 03 + +" Quit when a syntax file was already loaded +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +syn case match +syn sync minlines=50 + +" most JFX keywords +syn keyword jfxKeyword after as before bind class else extends first for foreach from if in into last new on private protected return select switch super then trigger var where while insert delete +syn keyword jfxImport import nextgroup=scalaFqn skipwhite +syn match jfxFqn "\<[._$a-zA-Z0-9,*]*" contained nextgroup=jfxFqnSet + +" booleans +syn keyword jfxBoolean true false + +" null +syn keyword jfxNull null + +" package and import statements +syn keyword jfxPackage package nextgroup=jfxFqn skipwhite +syn keyword jfxImport import nextgroup=jfxFqn skipwhite +syn match jfxFqn "\<[._$a-zA-Z0-9,]*" contained + +"" type declarations in val/var/def +syn match jfxType ":\s*[._$a-zA-Z0-9]\+[+*?]\?" contained +":\s*\(=>\s*\)\?[._$a-zA-Z0-9]\+\(\[[^]]*\]\+\)\?\(\s*\(<:\|>:\|#\|=>\)\s*[._$a-zA-Z0-9]\+\(\[[^]]*\]\+\)*\)*"ms=s+1 contained + +" definitions +syn keyword jfxDef function operation nextgroup=jfxDefName skipwhite +syn keyword jfxVar var nextgroup=jfxVarName skipwhite +syn keyword jfxClass class nextgroup=jfxClassName skipwhite +syn keyword jfxAttribute attribute nextgroup=jfxAttributeName skipwhite +syn match jfxAttributeName "[^ =:;([]\+" contained nextgroup=jfxType skipwhite +syn match jfxDefName "[^ =:;([]\+" contained nextgroup=jfxDefArgs nextgroup=jfxType skipwhite +syn match jfxVarName "[^ =:;([]\+" contained nextgroup=jfxType skipwhite +syn match jfxClassName "[^ =:;(\[]\+" contained skipwhite +syn region jfxDefArgs start="(" end=")" contained contains=jfxDefArg skipwhite +" TODO fixme +"syn match jfxDefArg "[^ =:;([]\+" contained nextgroup=jfxType skipwhite + +" comments +syn match jfxTodo "[tT][oO][dD][oO]\|[xX][xX][xX]" contained +syn match jfxLineComment "//.*" contains=jfxTodo +syn region jfxComment start="/\*" end="\*/" contains=jfxTodo + +" string literals with escapes +syn region jfxString start="\"" skip="\\\"" end="\"" contains=jfxStringEscape " TODO end \n or not? +syn match jfxStringEscape "\\u[0-9a-fA-F]\{4}" contained +syn match jfxStringEscape "\\[nrfvb\\\"]" contained +syn match jfxString "'[_a-zA-Z][_a-zA-Z0-9]*\>" +syn match jfxString "'[^'\\]'\|'\\.'" + +" number literals +syn match jfxNumber "\<\(0[0-7]*\|0[xX]\x\+\|\d\+\)[lL]\=\>" +syn match jfxNumber "\(\<\d\+\.\d*\|\.\d\+\)\([eE][-+]\=\d\+\)\=[fFdD]\=" +syn match jfxNumber "\<\d\+[eE][-+]\=\d\+[fFdD]\=\>" +syn match jfxNumber "\<\d\+\([eE][-+]\=\d\+\)\=[fFdD]\>" + +syn sync fromstart + +hi link jfxAttribute StorageClass +hi link jfxKeyword Keyword +hi link jfxPackage Include +hi link jfxImport Include +hi link jfxBoolean Boolean +hi link jfxNull Constant +hi link jfxNumber Number +hi link jfxString String +hi link jfxStringEscape Special +hi link jfxComment Comment +hi link jfxLineComment Comment +hi link jfxTodo Todo +hi link jfxDef Keyword +hi link jfxVar Keyword +hi link jfxClass Keyword +hi link jfxDefName Function +hi link jfxDefSpecializer Function +hi link jfxClassName Special +hi link jfxType Type + +let b:current_syntax = "jfx" Added: configs/trunk/src/vim/syntax/pdc.vim =================================================================== --- configs/trunk/src/vim/syntax/pdc.vim (rev 0) +++ configs/trunk/src/vim/syntax/pdc.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -0,0 +1,330 @@ +" Vim syntax file +" Language: Pandoc (superset of Markdown) +" Maintainer: Jeremy Schultz <ta...@gm...> +" URL: +" Version: 2 +" Changes: 2008-11-04 +" - Fixed an issue with Block elements (header) not being highlighted when +" placed on the first or second line of the file +" - Fixed multi line HTML comment block +" - Fixed lowercase list items +" - Fixed list items gobbling to many empty lines +" - Added highlight support to identify newline (2 spaces) +" - Fixed HTML highlight, ignore if the first character in the +" angle brackets is not a letter +" - Fixed Emphasis highlighting when it contained multiple +" spaces +" Remark: Uses HTML and TeX syntax file + +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +syn spell toplevel +syn case ignore +syn sync linebreaks=1 + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Set embedded HTML highlighting +syn include @HTML syntax/html.vim +syn match pdcHTML /<\a[^>]\+>/ contains=@HTML + +" Support HTML multi line comments +syn region pdcHTMLComment start=/<!--/ end=/-->/ + + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Set embedded LaTex (pandox extension) highlighting +" Unset current_syntax so the 2nd include will work +unlet b:current_syntax +syn include @LATEX syntax/tex.vim + +" Single Tex command +syn match pdcLatex /\\\w\+{[^}]\+}/ contains=@LATEX + +" Tex Block (begin-end) +syn region pdcLatex start=/\\begin{[^}]\+}\ze/ end=/\ze\\end{[^}]\+}/ contains=@LATEX + +" Math Tex +syn match pdcLatex /$[^$]\+\$/ contains=@LATEX + + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Block Elements +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" + +" Needed by other elements +syn match pdcBlankLine /\(^\s*\n\|\%^\)/ nextgroup=pdcHeader,pdcCodeBlock,pdcListItem,pdcListItem1,pdcHRule,pdcTableHeader,pdcTableMultiStart,pdcBlockquote transparent + + +""""""""""""""""""""""""""""""""""""""" +" Title Block: +syn match pandocTitleBlock /\%^\(%.*\n\)\{1,3}$/ + + +""""""""""""""""""""""""""""""""""""""" +" Headers: + +" Underlined, using == or -- +syn match pdcHeader /^.\+\n[=-]\+$/ contains=@Spell nextgroup=pdcHeader contained skipnl + +" Atx-style, Hash marks +syn region pdcHeader start="^\s*#\{1,6}[^#]*" end="\($\|#\+\)" contains=@Spell contained nextgroup=pdcHeader skipnl + + +""""""""""""""""""""""""""""""""""""""" +" Blockquotes: + +syn match pdcBlockquote /\s*>.*$/ nextgroup=pdcBlockquote,pdcBlockquote2 contained skipnl +syn match pdcBlockquote2 /[^>].*/ nextgroup=pdcBlockquote2 skipnl contained + + +""""""""""""""""""""""""""""""""""""""" +" Code Blocks: + +" Indent with at least 4 space or 1 tab +" This rule must appear for pdcListItem, or highlighting gets messed up +syn match pdcCodeBlock /\(\s\{2,}\|\t\{1,}\).*\n/ contained nextgroup=pdcCodeBlock + +" HTML code blocks, pre and code +syn match pdcCodeStartPre /<pre>/ nextgroup=pdcCodeHTMLPre skipnl transparent +syn match pdcCodeHTMLPre /.*/ contained nextgroup=pdcCodeHTMLPre,pdcCodeEndPre skipnl +syn match pdcCodeEndPre /\s*<\/pre>/ contained transparent + +" HTML code blocks, code +syn match pdcCodeStartCode /<code>/ nextgroup=pdcCodeHTMLCode skipnl transparent +syn match pdcCodeHTMLCode /.*/ contained nextgroup=pdcCodeHTMLCode,pdcCodeEndCode skipnl +syn match pdcCodeEndCode /\s*<\/code>/ contained transparent + + +""""""""""""""""""""""""""""""""""""""" +" Lists: + +" These first two rules need to be first or the highlighting will be +" incorrect + +" Continue a list on the next line +syn match pdcListCont /\s*[^-+*].*\n/ contained nextgroup=pdcListCont,pdcListItem,pdcListSkipNL transparent + +" Skip empty lines +syn match pdcListSkipNL /\s*\n/ contained nextgroup=pdcListItem,pdcListSkipNL + +" Unorder list +syn match pdcListItem /\s*[-*+]\s\+/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + +" Order list, numeric +syn match pdcListItem /\s*(\?\(\d\+\|#\)[\.)]\s\+/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + +" Order list, roman numerals (does not guarantee correct roman numerals) +syn match pdcListItem /\s*(\?[ivxlcdm]\+[\.)]\s\+/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + +" Order list, lowercase letters +syn match pdcListItem /\s*(\?\l[\.)]\s\+/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + +" Order list, uppercase letters, does not include '.' +syn match pdcListItem /\s*(\?\u[\)]\s\+/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + +" Order list, uppercase letters, special case using '.' and two or more spaces +syn match pdcListItem /\s*\u\.\([ ]\{2,}\|\t\+\)/ contained nextgroup=pdcListSkipNL,pdcListCont skipnl + + +""""""""""""""""""""""""""""""""""""""" +" Horizontal Rules: + +" 3 or more * on a line +syn match pdcHRule /\s\{0,3}\(-\s*\)\{3,}\n/ contained nextgroup=pdcHRule + +" 3 or more - on a line +syn match pdcHRule /\s\{0,3}\(\*\s*\)\{3,}\n/ contained nextgroup=pdcHRule + + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Span Elements +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" + +""""""""""""""""""""""""""""""""""""""" +" Links: + +" Link Text +syn match pdcLinkText /\[\zs[^\]]*\ze\]/ contains=@Spell + +" Link ID +syn match pdcLinkID /\][ ]\{0,1}\[\zs[^\]]*\ze\]/ + +" Skip [ so we do not highlight it +syn match pdcSkip /^[ ]\{0,3}\[/ nextgroup=pdcLinkID + +" Link ID - definition +syn match pdcLinkID /[^\]]*\ze\]:/ nextgroup=pdcSkip skipwhite contained + +" Skip ]: so we do not highlight it +syn match pdcSkip /\]:/ contained nextgroup=pdcLinkURL skipwhite + +" Link URL +syn region pdcLinkURL start=/\](\zs/ end=/)/me=e-1 + +" Link URL on ID definition line +syn match pdcLinkURL /\s\+.*\s\+\ze[("']/ nextgroup=pdcLinkTitle skipwhite contained +syn match pdcLinkURL /\s*.*\s*[^)"']\s*$/ contained +syn match pdcLinkURL /\s*.*\s*[^)"']\s*\n\s*\ze[("']/ contained nextgroup=pdcLinkTitle skipwhite + +" Link URL for inline <> links +syn match pdcLinkURL /<http[^>]*>/ +syn match pdcLinkURL /<[^>]*@[^>]*.[^>]*>/ + +" Link Title +syn match pdcLinkTitle /\s*[("'].*[)"']/ contained contains=@Spell + + +""""""""""""""""""""""""""""""""""""""" +" Emphasis: + +" Using underscores +syn match pdcEmphasis / \(_\|__\)\([^_ ]\|[^_]\( [^_]\)\+\)\+\1/ contains=@Spell + +" Using Asterisks +syn match pdcEmphasis / \(\*\|\*\*\)\([^\* ]\|[^\*]\( [^\*]\)\+\)\+\1/ contains=@Spell + + +""""""""""""""""""""""""""""""""""""""" +" Inline Code: + +" Using single back ticks +syn region pdcCode start=/`/ end=/`\|^\s*$/ + +" Using double back ticks +syn region pdcCode start=/``[^`]*/ end=/``\|^\s*$/ + + +""""""""""""""""""""""""""""""""""""""" +" Images: +" Handled by link syntax + + +""""""""""""""""""""""""""""""""""""""" +" Misc: + +" Pandoc escapes all characters after a backslash +syn match NONE /\\\W/ + + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Span Elements +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" + +""""""""""""""""""""""""""""""""""""""" +" Subscripts: +syn match pdcSubscript /\~\([^\~\\ ]\|\(\\ \)\)\+\~/ contains=@Spell + +""""""""""""""""""""""""""""""""""""""" +" Superscript: +syn match pdcSuperscript /\^\([^\^\\ ]\|\(\\ \)\)\+\^/ contains=@Spell + +""""""""""""""""""""""""""""""""""""""" +" Strikeout: +syn match pdcStrikeout /\~\~[^\~ ]\([^\~]\|\~ \)*\~\~/ contains=@Spell + + +""""""""""""""""""""""""""""""""""""""" +" Definitions: +syn match pdcDefinitions /:\(\t\|[ ]\{3,}\)/ nextgroup=pdcListItem,pdcCodeBlock,pdcBlockquote,pdcHRule + +""""""""""""""""""""""""""""""""""""""" +" Footnote: +syn match pdcFootnoteID /\[\^[^\]]\+\]/ nextgroup=pdcFootnoteDef + +" This does not work correctly +syn region pdcFootnoteDef start=/:/ end=/^\n\+\(\(\t\+\|[ ]\{4,}\)\S\)\@!/ contained contains=pdcFootnoteDef + +" Inline footnotes +syn region pdcFootnoteDef matchgroup=pdcFootnoteID start=/\^\[/ matchgroup=pdcFootnoteID end=/\]/ + + +""""""""""""""""""""""""""""""""""""""" +" Tables: +" +" Regular Table +syn match pdcTableHeader /\s*\w\+\(\s\+\w\+\)\+\s*\n\s*-\+\(\s\+-\+\)\+\s*\n/ contained nextgroup=pdcTableBody +syn match pdcTableBody /\s*\w\+\(\s\+\w\+\)\+\s*\n/ contained nextgroup=pdcTableBody,pdcTableCaption skipnl +syn match pdcTableCaption /\n\+\s*Table.*\n/ contained nextgroup=pdcTableCaptionCont +syn match pdcTableCaptionCont /\s*\S.\+\n/ contained nextgroup=pdcTableCaptionCont + +" Multi-line Table +syn match pdcTableMultiStart /^\s\{0,3}-\+\s*\n\ze\(\s*\w\+\(\s\+\w\+\)\+\s*\n\)\+\s*-\+\(\s\+-\+\)\+\s*\n/ contained nextgroup=pdcTableMultiHeader +syn match pdcTableMultiEnd /^\s\{0,3}-\+/ contained nextgroup=pdcTableMultiCaption skipnl +syn match pdcTableMultiHeader /\(\s*\w\+\(\s\+\w\+\)\+\s*\n\)\+\s*-\+\(\s\+-\+\)\+\s*\n/ contained nextgroup=pdcTableMultiBody +syn match pdcTableMultiBody /^\(\s\{3,}[^-]\|[^-\s]\).*$/ contained nextgroup=pdcTableMultiBody,pdcTableMultiSkipNL,pdcTableMultiEnd skipnl +syn match pdcTableMultiSkipNL /^\s*\n/ contained nextgroup=pdcTableMultiBody,pdcTableMultiEnd skipnl +syn match pdcTableMultiCaption /\n*\s*Table.*\n/ contained nextgroup=pdcTableCaptionCont + + + +""""""""""""""""""""""""""""""""""""""" +" Delimited Code Block: (added in 1.0) +syn region pdcCodeBlock matchgroup=pdcCodeStart start=/^\z(\~\{3,}\) \( {[^}]\+}\)\?/ matchgroup=pdcCodeEnd end=/^\z1\~*/ + + +""""""""""""""""""""""""""""""""""""""" +" Newline, 2 spaces at the end of line means newline +syn match pdcNewLine / $/ + + +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Highlight groups +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +hi link pdcHeader Title +hi link pdcBlockquote Comment +hi link pdcBlockquote2 Comment + +hi link pdcHTMLComment Comment + +hi link pdcHRule Underlined +"hi link pdcHRule Special + +hi link pdcListItem Operator +hi link pdcDefinitions Operator + +hi link pdcEmphasis Special +hi link pdcSubscript Special +hi link pdcSuperscript Special +hi link pdcStrikeout Special + +hi link pdcLinkText Underlined +hi link pdcLinkID Identifier +hi link pdcLinkURL Type +hi link pdcLinkTitle Comment + +hi link pdcFootnoteID Identifier +hi link pdcFootnoteDef Comment +hi link pandocFootnoteCont Error + +hi link pdcCodeBlock String +hi link pdcCodeHTMLPre String +hi link pdcCodeHTMLCode String +hi link pdcCode String +hi link pdcCodeStart Comment +hi link pdcCodeEnd Comment + +hi link pandocTitleBlock Comment + +hi link pdcTableMultiStart Comment +hi link pdcTableMultiEnd Comment +hi link pdcTableHeader Define +hi link pdcTableMultiHeader Define +hi link pdcTableBody Identifier +hi link pdcTableMultiBody Identifier +hi link pdcTableCaption Label +hi link pdcTableMultiCaption Label +hi link pdcTableCaptionCont Label + +hi link pdcNewLine Error + + +" For testing +hi link pdctest Error + + +let b:current_syntax = "pandoc" + Added: configs/trunk/src/vim/syntax/proto.vim =================================================================== --- configs/trunk/src/vim/syntax/proto.vim (rev 0) +++ configs/trunk/src/vim/syntax/proto.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -0,0 +1,106 @@ +" Protocol Buffers - Google's data interchange format +" Copyright 2008 Google Inc. All rights reserved. +" http://code.google.com/p/protobuf/ +" +" 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. +" * Neither the name of Google Inc. nor the names of its +" contributors may be used to endorse or promote products derived from +" this software without specific prior written permission. +" +" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +" LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +" A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +" OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +" LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +" OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +" This is the Vim syntax file for Google Protocol Buffers. +" +" Usage: +" +" 1. cp proto.vim ~/.vim/syntax/ +" 2. Add the following to ~/.vimrc: +" +" augroup filetype +" au! BufRead,BufNewFile *.proto setfiletype proto +" augroup end +" +" Or just create a new file called ~/.vim/ftdetect/proto.vim with the +" previous lines on it. + +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +syn case match + +syn keyword pbTodo contained TODO FIXME XXX +syn cluster pbCommentGrp contains=pbTodo + +syn keyword pbSyntax syntax import option +syn keyword pbStructure package message group +syn keyword pbRepeat optional required repeated +syn keyword pbDefault default +syn keyword pbExtend extend extensions to max +syn keyword pbRPC service rpc returns + +syn keyword pbType int32 int64 uint32 uint64 sint32 sint64 +syn keyword pbType fixed32 fixed64 sfixed32 sfixed64 +syn keyword pbType float double bool string bytes +syn keyword pbTypedef enum +syn keyword pbBool true false + +syn match pbInt /-\?\<\d\+\>/ +syn match pbInt /\<0[xX]\x+\>/ +syn match pbFloat /\<-\?\d*\(\.\d*\)\?/ +" TODO: .proto also supports C-style block comments; +" see /usr/share/vim/vim70/syntax/c.vim for how it's done. +syn region pbComment start="//" skip="\\$" end="$" keepend contains=@pbCommentGrp +syn region pbString start=/"/ skip=/\\"/ end=/"/ +syn region pbString start=/'/ skip=/\\'/ end=/'/ + +if version >= 508 || !exists("did_proto_syn_inits") + if version < 508 + let did_proto_syn_inits = 1 + command -nargs=+ HiLink hi link <args> + else + command -nargs=+ HiLink hi def link <args> + endif + + HiLink pbTodo Todo + + HiLink pbSyntax Include + HiLink pbStructure Structure + HiLink pbRepeat Repeat + HiLink pbDefault Keyword + HiLink pbExtend Keyword + HiLink pbRPC Keyword + HiLink pbType Type + HiLink pbTypedef Typedef + HiLink pbBool Boolean + + HiLink pbInt Number + HiLink pbFloat Float + HiLink pbComment Comment + HiLink pbString String + + delcommand HiLink +endif + +let b:current_syntax = "proto" Added: configs/trunk/src/vim/syntax/thrift.vim =================================================================== --- configs/trunk/src/vim/syntax/thrift.vim (rev 0) +++ configs/trunk/src/vim/syntax/thrift.vim 2008-12-03 18:52:39 UTC (rev 1089) @@ -0,0 +1,74 @@ +" Vim syntax file +" Language: Thrift +" Maintainer: Martin Smith <ma...@fa...> +" Last Change: $Date: $ +" Copy to ~/.vim/ +" Add to ~/.vimrc +" au BufRead,BufNewFile *.thrift set filetype=thrift +" au! Syntax thrift source ~/.vim/thrift.vim +" +" $Id: $ + +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +" Todo +syn keyword thriftTodo TODO todo FIXME fixme XXX xxx contained + +" Comments +syn match thriftComment "#.*" contains=thriftTodo +syn region thriftComment start="/\*" end="\*/" contains=thriftTodo +syn match thriftComment "//.\{-}\(?>\|$\)\@=" + +" String +syn region thriftStringDouble matchgroup=None start=+"+ end=+"+ + +" Number +syn match thriftNumber "-\=\<\d\+\>" contained + +" Keywords +syn keyword thriftKeyword namespace +syn keyword thriftKeyword php_namespace +syn keyword thriftKeyword xsd_all xsd_optional xsd_nillable xsd_namespace xsd_attrs +syn keyword thriftKeyword include cpp_include cpp_type const optional required +syn keyword thriftBasicTypes void bool byte i16 i32 i64 double string binary +syn keyword thriftStructure map list set struct typedef exception enum throws + +" Special +syn match thriftSpecial "\d\+:" + +" Structure +syn keyword thriftStructure service async extends +"async" { return tok_async; } +"exception" { return tok_xception; } +"extends" { return tok_extends; } +"throws" { return tok_throws; } +"service" { return tok_service; } +"enum" { return tok_enum; } +"const" { return tok_const; } + +if version >= 508 || !exists("did_thrift_syn_inits") + if version < 508 + let did_thrift_syn_inits = 1 + command! -nargs=+ HiLink hi link <args> + else + command! -nargs=+ HiLink hi def link <args> + endif + + HiLink thriftComment Comment + HiLink thriftKeyword Special + HiLink thriftBasicTypes Type + HiLink thriftStructure StorageClass + HiLink thriftTodo Todo + HiLink thriftString String + HiLink thriftNumber Number + HiLink thriftSpecial Special + HiLink thriftStructure Structure + + delcommand HiLink +endif + +let b:current_syntax = "thrift" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-10-12 02:21:46
|
Revision: 1481 http://assorted.svn.sourceforge.net/assorted/?rev=1481&view=rev Author: yangzhang Date: 2009-10-12 02:21:32 +0000 (Mon, 12 Oct 2009) Log Message: ----------- tweaks to make things work again under windows; using new ir_black color scheme Modified Paths: -------------- configs/trunk/src/vim/plugin/_yang.vim configs/trunk/src/vim/plugin/mru.vim Added Paths: ----------- configs/trunk/src/vim/colors/ir_black.vim Added: configs/trunk/src/vim/colors/ir_black.vim =================================================================== --- configs/trunk/src/vim/colors/ir_black.vim (rev 0) +++ configs/trunk/src/vim/colors/ir_black.vim 2009-10-12 02:21:32 UTC (rev 1481) @@ -0,0 +1,212 @@ +" ir_black color scheme +" More at: http://blog.infinitered.com/entries/show/8 + + +" ******************************************************************************** +" Standard colors used in all ir_black themes: +" Note, x:x:x are RGB values +" +" normal: #f6f3e8 +" +" string: #A8FF60 168:255:96 +" string inner (punc, code, etc): #00A0A0 0:160:160 +" number: #FF73FD 255:115:253 +" comments: #7C7C7C 124:124:124 +" keywords: #96CBFE 150:203:254 +" operators: white +" class: #FFFFB6 255:255:182 +" method declaration name: #FFD2A7 255:210:167 +" regular expression: #E9C062 233:192:98 +" regexp alternate: #FF8000 255:128:0 +" regexp alternate 2: #B18A3D 177:138:61 +" variable: #C6C5FE 198:197:254 +" +" Misc colors: +" red color (used for whatever): #FF6C60 255:108:96 +" light red: #FFB6B0 255:182:176 +" +" brown: #E18964 good for special +" +" lightpurpleish: #FFCCFF +" +" Interface colors: +" background color: black +" cursor (where underscore is used): #FFA560 255:165:96 +" cursor (where block is used): white +" visual selection: #1D1E2C +" current line: #151515 21:21:21 +" search selection: #07281C 7:40:28 +" line number: #3D3D3D 61:61:61 + + +" ******************************************************************************** +" The following are the preferred 16 colors for your terminal +" Colors Bright Colors +" Black #4E4E4E #7C7C7C +" Red #FF6C60 #FFB6B0 +" Green #A8FF60 #CEFFAB +" Yellow #FFFFB6 #FFFFCB +" Blue #96CBFE #FFFFCB +" Magenta #FF73FD #FF9CFE +" Cyan #C6C5FE #DFDFFE +" White #EEEEEE #FFFFFF + + +" ******************************************************************************** +set background=dark +hi clear + +if exists("syntax_on") + syntax reset +endif + +let colors_name = "ir_black" + + +"hi Example guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE + +" General colors +hi Normal guifg=#f6f3e8 guibg=black gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE +hi NonText guifg=#070707 guibg=black gui=NONE ctermfg=black ctermbg=NONE cterm=NONE + +hi Cursor guifg=black guibg=white gui=NONE ctermfg=black ctermbg=white cterm=reverse +hi LineNr guifg=#3D3D3D guibg=black gui=NONE ctermfg=darkgray ctermbg=NONE cterm=NONE + +hi VertSplit guifg=#202020 guibg=#202020 gui=NONE ctermfg=darkgray ctermbg=darkgray cterm=NONE +hi StatusLine guifg=#CCCCCC guibg=#202020 gui=italic ctermfg=white ctermbg=darkgray cterm=NONE +hi StatusLineNC guifg=black guibg=#202020 gui=NONE ctermfg=blue ctermbg=darkgray cterm=NONE + +hi Folded guifg=#a0a8b0 guibg=#384048 gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE +hi Title guifg=#f6f3e8 guibg=NONE gui=bold ctermfg=NONE ctermbg=NONE cterm=NONE +hi Visual guifg=NONE guibg=#262D51 gui=NONE ctermfg=NONE ctermbg=darkgray cterm=NONE + +hi SpecialKey guifg=#808080 guibg=#343434 gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE + +hi WildMenu guifg=green guibg=yellow gui=NONE ctermfg=black ctermbg=yellow cterm=NONE +hi PmenuSbar guifg=black guibg=white gui=NONE ctermfg=black ctermbg=white cterm=NONE +"hi Ignore guifg=gray guibg=black gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE + +hi Error guifg=NONE guibg=NONE gui=undercurl ctermfg=white ctermbg=red cterm=NONE guisp=#FF6C60 " undercurl color +hi ErrorMsg guifg=white guibg=#FF6C60 gui=BOLD ctermfg=white ctermbg=red cterm=NONE +hi WarningMsg guifg=white guibg=#FF6C60 gui=BOLD ctermfg=white ctermbg=red cterm=NONE + +" Message displayed in lower left, such as --INSERT-- +hi ModeMsg guifg=black guibg=#C6C5FE gui=BOLD ctermfg=black ctermbg=cyan cterm=BOLD + +if version >= 700 " Vim 7.x specific colors + hi CursorLine guifg=NONE guibg=#121212 gui=NONE ctermfg=NONE ctermbg=NONE cterm=BOLD + hi CursorColumn guifg=NONE guibg=#121212 gui=NONE ctermfg=NONE ctermbg=NONE cterm=BOLD + hi MatchParen guifg=#f6f3e8 guibg=#857b6f gui=BOLD ctermfg=white ctermbg=darkgray cterm=NONE + hi Pmenu guifg=#f6f3e8 guibg=#444444 gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE + hi PmenuSel guifg=#000000 guibg=#cae682 gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE + hi Search guifg=NONE guibg=NONE gui=underline ctermfg=NONE ctermbg=NONE cterm=underline +endif + +" Syntax highlighting +hi Comment guifg=#7C7C7C guibg=NONE gui=NONE ctermfg=darkgray ctermbg=NONE cterm=NONE +hi String guifg=#A8FF60 guibg=NONE gui=NONE ctermfg=green ctermbg=NONE cterm=NONE +hi Number guifg=#FF73FD guibg=NONE gui=NONE ctermfg=magenta ctermbg=NONE cterm=NONE + +hi Keyword guifg=#96CBFE guibg=NONE gui=NONE ctermfg=blue ctermbg=NONE cterm=NONE +hi PreProc guifg=#96CBFE guibg=NONE gui=NONE ctermfg=blue ctermbg=NONE cterm=NONE +hi Conditional guifg=#6699CC guibg=NONE gui=NONE ctermfg=blue ctermbg=NONE cterm=NONE " if else end + +hi Todo guifg=#8f8f8f guibg=NONE gui=NONE ctermfg=red ctermbg=NONE cterm=NONE +hi Constant guifg=#99CC99 guibg=NONE gui=NONE ctermfg=cyan ctermbg=NONE cterm=NONE + +hi Identifier guifg=#C6C5FE guibg=NONE gui=NONE ctermfg=cyan ctermbg=NONE cterm=NONE +hi Function guifg=#FFD2A7 guibg=NONE gui=NONE ctermfg=brown ctermbg=NONE cterm=NONE +hi Type guifg=#FFFFB6 guibg=NONE gui=NONE ctermfg=yellow ctermbg=NONE cterm=NONE +hi Statement guifg=#6699CC guibg=NONE gui=NONE ctermfg=lightblue ctermbg=NONE cterm=NONE + +hi Special guifg=#E18964 guibg=NONE gui=NONE ctermfg=white ctermbg=NONE cterm=NONE +hi Delimiter guifg=#00A0A0 guibg=NONE gui=NONE ctermfg=cyan ctermbg=NONE cterm=NONE +hi Operator guifg=white guibg=NONE gui=NONE ctermfg=white ctermbg=NONE cterm=NONE + +hi link Character Constant +hi link Boolean Constant +hi link Float Number +hi link Repeat Statement +hi link Label Statement +hi link Exception Statement +hi link Include PreProc +hi link Define PreProc +hi link Macro PreProc +hi link PreCondit PreProc +hi link StorageClass Type +hi link Structure Type +hi link Typedef Type +hi link Tag Special +hi link SpecialChar Special +hi link SpecialComment Special +hi link Debug Special + + +" Special for Ruby +hi rubyRegexp guifg=#B18A3D guibg=NONE gui=NONE ctermfg=brown ctermbg=NONE cterm=NONE +hi rubyRegexpDelimiter guifg=#FF8000 guibg=NONE gui=NONE ctermfg=brown ctermbg=NONE cterm=NONE +hi rubyEscape guifg=white guibg=NONE gui=NONE ctermfg=cyan ctermbg=NONE cterm=NONE +hi rubyInterpolationDelimiter guifg=#00A0A0 guibg=NONE gui=NONE ctermfg=blue ctermbg=NONE cterm=NONE +hi rubyControl guifg=#6699CC guibg=NONE gui=NONE ctermfg=blue ctermbg=NONE cterm=NONE "and break, etc +"hi rubyGlobalVariable guifg=#FFCCFF guibg=NONE gui=NONE ctermfg=lightblue ctermbg=NONE cterm=NONE "yield +hi rubyStringDelimiter guifg=#336633 guibg=NONE gui=NONE ctermfg=lightgreen ctermbg=NONE cterm=NONE +"rubyInclude +"rubySharpBang +"rubyAccess +"rubyPredefinedVariable +"rubyBoolean +"rubyClassVariable +"rubyBeginEnd +"rubyRepeatModifier +"hi link rubyArrayDelimiter Special " [ , , ] +"rubyCurlyBlock { , , } + +hi link rubyClass Keyword +hi link rubyModule Keyword +hi link rubyKeyword Keyword +hi link rubyOperator Operator +hi link rubyIdentifier Identifier +hi link rubyInstanceVariable Identifier +hi link rubyGlobalVariable Identifier +hi link rubyClassVariable Identifier +hi link rubyConstant Type + + +" Special for Java +" hi link javaClassDecl Type +hi link javaScopeDecl Identifier +hi link javaCommentTitle javaDocSeeTag +hi link javaDocTags javaDocSeeTag +hi link javaDocParam javaDocSeeTag +hi link javaDocSeeTagParam javaDocSeeTag + +hi javaDocSeeTag guifg=#CCCCCC guibg=NONE gui=NONE ctermfg=darkgray ctermbg=NONE cterm=NONE +hi javaDocSeeTag guifg=#CCCCCC guibg=NONE gui=NONE ctermfg=darkgray ctermbg=NONE cterm=NONE +"hi javaClassDecl guifg=#CCFFCC guibg=NONE gui=NONE ctermfg=white ctermbg=NONE cterm=NONE + + +" Special for XML +hi link xmlTag Keyword +hi link xmlTagName Conditional +hi link xmlEndTag Identifier + + +" Special for HTML +hi link htmlTag Keyword +hi link htmlTagName Conditional +hi link htmlEndTag Identifier + + +" Special for Javascript +hi link javaScriptNumber Number + + +" Special for Python +"hi link pythonEscape Keyword + + +" Special for CSharp +hi link csXmlTag Keyword + + +" Special for PHP Modified: configs/trunk/src/vim/plugin/_yang.vim =================================================================== --- configs/trunk/src/vim/plugin/_yang.vim 2009-10-10 03:37:41 UTC (rev 1480) +++ configs/trunk/src/vim/plugin/_yang.vim 2009-10-12 02:21:32 UTC (rev 1481) @@ -70,7 +70,9 @@ " XXX This doesn't work for setting options on the triggering buffer. " XXX This is highly insecure; should only allow the same things allowed in modelines. -autocmd BufNewFile,BufRead * if glob(ProjectDir() . "/.project.vim") !~ "^$" | execute "source " . ProjectDir() . "/.project.vim" | endif +if system("uname") =~ ".*Linux.*" " TODO fix this so cygwin is also accepted + autocmd BufNewFile,BufRead * if glob(ProjectDir() . "/.project.vim") !~ "^$" | execute "source " . ProjectDir() . "/.project.vim" | endif +endif @@ -108,7 +110,7 @@ set sp=>& " guifont " TODO fix the zoom resulting zoom issue (when specifying backup fonts) - set gfn=Bitstream_Vera_Sans_Mono:h14,Andale_Mono:h11 + set gfn=Consolas "set gfn=Lucida_Console:h8:cANSI " guifont "set gfn=Lucida_Console:h11 " guifont else @@ -138,7 +140,7 @@ hi User4 guibg=#000000 guifg=LightBlue gui=bold hi LineNr guibg=grey30 -colorscheme desert +colorscheme ir_black " desert syntax enable " set number " number lines Modified: configs/trunk/src/vim/plugin/mru.vim =================================================================== --- configs/trunk/src/vim/plugin/mru.vim 2009-10-10 03:37:41 UTC (rev 1480) +++ configs/trunk/src/vim/plugin/mru.vim 2009-10-12 02:21:32 UTC (rev 1481) @@ -1,7 +1,7 @@ " File: mru.vim " Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com) -" Version: 3.1 -" Last Modified: February 17, 2008 +" Version: 3.2 +" Last Modified: September 22, 2008 " " Overview " -------- @@ -47,10 +47,10 @@ " " Usage " ----- -" You can use the ":MRU" command to list all the most recently edited file -" names. The file names will be listed in a temporary Vim window. If the MRU -" window is already opened, then the MRU list displayed in the window will be -" refreshed. +" To list and edit files from the MRU list, you have to use the ":MRU" +" command. The ":MRU" command displays the MRU file list in a temporary Vim +" window. If the MRU window is already opened, then the MRU list displayed in +" the window is refreshed. " " If you are using GUI Vim, then the names of the recently edited files are " added to the "File->Recent Files" menu. You can select the name of a file @@ -99,11 +99,11 @@ " plugin. Set the following variables in your .vimrc file using the 'let' " command. " -" The list of recently edit file names is stored in the file specified by the +" The list of recently edited file names is stored in the file specified by the " MRU_File variable. The default setting for this variable is -" $HOME/.vim_mru_files for Unix systems and $VIM/_vim_mru_files for non-Unix -" systems. You can change this variable to point to a file by adding the -" following line to the .vimrc file: +" $HOME/.vim_mru_files for Unix-like systems and $USERPROFILE/_vim_mru_files +" for MS-Windows systems. You can change this variable to point to a file by +" adding the following line to the .vimrc file: " " let MRU_File = 'd:\myhome\_vim_mru_files' " @@ -126,6 +126,16 @@ " " The specified pattern should be a Vim regular expression pattern. " +" If you want to add only file names matching a set of patterns to the MRU +" list, then you can set the MRU_Include_Files variable. This variable should +" be set to a Vim regular expression pattern. For example, to add only .c and +" .h files to the MRU list, you can set this variable as below: +" +" let MRU_Include_Files = '\.c$\|\.h$' +" +" By default, MRU_Include_Files is set to an empty string and all the edited +" filenames are added to the MRU list. +" " The default height of the MRU window is 8. You can set the MRU_Window_Height " variable to change the window height. " @@ -177,6 +187,11 @@ let MRU_Exclude_Files = '' endif +" Files to include in the MRU list +if !exists('MRU_Include_Files') + let MRU_Include_Files = '' +endif + " Height of the MRU window " Default height is 8 if !exists('MRU_Window_Height') @@ -192,10 +207,16 @@ endif if !exists('MRU_File') - if has('unix') - let MRU_File = $HOME . "/.vim_mru_files" + if has('unix') || has('macunix') + let MRU_File = $HOME . '/.vim_mru_files' else - let MRU_File = $VIM . "/_vim_mru_files" + let MRU_File = $VIM . '/_vim_mru_files' + if has('win32') + " MS-Windows + if $USERPROFILE != '' + let MRU_File = $USERPROFILE . '\_vim_mru_files' + endif + endif endif endif @@ -204,19 +225,26 @@ let MRU_Add_Menu = 1 endif +" Control to temporarily lock the MRU list. Used to prevent files from +" getting added to the MRU list when the ':vimgrep' command is executed. +let s:mru_list_locked = 0 + " MRU_LoadList " Load the latest MRU file list from the MRU file function! s:MRU_LoadList() " Read the list from the MRU file. if filereadable(g:MRU_File) let s:MRU_files = readfile(g:MRU_File) - if s:MRU_files[0] =~# '^" Most recently edited files in Vim' - " Generated by the previous version of the MRU plugin. Ignore the - " list + if s:MRU_files[0] =~# '^\s*" Most recently edited files in Vim' + " Generated by the previous version of the MRU plugin. + " Discard the list. let s:MRU_files = [] elseif s:MRU_files[0] =~# '^#' " Remove the comment line call remove(s:MRU_files, 0) + else + " Unsupported format + let s:MRU_files = [] endif else let s:MRU_files = [] @@ -238,6 +266,11 @@ " MRU_AddFile " Add a file to the MRU file list function! s:MRU_AddFile(acmd_bufnr) + if s:mru_list_locked + " MRU list is currently locked + return + endif + " Get the full path to the filename let fname = fnamemodify(bufname(a:acmd_bufnr + 0), ':p') if fname == '' @@ -249,16 +282,24 @@ return endif + if g:MRU_Include_Files != '' + " If MRU_Include_Files is set, include only files matching the + " specified pattern + if fname !~# g:MRU_Include_Files + return + endif + endif + if g:MRU_Exclude_Files != '' " Do not add files matching the pattern specified in the " MRU_Exclude_Files to the MRU list - if fname =~? g:MRU_Exclude_Files + if fname =~# g:MRU_Exclude_Files return endif endif - " If the filename is already present in the MRU list, then move - " it to the beginning of the list + " If the filename is not already present in the MRU list and is not + " readable then ignore it let idx = index(s:MRU_files, fname) if idx == -1 if !filereadable(fname) @@ -276,7 +317,7 @@ " Add the new file list to the beginning of the updated old file list call insert(s:MRU_files, fname, 0) - " Return the trimmed list + " Trim the list if len(s:MRU_files) > g:MRU_Max_Entries call remove(s:MRU_files, g:MRU_Max_Entries, -1) endif @@ -299,12 +340,23 @@ endif endfunction +" Special characters in file names that should be escaped (for security +" reasons) +let s:esc_filename_chars = ' *?[{`$%#"|!<>();&' . "'\t\n" +function! s:MRU_escape_filename(fname) + return escape(a:fname, s:esc_filename_chars) +endfunction + " MRU_Edit_File " Edit the specified file -function! s:MRU_Edit_File(filename) - let fname = escape(a:filename, ' %#"') +function! s:MRU_Edit_File(filename, sanitized) + if !a:sanitized + let esc_fname = s:MRU_escape_filename(a:filename) + else + let esc_fname = a:filename + endif " If the file is already open in one of the windows, jump to it - let winnum = bufwinnr('^' . fname . '$') + let winnum = bufwinnr('^' . a:filename . '$') if winnum != -1 if winnum != winnr() exe winnum . 'wincmd w' @@ -313,9 +365,9 @@ if &modified || &buftype != '' || &previewwindow " Current buffer has unsaved changes or is a special buffer or is " the preview window. So open the file in a new window - exe 'split ' . fname + exe 'split ' . esc_fname else - exe 'edit ' . fname + exe 'edit ' . esc_fname endif endif endfunction @@ -332,11 +384,11 @@ return endif - let fname = escape(fname, ' %#"') + let esc_fname = s:MRU_escape_filename(fname) if a:win_opt == 'newwin' " Edit the file in a new window - exe 'leftabove new ' . fname + exe 'leftabove new ' . esc_fname if g:MRU_Auto_Close == 1 && g:MRU_Use_Current_Window == 0 " Go back to the MRU window and close it @@ -375,7 +427,7 @@ exe 'tabnext ' . i else " Open a new tab as the last tab page - exe '999tabnew ' . fname + exe '999tabnew ' . esc_fname endif endif @@ -427,9 +479,9 @@ if &modified || &buftype != '' || &previewwindow " Current buffer has unsaved changes or is a special buffer or " is the preview window. So open the file in a new window - exe 'split ' . fname + exe 'split ' . esc_fname else - exe 'edit ' . fname + exe 'edit ' . esc_fname endif endif endif @@ -546,11 +598,17 @@ silent! 0put =s:MRU_files else " Display only the entries matching the specified pattern - silent! 0put =filter(copy(s:MRU_files), 'v:val =~? a:1') + " First try using it as a literal pattern + let m = filter(copy(s:MRU_files), 'stridx(v:val, a:1) != -1') + if len(m) == 0 + " No match. Try using it as a regular expression + let m = filter(copy(s:MRU_files), 'v:val =~# a:1') + endif + silent! 0put =m endif " Move the cursor to the beginning of the file - exe 1 + normal! gg setlocal nomodifiable endfunction @@ -588,8 +646,21 @@ " filenames containing the string. If only one filename is found, " then edit it. let m = filter(copy(s:MRU_files), 'stridx(v:val, a:pat) != -1') - if len(m) == 1 - call s:MRU_Edit_File(m[0]) + if len(m) > 0 + if len(m) == 1 + call s:MRU_Edit_File(m[0], 0) + return + endif + + " More than one file matches. Try find an accurate match + let new_m = filter(m, 'v:val ==# a:pat') + if len(new_m) == 1 + call s:MRU_Edit_File(new_m[0], 0) + return + endif + + " Couldn't find an exact match, open the MRU window + call s:MRU_Open_Window(a:pat) return endif @@ -605,7 +676,7 @@ endif if len(m) == 1 - call s:MRU_Edit_File(m[0]) + call s:MRU_Edit_File(m[0], 0) return endif @@ -615,7 +686,9 @@ function! s:MRU_add_files_to_menu(prefix, file_list) for fname in a:file_list " Escape special characters in the filename - let esc_fname = escape(fnamemodify(fname, ':t'), ". \\|\t%#") + let esc_fname = escape(fnamemodify(fname, ':t'), ".\\" . + \ s:esc_filename_chars) + let esc_fname = substitute(esc_fname, '&', '&&', 'g') " Truncate the directory name if it is long let dir_name = fnamemodify(fname, ':h') @@ -627,11 +700,15 @@ \ '...' . \ strpart(dir_name, len - 20) endif - let esc_dir_name = escape(dir_name, ". \\|\t") + let esc_dir_name = escape(dir_name, ".\\" . s:esc_filename_chars) + let esc_dir_name = substitute(esc_dir_name, '&', '&&', 'g') - exe 'anoremenu <silent> &File.Recent\ Files.' . a:prefix . esc_fname . - \ '\ (' . esc_dir_name . ')' . - \ " :call <SID>MRU_Edit_File('" . fname . "')<CR>" + let menu_path = '&File.Recent\ Files.' . a:prefix . esc_fname . + \ '\ (' . esc_dir_name . ')' + let esc_mfname = s:MRU_escape_filename(fname) + exe 'anoremenu <silent> ' . menu_path . + \ " :call <SID>MRU_Edit_File('" . esc_mfname . "', 1)<CR>" + exe 'tmenu ' . menu_path . ' Edit file ' . esc_mfname endfor endfunction @@ -658,11 +735,14 @@ anoremenu <silent> &File.Recent\ Files.Refresh\ list \ :call <SID>MRU_LoadList()<CR> + exe 'tmenu File.Recent\ Files.Refresh\ list Reload the MRU file list from ' + \ . s:MRU_escape_filename(g:MRU_File) anoremenu File.Recent\ Files.-SEP1- : " Add the filenames in the MRU list to the menu let entry_cnt = len(s:MRU_files) if entry_cnt > 10 + " Split the MRU menu into sub-menus for start_idx in range(0, entry_cnt, 10) let last_idx = start_idx + 9 if last_idx >= entry_cnt @@ -692,6 +772,12 @@ autocmd BufNewFile * call s:MRU_AddFile(expand('<abuf>')) autocmd BufWritePost * call s:MRU_AddFile(expand('<abuf>')) +" The ':vimgrep' command adds all the files searched to the buffer list. +" This also modifies the MRU list, even though the user didn't edit the +" files. Use the following autocmds to prevent this. +autocmd QuickFixCmdPre *vimgrep* let s:mru_list_locked = 1 +autocmd QuickFixCmdPost *vimgrep* let s:mru_list_locked = 0 + " Command to open the MRU window command! -nargs=? -complete=customlist,s:MRU_Complete MRU \ call s:MRU_Cmd(<q-args>) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-01-25 03:38:54
|
Revision: 1550 http://assorted.svn.sourceforge.net/assorted/?rev=1550&view=rev Author: yangzhang Date: 2010-01-25 03:38:43 +0000 (Mon, 25 Jan 2010) Log Message: ----------- added nerdtree for vim Added Paths: ----------- configs/trunk/src/vim/doc/NERD_tree.txt configs/trunk/src/vim/nerdtree_plugin/ configs/trunk/src/vim/nerdtree_plugin/exec_menuitem.vim configs/trunk/src/vim/nerdtree_plugin/fs_menu.vim configs/trunk/src/vim/plugin/NERD_tree.vim Added: configs/trunk/src/vim/doc/NERD_tree.txt =================================================================== --- configs/trunk/src/vim/doc/NERD_tree.txt (rev 0) +++ configs/trunk/src/vim/doc/NERD_tree.txt 2010-01-25 03:38:43 UTC (rev 1550) @@ -0,0 +1,1222 @@ +*NERD_tree.txt* A tree explorer plugin that owns your momma! + + + + omg its ... ~ + + ________ ________ _ ____________ ____ __________ ____________~ + /_ __/ / / / ____/ / | / / ____/ __ \/ __ \ /_ __/ __ \/ ____/ ____/~ + / / / /_/ / __/ / |/ / __/ / /_/ / / / / / / / /_/ / __/ / __/ ~ + / / / __ / /___ / /| / /___/ _, _/ /_/ / / / / _, _/ /___/ /___ ~ + /_/ /_/ /_/_____/ /_/ |_/_____/_/ |_/_____/ /_/ /_/ |_/_____/_____/ ~ + + + Reference Manual~ + + + + +============================================================================== +CONTENTS *NERDTree-contents* + + 1.Intro...................................|NERDTree| + 2.Functionality provided..................|NERDTreeFunctionality| + 2.1.Global commands...................|NERDTreeGlobalCommands| + 2.2.Bookmarks.........................|NERDTreeBookmarks| + 2.2.1.The bookmark table..........|NERDTreeBookmarkTable| + 2.2.2.Bookmark commands...........|NERDTreeBookmarkCommands| + 2.2.3.Invalid bookmarks...........|NERDTreeInvalidBookmarks| + 2.3.NERD tree mappings................|NERDTreeMappings| + 2.4.The NERD tree menu................|NERDTreeMenu| + 3.Options.................................|NERDTreeOptions| + 3.1.Option summary....................|NERDTreeOptionSummary| + 3.2.Option details....................|NERDTreeOptionDetails| + 4.The NERD tree API.......................|NERDTreeAPI| + 4.1.Key map API.......................|NERDTreeKeymapAPI| + 4.2.Menu API..........................|NERDTreeMenuAPI| + 5.About...................................|NERDTreeAbout| + 6.Changelog...............................|NERDTreeChangelog| + 7.Credits.................................|NERDTreeCredits| + 8.License.................................|NERDTreeLicense| + +============================================================================== +1. Intro *NERDTree* + +What is this "NERD tree"?? + +The NERD tree allows you to explore your filesystem and to open files and +directories. It presents the filesystem to you in the form of a tree which you +manipulate with the keyboard and/or mouse. It also allows you to perform +simple filesystem operations. + +The following features and functionality are provided by the NERD tree: + * Files and directories are displayed in a hierarchical tree structure + * Different highlighting is provided for the following types of nodes: + * files + * directories + * sym-links + * windows .lnk files + * read-only files + * executable files + * Many (customisable) mappings are provided to manipulate the tree: + * Mappings to open/close/explore directory nodes + * Mappings to open files in new/existing windows/tabs + * Mappings to change the current root of the tree + * Mappings to navigate around the tree + * ... + * Directories and files can be bookmarked. + * Most NERD tree navigation can also be done with the mouse + * Filtering of tree content (can be toggled at runtime) + * custom file filters to prevent e.g. vim backup files being displayed + * optional displaying of hidden files (. files) + * files can be "turned off" so that only directories are displayed + * The position and size of the NERD tree window can be customised + * The order in which the nodes in the tree are listed can be customised. + * A model of your filesystem is created/maintained as you explore it. This + has several advantages: + * All filesystem information is cached and is only re-read on demand + * If you revisit a part of the tree that you left earlier in your + session, the directory nodes will be opened/closed as you left them + * The script remembers the cursor position and window position in the NERD + tree so you can toggle it off (or just close the tree window) and then + reopen it (with NERDTreeToggle) the NERD tree window will appear exactly + as you left it + * You can have a separate NERD tree for each tab, share trees across tabs, + or a mix of both. + * By default the script overrides the default file browser (netw), so if + you :edit a directory a (slighly modified) NERD tree will appear in the + current window + * A programmable menu system is provided (simulates right clicking on a + node) + * one default menu plugin is provided to perform basic filesytem + operations (create/delete/move/copy files/directories) + * There's an API for adding your own keymappings + + +============================================================================== +2. Functionality provided *NERDTreeFunctionality* + +------------------------------------------------------------------------------ +2.1. Global Commands *NERDTreeGlobalCommands* + +:NERDTree [<start-directory> | <bookmark>] *:NERDTree* + Opens a fresh NERD tree. The root of the tree depends on the argument + given. There are 3 cases: If no argument is given, the current directory + will be used. If a directory is given, that will be used. If a bookmark + name is given, the corresponding directory will be used. For example: > + :NERDTree /home/marty/vim7/src + :NERDTree foo (foo is the name of a bookmark) +< +:NERDTreeFromBookmark <bookmark> *:NERDTreeFromBookmark* + Opens a fresh NERD tree with the root initialized to the dir for + <bookmark>. This only reason to use this command over :NERDTree is for + the completion (which is for bookmarks rather than directories). + +:NERDTreeToggle [<start-directory> | <bookmark>] *:NERDTreeToggle* + If a NERD tree already exists for this tab, it is reopened and rendered + again. If no NERD tree exists for this tab then this command acts the + same as the |:NERDTree| command. + +:NERDTreeMirror *:NERDTreeMirror* + Shares an existing NERD tree, from another tab, in the current tab. + Changes made to one tree are reflected in both as they are actually the + same buffer. + + If only one other NERD tree exists, that tree is automatically mirrored. If + more than one exists, the script will ask which tree to mirror. + +:NERDTreeClose *:NERDTreeClose* + Close the NERD tree in this tab. + +:NERDTreeFind *:NERDTreeFind* + Find the current file in the tree. If no tree exists for the current tab, + or the file is not under the current root, then initialize a new tree where + the root is the directory of the current file. + +------------------------------------------------------------------------------ +2.2. Bookmarks *NERDTreeBookmarks* + +Bookmarks in the NERD tree are a way to tag files or directories of interest. +For example, you could use bookmarks to tag all of your project directories. + +------------------------------------------------------------------------------ +2.2.1. The Bookmark Table *NERDTreeBookmarkTable* + +If the bookmark table is active (see |NERDTree-B| and +|'NERDTreeShowBookmarks'|), it will be rendered above the tree. You can double +click bookmarks or use the |NERDTree-o| mapping to activate them. See also, +|NERDTree-t| and |NERDTree-T| + +------------------------------------------------------------------------------ +2.2.2. Bookmark commands *NERDTreeBookmarkCommands* + +Note that the following commands are only available in the NERD tree buffer. + +:Bookmark <name> + Bookmark the current node as <name>. If there is already a <name> + bookmark, it is overwritten. <name> must not contain spaces. + +:BookmarkToRoot <bookmark> + Make the directory corresponding to <bookmark> the new root. If a treenode + corresponding to <bookmark> is already cached somewhere in the tree then + the current tree will be used, otherwise a fresh tree will be opened. + Note that if <bookmark> points to a file then its parent will be used + instead. + +:RevealBookmark <bookmark> + If the node is cached under the current root then it will be revealed + (i.e. directory nodes above it will be opened) and the cursor will be + placed on it. + +:OpenBookmark <bookmark> + <bookmark> must point to a file. The file is opened as though |NERDTree-o| + was applied. If the node is cached under the current root then it will be + revealed and the cursor will be placed on it. + +:ClearBookmarks [<bookmarks>] + Remove all the given bookmarks. If no bookmarks are given then remove all + bookmarks on the current node. + +:ClearAllBookmarks + Remove all bookmarks. + +:ReadBookmarks + Re-read the bookmarks in the |'NERDTreeBookmarksFile'|. + +See also |:NERDTree| and |:NERDTreeFromBookmark|. + +------------------------------------------------------------------------------ +2.2.3. Invalid Bookmarks *NERDTreeInvalidBookmarks* + +If invalid bookmarks are detected, the script will issue an error message and +the invalid bookmarks will become unavailable for use. + +These bookmarks will still be stored in the bookmarks file (see +|'NERDTreeBookmarksFile'|), down the bottom. There will always be a blank line +after the valid bookmarks but before the invalid ones. + +Each line in the bookmarks file represents one bookmark. The proper format is: +<bookmark name><space><full path to the bookmark location> + +After you have corrected any invalid bookmarks, either restart vim, or go +:ReadBookmarks from the NERD tree window. + +------------------------------------------------------------------------------ +2.3. NERD tree Mappings *NERDTreeMappings* + +Default Description~ help-tag~ +Key~ + +o.......Open files, directories and bookmarks....................|NERDTree-o| +go......Open selected file, but leave cursor in the NERDTree.....|NERDTree-go| +t.......Open selected node/bookmark in a new tab.................|NERDTree-t| +T.......Same as 't' but keep the focus on the current tab........|NERDTree-T| +i.......Open selected file in a split window.....................|NERDTree-i| +gi......Same as i, but leave the cursor on the NERDTree..........|NERDTree-gi| +s.......Open selected file in a new vsplit.......................|NERDTree-s| +gs......Same as s, but leave the cursor on the NERDTree..........|NERDTree-gs| +O.......Recursively open the selected directory..................|NERDTree-O| +x.......Close the current nodes parent...........................|NERDTree-x| +X.......Recursively close all children of the current node.......|NERDTree-X| +e.......Edit the current dif.....................................|NERDTree-e| + +<CR>...............same as |NERDTree-o|. +double-click.......same as the |NERDTree-o| map. +middle-click.......same as |NERDTree-i| for files, same as + |NERDTree-e| for dirs. + +D.......Delete the current bookmark .............................|NERDTree-D| + +P.......Jump to the root node....................................|NERDTree-P| +p.......Jump to current nodes parent.............................|NERDTree-p| +K.......Jump up inside directories at the current tree depth.....|NERDTree-K| +J.......Jump down inside directories at the current tree depth...|NERDTree-J| +<C-J>...Jump down to the next sibling of the current directory...|NERDTree-C-J| +<C-K>...Jump up to the previous sibling of the current directory.|NERDTree-C-K| + +C.......Change the tree root to the selected dir.................|NERDTree-C| +u.......Move the tree root up one directory......................|NERDTree-u| +U.......Same as 'u' except the old root node is left open........|NERDTree-U| +r.......Recursively refresh the current directory................|NERDTree-r| +R.......Recursively refresh the current root.....................|NERDTree-R| +m.......Display the NERD tree menu...............................|NERDTree-m| +cd......Change the CWD to the dir of the selected node...........|NERDTree-cd| + +I.......Toggle whether hidden files displayed....................|NERDTree-I| +f.......Toggle whether the file filters are used.................|NERDTree-f| +F.......Toggle whether files are displayed.......................|NERDTree-F| +B.......Toggle whether the bookmark table is displayed...........|NERDTree-B| + +q.......Close the NERDTree window................................|NERDTree-q| +A.......Zoom (maximize/minimize) the NERDTree window.............|NERDTree-A| +?.......Toggle the display of the quick help.....................|NERDTree-?| + +------------------------------------------------------------------------------ + *NERDTree-o* +Default key: o +Map option: NERDTreeMapActivateNode +Applies to: files and directories. + +If a file node is selected, it is opened in the previous window. + +If a directory is selected it is opened or closed depending on its current +state. + +If a bookmark that links to a directory is selected then that directory +becomes the new root. + +If a bookmark that links to a file is selected then that file is opened in the +previous window. + +------------------------------------------------------------------------------ + *NERDTree-go* +Default key: go +Map option: None +Applies to: files. + +If a file node is selected, it is opened in the previous window, but the +cursor does not move. + +The key combo for this mapping is always "g" + NERDTreeMapActivateNode (see +|NERDTree-o|). + +------------------------------------------------------------------------------ + *NERDTree-t* +Default key: t +Map option: NERDTreeMapOpenInTab +Applies to: files and directories. + +Opens the selected file in a new tab. If a directory is selected, a fresh +NERD Tree for that directory is opened in a new tab. + +If a bookmark which points to a directory is selected, open a NERD tree for +that directory in a new tab. If the bookmark points to a file, open that file +in a new tab. + +------------------------------------------------------------------------------ + *NERDTree-T* +Default key: T +Map option: NERDTreeMapOpenInTabSilent +Applies to: files and directories. + +The same as |NERDTree-t| except that the focus is kept in the current tab. + +------------------------------------------------------------------------------ + *NERDTree-i* +Default key: i +Map option: NERDTreeMapOpenSplit +Applies to: files. + +Opens the selected file in a new split window and puts the cursor in the new +window. + +------------------------------------------------------------------------------ + *NERDTree-gi* +Default key: gi +Map option: None +Applies to: files. + +The same as |NERDTree-i| except that the cursor is not moved. + +The key combo for this mapping is always "g" + NERDTreeMapOpenSplit (see +|NERDTree-i|). + +------------------------------------------------------------------------------ + *NERDTree-s* +Default key: s +Map option: NERDTreeMapOpenVSplit +Applies to: files. + +Opens the selected file in a new vertically split window and puts the cursor in +the new window. + +------------------------------------------------------------------------------ + *NERDTree-gs* +Default key: gs +Map option: None +Applies to: files. + +The same as |NERDTree-s| except that the cursor is not moved. + +The key combo for this mapping is always "g" + NERDTreeMapOpenVSplit (see +|NERDTree-s|). + +------------------------------------------------------------------------------ + *NERDTree-O* +Default key: O +Map option: NERDTreeMapOpenRecursively +Applies to: directories. + +Recursively opens the selelected directory. + +All files and directories are cached, but if a directory would not be +displayed due to file filters (see |'NERDTreeIgnore'| |NERDTree-f|) or the +hidden file filter (see |'NERDTreeShowHidden'|) then its contents are not +cached. This is handy, especially if you have .svn directories. + +------------------------------------------------------------------------------ + *NERDTree-x* +Default key: x +Map option: NERDTreeMapCloseDir +Applies to: files and directories. + +Closes the parent of the selected node. + +------------------------------------------------------------------------------ + *NERDTree-X* +Default key: X +Map option: NERDTreeMapCloseChildren +Applies to: directories. + +Recursively closes all children of the selected directory. + +Tip: To quickly "reset" the tree, use |NERDTree-P| with this mapping. + +------------------------------------------------------------------------------ + *NERDTree-e* +Default key: e +Map option: NERDTreeMapOpenExpl +Applies to: files and directories. + +|:edit|s the selected directory, or the selected file's directory. This could +result in a NERD tree or a netrw being opened, depending on +|'NERDTreeHijackNetrw'|. + +------------------------------------------------------------------------------ + *NERDTree-D* +Default key: D +Map option: NERDTreeMapDeleteBookmark +Applies to: lines in the bookmarks table + +Deletes the currently selected bookmark. + +------------------------------------------------------------------------------ + *NERDTree-P* +Default key: P +Map option: NERDTreeMapJumpRoot +Applies to: no restrictions. + +Jump to the tree root. + +------------------------------------------------------------------------------ + *NERDTree-p* +Default key: p +Map option: NERDTreeMapJumpParent +Applies to: files and directories. + +Jump to the parent node of the selected node. + +------------------------------------------------------------------------------ + *NERDTree-K* +Default key: K +Map option: NERDTreeMapJumpFirstChild +Applies to: files and directories. + +Jump to the first child of the current nodes parent. + +If the cursor is already on the first node then do the following: + * loop back thru the siblings of the current nodes parent until we find an + open dir with children + * go to the first child of that node + +------------------------------------------------------------------------------ + *NERDTree-J* +Default key: J +Map option: NERDTreeMapJumpLastChild +Applies to: files and directories. + +Jump to the last child of the current nodes parent. + +If the cursor is already on the last node then do the following: + * loop forward thru the siblings of the current nodes parent until we find + an open dir with children + * go to the last child of that node + +------------------------------------------------------------------------------ + *NERDTree-C-J* +Default key: <C-J> +Map option: NERDTreeMapJumpNextSibling +Applies to: files and directories. + +Jump to the next sibling of the selected node. + +------------------------------------------------------------------------------ + *NERDTree-C-K* +Default key: <C-K> +Map option: NERDTreeMapJumpPrevSibling +Applies to: files and directories. + +Jump to the previous sibling of the selected node. + +------------------------------------------------------------------------------ + *NERDTree-C* +Default key: C +Map option: NERDTreeMapChdir +Applies to: directories. + +Make the selected directory node the new tree root. If a file is selected, its +parent is used. + +------------------------------------------------------------------------------ + *NERDTree-u* +Default key: u +Map option: NERDTreeMapUpdir +Applies to: no restrictions. + +Move the tree root up a dir (like doing a "cd .."). + +------------------------------------------------------------------------------ + *NERDTree-U* +Default key: U +Map option: NERDTreeMapUpdirKeepOpen +Applies to: no restrictions. + +Like |NERDTree-u| except that the old tree root is kept open. + +------------------------------------------------------------------------------ + *NERDTree-r* +Default key: r +Map option: NERDTreeMapRefresh +Applies to: files and directories. + +If a dir is selected, recursively refresh that dir, i.e. scan the filesystem +for changes and represent them in the tree. + +If a file node is selected then the above is done on it's parent. + +------------------------------------------------------------------------------ + *NERDTree-R* +Default key: R +Map option: NERDTreeMapRefreshRoot +Applies to: no restrictions. + +Recursively refresh the tree root. + +------------------------------------------------------------------------------ + *NERDTree-m* +Default key: m +Map option: NERDTreeMapMenu +Applies to: files and directories. + +Display the NERD tree menu. See |NERDTreeMenu| for details. + +------------------------------------------------------------------------------ + *NERDTree-cd* +Default key: cd +Map option: NERDTreeMapChdir +Applies to: files and directories. + +Change vims current working directory to that of the selected node. + +------------------------------------------------------------------------------ + *NERDTree-I* +Default key: I +Map option: NERDTreeMapToggleHidden +Applies to: no restrictions. + +Toggles whether hidden files (i.e. "dot files") are displayed. + +------------------------------------------------------------------------------ + *NERDTree-f* +Default key: f +Map option: NERDTreeMapToggleFilters +Applies to: no restrictions. + +Toggles whether file filters are used. See |'NERDTreeIgnore'| for details. + +------------------------------------------------------------------------------ + *NERDTree-F* +Default key: F +Map option: NERDTreeMapToggleFiles +Applies to: no restrictions. + +Toggles whether file nodes are displayed. + +------------------------------------------------------------------------------ + *NERDTree-B* +Default key: B +Map option: NERDTreeMapToggleBookmarks +Applies to: no restrictions. + +Toggles whether the bookmarks table is displayed. + +------------------------------------------------------------------------------ + *NERDTree-q* +Default key: q +Map option: NERDTreeMapQuit +Applies to: no restrictions. + +Closes the NERDtree window. + +------------------------------------------------------------------------------ + *NERDTree-A* +Default key: A +Map option: NERDTreeMapToggleZoom +Applies to: no restrictions. + +Maximize (zoom) and minimize the NERDtree window. + +------------------------------------------------------------------------------ + *NERDTree-?* +Default key: ? +Map option: NERDTreeMapHelp +Applies to: no restrictions. + +Toggles whether the quickhelp is displayed. + +------------------------------------------------------------------------------ +2.3. The NERD tree menu *NERDTreeMenu* + +The NERD tree has a menu that can be programmed via the an API (see +|NERDTreeMenuAPI|). The idea is to simulate the "right click" menus that most +file explorers have. + +The script comes with two default menu plugins: exec_menuitem.vim and +fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for +creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a +menu item to execute executable files. + +Related tags: |NERDTree-m| |NERDTreeApi| + +============================================================================== +3. Customisation *NERDTreeOptions* + + +------------------------------------------------------------------------------ +3.1. Customisation summary *NERDTreeOptionSummary* + +The script provides the following options that can customise the behaviour the +NERD tree. These options should be set in your vimrc. + +|'loaded_nerd_tree'| Turns off the script. + +|'NERDChristmasTree'| Tells the NERD tree to make itself colourful + and pretty. + +|'NERDTreeAutoCenter'| Controls whether the NERD tree window centers + when the cursor moves within a specified + distance to the top/bottom of the window. +|'NERDTreeAutoCenterThreshold'| Controls the sensitivity of autocentering. + +|'NERDTreeCaseSensitiveSort'| Tells the NERD tree whether to be case + sensitive or not when sorting nodes. + +|'NERDTreeChDirMode'| Tells the NERD tree if/when it should change + vim's current working directory. + +|'NERDTreeHighlightCursorline'| Tell the NERD tree whether to highlight the + current cursor line. + +|'NERDTreeHijackNetrw'| Tell the NERD tree whether to replace the netrw + autocommands for exploring local directories. + +|'NERDTreeIgnore'| Tells the NERD tree which files to ignore. + +|'NERDTreeBookmarksFile'| Where the bookmarks are stored. + +|'NERDTreeMouseMode'| Tells the NERD tree how to handle mouse + clicks. + +|'NERDTreeQuitOnOpen'| Closes the tree window after opening a file. + +|'NERDTreeShowBookmarks'| Tells the NERD tree whether to display the + bookmarks table on startup. + +|'NERDTreeShowFiles'| Tells the NERD tree whether to display files + in the tree on startup. + +|'NERDTreeShowHidden'| Tells the NERD tree whether to display hidden + files on startup. + +|'NERDTreeShowLineNumbers'| Tells the NERD tree whether to display line + numbers in the tree window. + +|'NERDTreeSortOrder'| Tell the NERD tree how to sort the nodes in + the tree. + +|'NERDTreeStatusline'| Set a statusline for NERD tree windows. + +|'NERDTreeWinPos'| Tells the script where to put the NERD tree + window. + +|'NERDTreeWinSize'| Sets the window size when the NERD tree is + opened. + +------------------------------------------------------------------------------ +3.2. Customisation details *NERDTreeOptionDetails* + +To enable any of the below options you should put the given line in your +~/.vimrc + + *'loaded_nerd_tree'* +If this plugin is making you feel homicidal, it may be a good idea to turn it +off with this line in your vimrc: > + let loaded_nerd_tree=1 +< +------------------------------------------------------------------------------ + *'NERDChristmasTree'* +Values: 0 or 1. +Default: 1. + +If this option is set to 1 then some extra syntax highlighting elements are +added to the nerd tree to make it more colourful. + +Set it to 0 for a more vanilla looking tree. + +------------------------------------------------------------------------------ + *'NERDTreeAutoCenter'* +Values: 0 or 1. +Default: 1 + +If set to 1, the NERD tree window will center around the cursor if it moves to +within |'NERDTreeAutoCenterThreshold'| lines of the top/bottom of the window. + +This is ONLY done in response to tree navigation mappings, +i.e. |NERDTree-J| |NERDTree-K| |NERDTree-C-J| |NERDTree-C-K| |NERDTree-p| +|NERDTree-P| + +The centering is done with a |zz| operation. + +------------------------------------------------------------------------------ + *'NERDTreeAutoCenterThreshold'* +Values: Any natural number. +Default: 3 + +This option controls the "sensitivity" of the NERD tree auto centering. See +|'NERDTreeAutoCenter'| for details. + +------------------------------------------------------------------------------ + *'NERDTreeCaseSensitiveSort'* +Values: 0 or 1. +Default: 0. + +By default the NERD tree does not sort nodes case sensitively, i.e. nodes +could appear like this: > + bar.c + Baz.c + blarg.c + boner.c + Foo.c +< +But, if you set this option to 1 then the case of the nodes will be taken into +account. The above nodes would then be sorted like this: > + Baz.c + Foo.c + bar.c + blarg.c + boner.c +< +------------------------------------------------------------------------------ + *'NERDTreeChDirMode'* + +Values: 0, 1 or 2. +Default: 0. + +Use this option to tell the script when (if at all) to change the current +working directory (CWD) for vim. + +If it is set to 0 then the CWD is never changed by the NERD tree. + +If set to 1 then the CWD is changed when the NERD tree is first loaded to the +directory it is initialized in. For example, if you start the NERD tree with > + :NERDTree /home/marty/foobar +< +then the CWD will be changed to /home/marty/foobar and will not be changed +again unless you init another NERD tree with a similar command. + +If the option is set to 2 then it behaves the same as if set to 1 except that +the CWD is changed whenever the tree root is changed. For example, if the CWD +is /home/marty/foobar and you make the node for /home/marty/foobar/baz the new +root then the CWD will become /home/marty/foobar/baz. + +------------------------------------------------------------------------------ + *'NERDTreeHighlightCursorline'* +Values: 0 or 1. +Default: 1. + +If set to 1, the current cursor line in the NERD tree buffer will be +highlighted. This is done using the |'cursorline'| option. + +------------------------------------------------------------------------------ + *'NERDTreeHijackNetrw'* +Values: 0 or 1. +Default: 1. + +If set to 1, doing a > + :edit <some directory> +< +will open up a "secondary" NERD tree instead of a netrw in the target window. + +Secondary NERD trees behaves slighly different from a regular trees in the +following respects: + 1. 'o' will open the selected file in the same window as the tree, + replacing it. + 2. you can have as many secondary tree as you want in the same tab. + +------------------------------------------------------------------------------ + *'NERDTreeIgnore'* +Values: a list of regular expressions. +Default: ['\~$']. + +This option is used to specify which files the NERD tree should ignore. It +must be a list of regular expressions. When the NERD tree is rendered, any +files/dirs that match any of the regex's in 'NERDTreeIgnore' wont be +displayed. + +For example if you put the following line in your vimrc: > + let NERDTreeIgnore=['\.vim$', '\~$'] +< +then all files ending in .vim or ~ will be ignored. + +Note: to tell the NERD tree not to ignore any files you must use the following +line: > + let NERDTreeIgnore=[] +< + +The file filters can be turned on and off dynamically with the |NERDTree-f| +mapping. + +------------------------------------------------------------------------------ + *'NERDTreeBookmarksFile'* +Values: a path +Default: $HOME/.NERDTreeBookmarks + +This is where bookmarks are saved. See |NERDTreeBookmarkCommands|. + +------------------------------------------------------------------------------ + *'NERDTreeMouseMode'* +Values: 1, 2 or 3. +Default: 1. + +If set to 1 then a double click on a node is required to open it. +If set to 2 then a single click will open directory nodes, while a double +click will still be required for file nodes. +If set to 3 then a single click will open any node. + +Note: a double click anywhere on a line that a tree node is on will +activate it, but all single-click activations must be done on name of the node +itself. For example, if you have the following node: > + | | |-application.rb +< +then (to single click activate it) you must click somewhere in +'application.rb'. + +------------------------------------------------------------------------------ + *'NERDTreeQuitOnOpen'* + +Values: 0 or 1. +Default: 0 + +If set to 1, the NERD tree window will close after opening a file with the +|NERDTree-o|, |NERDTree-i|, |NERDTree-t| and |NERDTree-T| mappings. + +------------------------------------------------------------------------------ + *'NERDTreeShowBookmarks'* +Values: 0 or 1. +Default: 0. + +If this option is set to 1 then the bookmarks table will be displayed. + +This option can be toggled dynamically, per tree, with the |NERDTree-B| +mapping. + +------------------------------------------------------------------------------ + *'NERDTreeShowFiles'* +Values: 0 or 1. +Default: 1. + +If this option is set to 1 then files are displayed in the NERD tree. If it is +set to 0 then only directories are displayed. + +This option can be toggled dynamically, per tree, with the |NERDTree-F| +mapping and is useful for drastically shrinking the tree when you are +navigating to a different part of the tree. + +------------------------------------------------------------------------------ + *'NERDTreeShowHidden'* +Values: 0 or 1. +Default: 0. + +This option tells vim whether to display hidden files by default. This option +can be dynamically toggled, per tree, with the |NERDTree-I| mapping. Use one +of the follow lines to set this option: > + let NERDTreeShowHidden=0 + let NERDTreeShowHidden=1 +< + +------------------------------------------------------------------------------ + *'NERDTreeShowLineNumbers'* +Values: 0 or 1. +Default: 0. + +This option tells vim whether to display line numbers for the NERD tree +window. Use one of the follow lines to set this option: > + let NERDTreeShowLineNumbers=0 + let NERDTreeShowLineNumbers=1 +< + +------------------------------------------------------------------------------ + *'NERDTreeSortOrder'* +Values: a list of regular expressions. +Default: ['\/$', '*', '\.swp$', '\.bak$', '\~$'] + +This option is set to a list of regular expressions which are used to +specify the order of nodes under their parent. + +For example, if the option is set to: > + ['\.vim$', '\.c$', '\.h$', '*', 'foobar'] +< +then all .vim files will be placed at the top, followed by all .c files then +all .h files. All files containing the string 'foobar' will be placed at the +end. The star is a special flag: it tells the script that every node that +doesnt match any of the other regexps should be placed here. + +If no star is present in 'NERDTreeSortOrder' then one is automatically +appended to the array. + +The regex '\/$' should be used to match directory nodes. + +After this sorting is done, the files in each group are sorted alphabetically. + +Other examples: > + (1) ['*', '\/$'] + (2) [] + (3) ['\/$', '\.rb$', '\.php$', '*', '\.swp$', '\.bak$', '\~$'] +< +1. Directories will appear last, everything else will appear above. +2. Everything will simply appear in alphabetical order. +3. Dirs will appear first, then ruby and php. Swap files, bak files and vim + backup files will appear last with everything else preceding them. + +------------------------------------------------------------------------------ + *'NERDTreeStatusline'* +Values: Any valid statusline setting. +Default: %{b:NERDTreeRoot.path.strForOS(0)} + +Tells the script what to use as the |'statusline'| setting for NERD tree +windows. + +Note that the statusline is set using |:let-&| not |:set| so escaping spaces +isn't necessary. + +Setting this option to -1 will will deactivate it so that your global +statusline setting is used instead. + +------------------------------------------------------------------------------ + *'NERDTreeWinPos'* +Values: "left" or "right" +Default: "left". + +This option is used to determine where NERD tree window is placed on the +screen. + +This option makes it possible to use two different explorer plugins +simultaneously. For example, you could have the taglist plugin on the left of +the window and the NERD tree on the right. + +------------------------------------------------------------------------------ + *'NERDTreeWinSize'* +Values: a positive integer. +Default: 31. + +This option is used to change the size of the NERD tree when it is loaded. + +============================================================================== +4. The NERD tree API *NERDTreeAPI* + +The NERD tree script allows you to add custom key mappings and menu items via +a set of API calls. Any scripts that use this API should be placed in +~/.vim/nerdtree_plugin/ (*nix) or ~/vimfiles/nerdtree_plugin (windows). + +The script exposes some prototype objects that can be used to manipulate the +tree and/or get information from it: > + g:NERDTreePath + g:NERDTreeDirNode + g:NERDTreeFileNode + g:NERDTreeBookmark +< +See the code/comments in NERD_tree.vim to find how to use these objects. The +following code conventions are used: + * class members start with a capital letter + * instance members start with a lower case letter + * private members start with an underscore + +See this blog post for more details: + http://got-ravings.blogspot.com/2008/09/vim-pr0n-prototype-based-objects.html + +------------------------------------------------------------------------------ +4.1. Key map API *NERDTreeKeymapAPI* + +NERDTreeAddKeyMap({options}) *NERDTreeAddKeyMap()* + Adds a new keymapping for all NERD tree buffers. + {options} must be a dictionary, and must contain the following keys: + "key" - the trigger key for the new mapping + "callback" - the function the new mapping will be bound to + "quickhelpText" - the text that will appear in the quickhelp (see + |NERDTree-?|) + + Example: > + call NERDTreeAddKeyMap({ + \ 'key': 'b', + \ 'callback': 'NERDTreeEchoCurrentNode', + \ 'quickhelpText': 'echo full path of current node' }) + + function! NERDTreeEchoCurrentNode() + let n = g:NERDTreeFileNode.GetSelected() + if n != {} + echomsg 'Current node: ' . n.path.str() + endif + endfunction +< + This code should sit in a file like ~/.vim/nerdtree_plugin/mymapping.vim. + It adds a (rather useless) mapping on 'b' which echos the full path to the + current node. + +------------------------------------------------------------------------------ +4.2. Menu API *NERDTreeMenuAPI* + +NERDTreeAddSubmenu({options}) *NERDTreeAddSubmenu()* + Creates and returns a new submenu. + + {options} must be a dictionary and must contain the following keys: + "text" - the text of the submenu that the user will see + "shortcut" - a shortcut key for the submenu (need not be unique) + + The following keys are optional: + "isActiveCallback" - a function that will be called to determine whether + this submenu item will be displayed or not. The callback function must return + 0 or 1. + "parent" - the parent submenu of the new submenu (returned from a previous + invocation of NERDTreeAddSubmenu()). If this key is left out then the new + submenu will sit under the top level menu. + + See below for an example. + +NERDTreeAddMenuItem({options}) *NERDTreeAddMenuItem()* + Adds a new menu item to the NERD tree menu (see |NERDTreeMenu|). + + {options} must be a dictionary and must contain the + following keys: + "text" - the text of the menu item which the user will see + "shortcut" - a shortcut key for the menu item (need not be unique) + "callback" - the function that will be called when the user activates the + menu item. + + The following keys are optional: + "isActiveCallback" - a function that will be called to determine whether + this menu item will be displayed or not. The callback function must return + 0 or 1. + "parent" - if the menu item belongs under a submenu then this key must be + specified. This value for this key will be the object that + was returned when the submenu was created with |NERDTreeAddSubmenu()|. + + See below for an example. + +NERDTreeAddMenuSeparator([{options}]) *NERDTreeAddMenuSeparator()* + Adds a menu separator (a row of dashes). + + {options} is an optional dictionary that may contain the following keys: + "isActiveCallback" - see description in |NERDTreeAddMenuItem()|. + +Below is an example of the menu API in action. > + call NERDTreeAddMenuSeparator() + + call NERDTreeAddMenuItem({ + \ 'text': 'a (t)op level menu item', + \ 'shortcut': 't', + \ 'callback': 'SomeFunction' }) + + let submenu = NERDTreeAddSubmenu({ + \ 'text': 'a (s)ub menu', + \ 'shortcut': 's' }) + + call NERDTreeAddMenuItem({ + \ 'text': '(n)ested item 1', + \ 'shortcut': 'n', + \ 'callback': 'SomeFunction', + \ 'parent': submenu }) + + call NERDTreeAddMenuItem({ + \ 'text': '(n)ested item 2', + \ 'shortcut': 'n', + \ 'callback': 'SomeFunction', + \ 'parent': submenu }) +< +This will create the following menu: > + -------------------- + a (t)op level menu item + a (s)ub menu +< +Where selecting "a (s)ub menu" will lead to a second menu: > + (n)ested item 1 + (n)ested item 2 +< +When any of the 3 concrete menu items are selected the function "SomeFunction" +will be called. + +------------------------------------------------------------------------------ +NERDTreeRender() *NERDTreeRender()* + Re-renders the NERD tree buffer. Useful if you change the state of the + tree and you want to it to be reflected in the UI. + +============================================================================== +5. About *NERDTreeAbout* + +The author of the NERD tree is a terrible terrible monster called Martyzilla +who gobbles up small children with milk and sugar for breakfast. + +He can be reached at martin.grenfell at gmail dot com. He would love to hear +from you, so feel free to send him suggestions and/or comments about this +plugin. Don't be shy --- the worst he can do is slaughter you and stuff you in +the fridge for later ;) + +The latest stable versions can be found at + http://www.vim.org/scripts/script.php?script_id=1658 + +The latest dev versions are on github + http://github.com/scrooloose/nerdtree + + +============================================================================== +6. Changelog *NERDTreeChangelog* + +4.1.0 + features: + - NERDTreeFind to reveal the node for the current buffer in the tree, + see |NERDTreeFind|. This effectively merges the FindInNERDTree plugin (by + Doug McInnes) into the script. + - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan + Ritter and Rémi Prévost. + - truncate the root node if wider than the tree window. Thanks to Victor + Gonzalez. + + bugfixes: + - really fix window state restoring + - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, + jfilip1024, and Chris Chambers + +4.0.0 + - add a new programmable menu system (see :help NERDTreeMenu). + - add new APIs to add menus/menu-items to the menu system as well as + custom key mappings to the NERD tree buffer (see :help NERDTreeAPI). + - removed the old API functions + - added a mapping to maximize/restore the size of nerd tree window, thanks + to Guillaume Duranceau for the patch. See :help NERDTree-A for details. + + - fix a bug where secondary nerd trees (netrw hijacked trees) and + NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. + - fix a bug where the script ignored directories whose name ended in a dot, + thanks to Aggelos Orfanakos for the patch. + - fix a bug when using the x mapping on the tree root, thanks to Bryan + Venteicher for the patch. + - fix a bug where the cursor position/window size of the nerd tree buffer + wasnt being stored on closing the window, thanks to Richard Hart. + - fix a bug where NERDTreeMirror would mirror the wrong tree + +3.1.1 + - fix a bug where a non-listed no-name buffer was getting created every + time the tree windows was created, thanks to Derek Wyatt and owen1 + - make <CR> behave the same as the 'o' mapping + - some helptag fixes in the doc, thanks strull + - fix a bug when using :set nohidden and opening a file where the previous + buf was modified. Thanks iElectric + - other minor fixes + +3.1.0 + New features: + - add mappings to open files in a vsplit, see :help NERDTree-s and :help + NERDTree-gs + - make the statusline for the nerd tree window default to something + hopefully more useful. See :help 'NERDTreeStatusline' + Bugfixes: + - make the hijack netrw functionality work when vim is started with "vim + <some dir>" (thanks to Alf Mikula for the patch). + - fix a bug where the CWD wasnt being changed for some operations even when + NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) + - add -bar to all the nerd tree :commands so they can chain with other + :commands (thanks to tpope) + - fix bugs when ignorecase was set (thanks to nach) + - fix a bug with the relative path code (thanks to nach) + - fix a bug where doing a :cd would cause :NERDTreeToggle to fail (thanks nach) + + +3.0.1 + Bugfixes: + - fix bugs with :NERDTreeToggle and :NERDTreeMirror when 'hidden + was not set + - fix a bug where :NERDTree <path> would fail if <path> was relative and + didnt start with a ./ or ../ Thanks to James Kanze. + - make the q mapping work with secondary (:e <dir> style) trees, + thanks to jamessan + - fix a bunch of small bugs with secondary trees + + More insane refactoring. + +3.0.0 + - hijack netrw so that doing an :edit <directory> will put a NERD tree in + the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' + - allow sharing of trees across tabs, see :help :NERDTreeMirror + - remove "top" and "bottom" as valid settings for NERDTreeWinPos + - change the '<tab>' mapping to 'i' + - change the 'H' mapping to 'I' + - lots of refactoring + +============================================================================== +7. Credits *NERDTreeCredits* + +Thanks to the following people for testing, bug reports, ideas etc. Without +you I probably would have got bored of the hacking the NERD tree and +just downloaded pr0n instead. + + Tim Carey-Smith (halorgium) + Vigil + Nick Brettell + Thomas Scott Urban + Terrance Cohen + Yegappan Lakshmanan + Jason Mills + Michael Geddes (frogonwheels) + Yu Jun + Michael Madsen + AOYAMA Shotaro + Zhang Weiwu + Niels Aan de Brugh + Olivier Yiptong + Zhang Shuhan + Cory Echols + Piotr Czachur + Yuan Jiang + Matan Nassau + Maxim Kim + Charlton Wang + Matt Wozniski (godlygeek) + knekk + Sean Chou + Ryan Penn + Simon Peter Nicholls + Michael Foobar + Tomasz Chomiuk + Denis Pokataev + Tim Pope (tpope) + James Kanze + James Vega (jamessan) + Frederic Chanal (nach) + Alf Mikula + Lucas S. Buchala + Curtis Harvey + Guillaume Duranceau + Richard Hart (hates) + Doug McInnes + Stefan Ritter + Rémi Prévost + Victor Gonzalez + Stephan Baumeister + Ricky + jfilip1024 + Chris Chambers + +============================================================================== +8. License *NERDTreeLicense* + +The NERD tree is released under the wtfpl. +See http://sam.zoy.org/wtfpl/COPYING. Added: configs/trunk/src/vim/nerdtree_plugin/exec_menuitem.vim =================================================================== --- configs/trunk/src/vim/nerdtree_plugin/exec_menuitem.vim (rev 0) +++ configs/trunk/src/vim/nerdtree_plugin/exec_menuitem.vim 2010-01-25 03:38:43 UTC (rev 1550) @@ -0,0 +1,41 @@ +" ============================================================================ +" File: exec_menuitem.vim +" Description: plugin for NERD Tree that provides an execute file menu item +" Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> +" Last Change: 22 July, 2009 +" License: This program is free software. It comes without any warranty, +" to the extent permitted by applicable law. You can redistribute +" it and/or modify it under the terms of the Do What The Fuck You +" Want To Public License, Version 2, as published by Sam Hocevar. +" See http://sam.zoy.org/wtfpl/COPYING for more details. +" +" ============================================================================ +if exists("g:loaded_nerdtree_exec_menuitem") + finish +endif +let g:loaded_nerdtree_exec_menuitem = 1 + +call NERDTreeAddMenuItem({ + \ 'text': '(!)Execute file', + \ 'shortcut': '!', + \ 'callback': 'NERDTreeExecFile', + \ 'isActiveCallback': 'NERDTreeExecFileActive' }) + +function! NERDTreeExecFileActive() + let node = g:NERDTreeFileNode.GetSelected() + return !node.path.isDirectory && node.path.isExecutable +endfunction + +function! NERDTreeExecFile() + let treenode = g:NERDTreeFileNode.GetSelected() + echo "==========================================================\n" + echo "Complete the command to execute (add arguments etc):\n" + let cmd = treenode.path.str({'escape': 1}) + let cmd = input(':!', cmd . ' ') + + if cmd != '' + exec ':!' . cmd + else + echo "Aborted" + endif +endfunction Added: configs/trunk/src/vim/nerdtree_plugin/fs_menu.vim =================================================================== --- configs/trunk/src/vim/nerdtree_plugin/fs_menu.vim (rev 0) +++ configs/trunk/src/vim/nerdtree_plugin/fs_menu.vim 2010-01-25 03:38:43 UTC (rev 1550) @@ -0,0 +1,194 @@ +" ============================================================================ +" File: fs_menu.vim +" Description: plugin for the NERD Tree that provides a file system menu +" Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> +" Last Change: 17 July, 2009 +" License: This program is free software. It comes without any warranty, +" to the extent permitted by applicable law. You can redistribute +" it and/or modify it under the terms of the Do What The Fuck You +" Want To Public License, Version 2, as published by Sam Hocevar. +" See http://sam.zoy.org/wtfpl/COPYING for more details. +" +" ============================================================================ +if exists("g:loaded_nerdtree_fs_menu") + finish +endif +let g:loaded_nerdtree_fs_menu = 1 + +call NERDTreeAddMenuItem({'text': '(a)dd a childnode', 'shortcut': 'a', 'callback': 'NERDTreeAddNode'}) +call NERDTreeAddMenuItem({'text': '(m)ove the curent node', 'shortcut': 'm', 'callback': 'NERDTreeMoveNode'}) +call NERDTreeAddMenuItem({'text': '(d)elete the curent node', 'shortcut': 'd', 'callback': 'NERDTreeDeleteNode'}) +if g:NERDTreePath.CopyingSupported() + call NERDTreeAddMenuItem({'text': '(c)copy the current node', 'shortcut': 'c', 'callback': 'NERDTreeCopyNode'}) +endif + +"FUNCTION: s:echo(msg){{{1 +function! s:echo(msg) + redraw + echomsg "NERDTree: " . a:msg +endfunction + +"FUNCTION: s:echoWarning(msg){{{1 +function! s:echoWarning(msg) + echohl warningmsg + call s:echo(a:msg) + echohl normal +endfunction + +"FUNCTION: s:promptToDelBuffer(bufnum, msg){{{1 +"prints out the given msg and, if the user responds by pushing 'y' then the +"buffer with the given bufnum is deleted +" +"Args: +"bufnum: the buffer that may be deleted +"msg: a message that will be echoed to the user asking them if they wish to +" del the buffer +function! s:promptToDelBuffer(bufnum, msg) + echo a:msg + if nr2char(getchar()) ==# 'y' + exec "silent bdelete! " . a:bufnum + endif +endfunction + +"FUNCTION: NERDTreeAddNode(){{{1 +function! NERDTreeAddNode() + let curDirNode = g:NERDTreeDirNode.GetSelected() + + let newNodeName = input("Add a childnode\n". + \ "==========================================================\n". + \ "Enter the dir/file name to be created. Dirs end with a '/'\n" . + \ "", curDirNode.path.str({'format': 'Glob'}) . g:NERDTreePath.Slash()) + + if newNodeName ==# '' + call s:echo("Node Creation Aborted.") + return + endif + + try + let newPath = g:NERDTreePath.Create(newNodeName) + let parentNode = b:NERDTreeRoot.findNode(newPath.getParent()) + + let newTreeNode = g:NERDTreeFileNode.New(newPath) + if parentNode.isOpen || !empty(parentNode.children) + call parentNode.addChild(newTreeNode, 1) + call NERDTreeRender() + call newTreeNode.putCursorHere(1, 0) + endif + catch /^NERDTree/ + call s:echoWarning("Node Not Created.") + endtry +endfunction + +"FUNCTION: NERDTreeMoveNode(){{{1 +function! NERDTreeMoveNode() + let curNode = g:NERDTreeFileNode.GetSelected() + let newNodePath = input("Rename the current node\n" . + \ "==========================================================\n" . + \ "Enter the new path for the node: \n" . + \ "", curNode.path.str()) + + if newNodePath ==# '' + call s:echo("Node Renaming Aborted.") + return + endif + + try + let bufnum = bufnr(curNode.path.str()) + + call curNode.rename(newNodePath) + call NERDTreeRender() + + "if the node is open in a buffer, ask the user if they want to + "close that buffer + if bufnum != -1 + let prompt = "\nNode renamed.\n\nThe old file is open in buffer ". bufnum . (bufwinnr(bufnum) ==# -1 ? " (hidden)" : "") .". Delete this buffer? (yN)" + call s:promptToDelBuffer(bufnum, prompt) + endif + + call curNode.putCursorHere(1, 0) + + redraw + catch /^NERDTree/ + call s:echoWarning("Node Not Renamed.") + endtry +endfunction + +" FUNCTION: NERDTreeDeleteNode() {{{1 +function! NERDTreeDeleteNode() + let currentNode = g:NERDTreeFileNode.GetSelected() + let confirmed = 0 + + if currentNode.path.isDirectory + let choice =input("Delete the current node\n" . + \ "==========================================================\n" . + \ "STOP! To delete this entire directory, type 'yes'\n" . + \ "" . currentNode.path.str() . ": ") + let confirmed = choice ==# 'yes' + else + echo "Delete the current node\n" . + \ "==========================================================\n". + \ "Are you sure you wish to delete the node:\n" . + \ "" . currentNode.path.str() . " (yN):" + let choice = nr2char(getchar()) + let confirmed = choice ==# 'y' + endif + + + if confirmed + try + call currentNode.delete() + call NERDTreeRender() + + "if the node is open in a buffer, ask the user if they want to + "close that buffer + let bufnum = bufnr(currentNode.path.str()) + if buflisted(bufnum) + let prompt = "\nNode deleted.\n\nThe file is open in buffer ". bufnum . (bufwinnr(bufnum) ==# -1 ? " (hidden)" : "") .". Delete this buffer? (yN)" + call s:promptToDelBuffer(bufnum, prompt) + endif + + redraw + catch /^NERDTree/ + call s:echoWarning("Could not remove node") + endtry + else + call s:echo("delete aborted") + endif + +endfunction + +" FUNCTION: NERDTreeCopyNode() {{{1 +function! NERDTreeCopyNode() + let currentNode = g:NERDTreeFileNode.GetSelected() + let newNodePath = input("Copy the current node\n" . + \ "==========================================================\n" . + \ "Enter the new path to copy the node to: \n" . + \ "", currentNode.path.str()) + + if newNodePat... [truncated message content] |
From: <yan...@us...> - 2010-01-25 03:39:50
|
Revision: 1551 http://assorted.svn.sourceforge.net/assorted/?rev=1551&view=rev Author: yangzhang Date: 2010-01-25 03:39:43 +0000 (Mon, 25 Jan 2010) Log Message: ----------- added snipmate for vim Added Paths: ----------- configs/trunk/src/vim/after/ configs/trunk/src/vim/after/plugin/ configs/trunk/src/vim/after/plugin/snipMate.vim configs/trunk/src/vim/autoload/ configs/trunk/src/vim/autoload/snipMate.vim configs/trunk/src/vim/ftplugin/html_snip_helper.vim configs/trunk/src/vim/plugin/snipMate.vim configs/trunk/src/vim/snippets/ configs/trunk/src/vim/snippets/_.snippets configs/trunk/src/vim/snippets/autoit.snippets configs/trunk/src/vim/snippets/c.snippets configs/trunk/src/vim/snippets/cpp.snippets configs/trunk/src/vim/snippets/html.snippets configs/trunk/src/vim/snippets/java.snippets configs/trunk/src/vim/snippets/javascript.snippets configs/trunk/src/vim/snippets/mako.snippets configs/trunk/src/vim/snippets/objc.snippets configs/trunk/src/vim/snippets/perl.snippets configs/trunk/src/vim/snippets/php.snippets configs/trunk/src/vim/snippets/python.snippets configs/trunk/src/vim/snippets/ruby.snippets configs/trunk/src/vim/snippets/sh.snippets configs/trunk/src/vim/snippets/snippet.snippets configs/trunk/src/vim/snippets/tcl.snippets configs/trunk/src/vim/snippets/tex.snippets configs/trunk/src/vim/snippets/vim.snippets configs/trunk/src/vim/snippets/zsh.snippets configs/trunk/src/vim/syntax/snippet.vim Added: configs/trunk/src/vim/after/plugin/snipMate.vim =================================================================== --- configs/trunk/src/vim/after/plugin/snipMate.vim (rev 0) +++ configs/trunk/src/vim/after/plugin/snipMate.vim 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,35 @@ +" These are the mappings for snipMate.vim. Putting it here ensures that it +" will be mapped after other plugins such as supertab.vim. +if !exists('loaded_snips') || exists('s:did_snips_mappings') + finish +endif +let s:did_snips_mappings = 1 + +ino <silent> <tab> <c-r>=TriggerSnippet()<cr> +snor <silent> <tab> <esc>i<right><c-r>=TriggerSnippet()<cr> +ino <silent> <s-tab> <c-r>=BackwardsSnippet()<cr> +snor <silent> <s-tab> <esc>i<right><c-r>=BackwardsSnippet()<cr> +ino <silent> <c-r><tab> <c-r>=ShowAvailableSnips()<cr> + +" The default mappings for these are annoying & sometimes break snipMate. +" You can change them back if you want, I've put them here for convenience. +snor <bs> b<bs> +snor <right> <esc>a +snor <left> <esc>bi +snor ' b<bs>' +snor ` b<bs>` +snor % b<bs>% +snor U b<bs>U +snor ^ b<bs>^ +snor \ b<bs>\ +snor <c-x> b<bs><c-x> + +" By default load snippets in snippets_dir +if empty(snippets_dir) + finish +endif + +call GetSnippets(snippets_dir, '_') " Get global snippets + +au FileType * if &ft != 'help' | call GetSnippets(snippets_dir, &ft) | endif +" vim:noet:sw=4:ts=4:ft=vim Added: configs/trunk/src/vim/autoload/snipMate.vim =================================================================== --- configs/trunk/src/vim/autoload/snipMate.vim (rev 0) +++ configs/trunk/src/vim/autoload/snipMate.vim 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,433 @@ +fun! Filename(...) + let filename = expand('%:t:r') + if filename == '' | return a:0 == 2 ? a:2 : '' | endif + return !a:0 || a:1 == '' ? filename : substitute(a:1, '$1', filename, 'g') +endf + +fun s:RemoveSnippet() + unl! g:snipPos s:curPos s:snipLen s:endCol s:endLine s:prevLen + \ s:lastBuf s:oldWord + if exists('s:update') + unl s:startCol s:origWordLen s:update + if exists('s:oldVars') | unl s:oldVars s:oldEndCol | endif + endif + aug! snipMateAutocmds +endf + +fun snipMate#expandSnip(snip, col) + let lnum = line('.') | let col = a:col + + let snippet = s:ProcessSnippet(a:snip) + " Avoid error if eval evaluates to nothing + if snippet == '' | return '' | endif + + " Expand snippet onto current position with the tab stops removed + let snipLines = split(substitute(snippet, '$\d\+\|${\d\+.\{-}}', '', 'g'), "\n", 1) + + let line = getline(lnum) + let afterCursor = strpart(line, col - 1) + " Keep text after the cursor + if afterCursor != "\t" && afterCursor != ' ' + let line = strpart(line, 0, col - 1) + let snipLines[-1] .= afterCursor + else + let afterCursor = '' + " For some reason the cursor needs to move one right after this + if line != '' && col == 1 && &ve != 'all' && &ve != 'onemore' + let col += 1 + endif + endif + + call setline(lnum, line.snipLines[0]) + + " Autoindent snippet according to previous indentation + let indent = matchend(line, '^.\{-}\ze\(\S\|$\)') + 1 + call append(lnum, map(snipLines[1:], "'".strpart(line, 0, indent - 1)."'.v:val")) + + " Open any folds snippet expands into + if &fen | sil! exe lnum.','.(lnum + len(snipLines) - 1).'foldopen' | endif + + let [g:snipPos, s:snipLen] = s:BuildTabStops(snippet, lnum, col - indent, indent) + + if s:snipLen + aug snipMateAutocmds + au CursorMovedI * call s:UpdateChangedSnip(0) + au InsertEnter * call s:UpdateChangedSnip(1) + aug END + let s:lastBuf = bufnr(0) " Only expand snippet while in current buffer + let s:curPos = 0 + let s:endCol = g:snipPos[s:curPos][1] + let s:endLine = g:snipPos[s:curPos][0] + + call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) + let s:prevLen = [line('$'), col('$')] + if g:snipPos[s:curPos][2] != -1 | return s:SelectWord() | endif + else + unl g:snipPos s:snipLen + " Place cursor at end of snippet if no tab stop is given + let newlines = len(snipLines) - 1 + call cursor(lnum + newlines, indent + len(snipLines[-1]) - len(afterCursor) + \ + (newlines ? 0: col - 1)) + endif + return '' +endf + +" Prepare snippet to be processed by s:BuildTabStops +fun s:ProcessSnippet(snip) + let snippet = a:snip + " Evaluate eval (`...`) expressions. + " Using a loop here instead of a regex fixes a bug with nested "\=". + if stridx(snippet, '`') != -1 + while match(snippet, '`.\{-}`') != -1 + let snippet = substitute(snippet, '`.\{-}`', + \ substitute(eval(matchstr(snippet, '`\zs.\{-}\ze`')), + \ "\n\\%$", '', ''), '') + endw + let snippet = substitute(snippet, "\r", "\n", 'g') + endif + + " Place all text after a colon in a tab stop after the tab stop + " (e.g. "${#:foo}" becomes "${:foo}foo"). + " This helps tell the position of the tab stops later. + let snippet = substitute(snippet, '${\d\+:\(.\{-}\)}', '&\1', 'g') + + " Update the a:snip so that all the $# become the text after + " the colon in their associated ${#}. + " (e.g. "${1:foo}" turns all "$1"'s into "foo") + let i = 1 + while stridx(snippet, '${'.i) != -1 + let s = matchstr(snippet, '${'.i.':\zs.\{-}\ze}') + if s != '' + let snippet = substitute(snippet, '$'.i, s.'&', 'g') + endif + let i += 1 + endw + + if &et " Expand tabs to spaces if 'expandtab' is set. + return substitute(snippet, '\t', repeat(' ', &sts ? &sts : &sw), 'g') + endif + return snippet +endf + +" Counts occurences of haystack in needle +fun s:Count(haystack, needle) + let counter = 0 + let index = stridx(a:haystack, a:needle) + while index != -1 + let index = stridx(a:haystack, a:needle, index+1) + let counter += 1 + endw + return counter +endf + +" Builds a list of a list of each tab stop in the snippet containing: +" 1.) The tab stop's line number. +" 2.) The tab stop's column number +" (by getting the length of the string between the last "\n" and the +" tab stop). +" 3.) The length of the text after the colon for the current tab stop +" (e.g. "${1:foo}" would return 3). If there is no text, -1 is returned. +" 4.) If the "${#:}" construct is given, another list containing all +" the matches of "$#", to be replaced with the placeholder. This list is +" composed the same way as the parent; the first item is the line number, +" and the second is the column. +fun s:BuildTabStops(snip, lnum, col, indent) + let snipPos = [] + let i = 1 + let withoutVars = substitute(a:snip, '$\d\+', '', 'g') + while stridx(a:snip, '${'.i) != -1 + let beforeTabStop = matchstr(withoutVars, '^.*\ze${'.i.'\D') + let withoutOthers = substitute(withoutVars, '${\('.i.'\D\)\@!\d\+.\{-}}', '', 'g') + + let j = i - 1 + call add(snipPos, [0, 0, -1]) + let snipPos[j][0] = a:lnum + s:Count(beforeTabStop, "\n") + let snipPos[j][1] = a:indent + len(matchstr(withoutOthers, '.*\(\n\|^\)\zs.*\ze${'.i.'\D')) + if snipPos[j][0] == a:lnum | let snipPos[j][1] += a:col | endif + + " Get all $# matches in another list, if ${#:name} is given + if stridx(withoutVars, '${'.i.':') != -1 + let snipPos[j][2] = len(matchstr(withoutVars, '${'.i.':\zs.\{-}\ze}')) + let dots = repeat('.', snipPos[j][2]) + call add(snipPos[j], []) + let withoutOthers = substitute(a:snip, '${\d\+.\{-}}\|$'.i.'\@!\d\+', '', 'g') + while match(withoutOthers, '$'.i.'\(\D\|$\)') != -1 + let beforeMark = matchstr(withoutOthers, '^.\{-}\ze'.dots.'$'.i.'\(\D\|$\)') + call add(snipPos[j][3], [0, 0]) + let snipPos[j][3][-1][0] = a:lnum + s:Count(beforeMark, "\n") + let snipPos[j][3][-1][1] = a:indent + (snipPos[j][3][-1][0] > a:lnum + \ ? len(matchstr(beforeMark, '.*\n\zs.*')) + \ : a:col + len(beforeMark)) + let withoutOthers = substitute(withoutOthers, '$'.i.'\ze\(\D\|$\)', '', '') + endw + endif + let i += 1 + endw + return [snipPos, i - 1] +endf + +fun snipMate#jumpTabStop(backwards) + let leftPlaceholder = exists('s:origWordLen') + \ && s:origWordLen != g:snipPos[s:curPos][2] + if leftPlaceholder && exists('s:oldEndCol') + let startPlaceholder = s:oldEndCol + 1 + endif + + if exists('s:update') + call s:UpdatePlaceholderTabStops() + else + call s:UpdateTabStops() + endif + + " Don't reselect placeholder if it has been modified + if leftPlaceholder && g:snipPos[s:curPos][2] != -1 + if exists('startPlaceholder') + let g:snipPos[s:curPos][1] = startPlaceholder + else + let g:snipPos[s:curPos][1] = col('.') + let g:snipPos[s:curPos][2] = 0 + endif + endif + + let s:curPos += a:backwards ? -1 : 1 + " Loop over the snippet when going backwards from the beginning + if s:curPos < 0 | let s:curPos = s:snipLen - 1 | endif + + if s:curPos == s:snipLen + let sMode = s:endCol == g:snipPos[s:curPos-1][1]+g:snipPos[s:curPos-1][2] + call s:RemoveSnippet() + return sMode ? "\<tab>" : TriggerSnippet() + endif + + call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) + + let s:endLine = g:snipPos[s:curPos][0] + let s:endCol = g:snipPos[s:curPos][1] + let s:prevLen = [line('$'), col('$')] + + return g:snipPos[s:curPos][2] == -1 ? '' : s:SelectWord() +endf + +fun s:UpdatePlaceholderTabStops() + let changeLen = s:origWordLen - g:snipPos[s:curPos][2] + unl s:startCol s:origWordLen s:update + if !exists('s:oldVars') | return | endif + " Update tab stops in snippet if text has been added via "$#" + " (e.g., in "${1:foo}bar$1${2}"). + if changeLen != 0 + let curLine = line('.') + + for pos in g:snipPos + if pos == g:snipPos[s:curPos] | continue | endif + let changed = pos[0] == curLine && pos[1] > s:oldEndCol + let changedVars = 0 + let endPlaceholder = pos[2] - 1 + pos[1] + " Subtract changeLen from each tab stop that was after any of + " the current tab stop's placeholders. + for [lnum, col] in s:oldVars + if lnum > pos[0] | break | endif + if pos[0] == lnum + if pos[1] > col || (pos[2] == -1 && pos[1] == col) + let changed += 1 + elseif col < endPlaceholder + let changedVars += 1 + endif + endif + endfor + let pos[1] -= changeLen * changed + let pos[2] -= changeLen * changedVars " Parse variables within placeholders + " e.g., "${1:foo} ${2:$1bar}" + + if pos[2] == -1 | continue | endif + " Do the same to any placeholders in the other tab stops. + for nPos in pos[3] + let changed = nPos[0] == curLine && nPos[1] > s:oldEndCol + for [lnum, col] in s:oldVars + if lnum > nPos[0] | break | endif + if nPos[0] == lnum && nPos[1] > col + let changed += 1 + endif + endfor + let nPos[1] -= changeLen * changed + endfor + endfor + endif + unl s:endCol s:oldVars s:oldEndCol +endf + +fun s:UpdateTabStops() + let changeLine = s:endLine - g:snipPos[s:curPos][0] + let changeCol = s:endCol - g:snipPos[s:curPos][1] + if exists('s:origWordLen') + let changeCol -= s:origWordLen + unl s:origWordLen + endif + let lnum = g:snipPos[s:curPos][0] + let col = g:snipPos[s:curPos][1] + " Update the line number of all proceeding tab stops if <cr> has + " been inserted. + if changeLine != 0 + let changeLine -= 1 + for pos in g:snipPos + if pos[0] >= lnum + if pos[0] == lnum | let pos[1] += changeCol | endif + let pos[0] += changeLine + endif + if pos[2] == -1 | continue | endif + for nPos in pos[3] + if nPos[0] >= lnum + if nPos[0] == lnum | let nPos[1] += changeCol | endif + let nPos[0] += changeLine + endif + endfor + endfor + elseif changeCol != 0 + " Update the column of all proceeding tab stops if text has + " been inserted/deleted in the current line. + for pos in g:snipPos + if pos[1] >= col && pos[0] == lnum + let pos[1] += changeCol + endif + if pos[2] == -1 | continue | endif + for nPos in pos[3] + if nPos[0] > lnum | break | endif + if nPos[0] == lnum && nPos[1] >= col + let nPos[1] += changeCol + endif + endfor + endfor + endif +endf + +fun s:SelectWord() + let s:origWordLen = g:snipPos[s:curPos][2] + let s:oldWord = strpart(getline('.'), g:snipPos[s:curPos][1] - 1, + \ s:origWordLen) + let s:prevLen[1] -= s:origWordLen + if !empty(g:snipPos[s:curPos][3]) + let s:update = 1 + let s:endCol = -1 + let s:startCol = g:snipPos[s:curPos][1] - 1 + endif + if !s:origWordLen | return '' | endif + let l = col('.') != 1 ? 'l' : '' + if &sel == 'exclusive' + return "\<esc>".l.'v'.s:origWordLen."l\<c-g>" + endif + return s:origWordLen == 1 ? "\<esc>".l.'gh' + \ : "\<esc>".l.'v'.(s:origWordLen - 1)."l\<c-g>" +endf + +" This updates the snippet as you type when text needs to be inserted +" into multiple places (e.g. in "${1:default text}foo$1bar$1", +" "default text" would be highlighted, and if the user types something, +" UpdateChangedSnip() would be called so that the text after "foo" & "bar" +" are updated accordingly) +" +" It also automatically quits the snippet if the cursor is moved out of it +" while in insert mode. +fun s:UpdateChangedSnip(entering) + if exists('g:snipPos') && bufnr(0) != s:lastBuf + call s:RemoveSnippet() + elseif exists('s:update') " If modifying a placeholder + if !exists('s:oldVars') && s:curPos + 1 < s:snipLen + " Save the old snippet & word length before it's updated + " s:startCol must be saved too, in case text is added + " before the snippet (e.g. in "foo$1${2}bar${1:foo}"). + let s:oldEndCol = s:startCol + let s:oldVars = deepcopy(g:snipPos[s:curPos][3]) + endif + let col = col('.') - 1 + + if s:endCol != -1 + let changeLen = col('$') - s:prevLen[1] + let s:endCol += changeLen + else " When being updated the first time, after leaving select mode + if a:entering | return | endif + let s:endCol = col - 1 + endif + + " If the cursor moves outside the snippet, quit it + if line('.') != g:snipPos[s:curPos][0] || col < s:startCol || + \ col - 1 > s:endCol + unl! s:startCol s:origWordLen s:oldVars s:update + return s:RemoveSnippet() + endif + + call s:UpdateVars() + let s:prevLen[1] = col('$') + elseif exists('g:snipPos') + if !a:entering && g:snipPos[s:curPos][2] != -1 + let g:snipPos[s:curPos][2] = -2 + endif + + let col = col('.') + let lnum = line('.') + let changeLine = line('$') - s:prevLen[0] + + if lnum == s:endLine + let s:endCol += col('$') - s:prevLen[1] + let s:prevLen = [line('$'), col('$')] + endif + if changeLine != 0 + let s:endLine += changeLine + let s:endCol = col + endif + + " Delete snippet if cursor moves out of it in insert mode + if (lnum == s:endLine && (col > s:endCol || col < g:snipPos[s:curPos][1])) + \ || lnum > s:endLine || lnum < g:snipPos[s:curPos][0] + call s:RemoveSnippet() + endif + endif +endf + +" This updates the variables in a snippet when a placeholder has been edited. +" (e.g., each "$1" in "${1:foo} $1bar $1bar") +fun s:UpdateVars() + let newWordLen = s:endCol - s:startCol + 1 + let newWord = strpart(getline('.'), s:startCol, newWordLen) + if newWord == s:oldWord || empty(g:snipPos[s:curPos][3]) + return + endif + + let changeLen = g:snipPos[s:curPos][2] - newWordLen + let curLine = line('.') + let startCol = col('.') + let oldStartSnip = s:startCol + let updateTabStops = changeLen != 0 + let i = 0 + + for [lnum, col] in g:snipPos[s:curPos][3] + if updateTabStops + let start = s:startCol + if lnum == curLine && col <= start + let s:startCol -= changeLen + let s:endCol -= changeLen + endif + for nPos in g:snipPos[s:curPos][3][(i):] + " This list is in ascending order, so quit if we've gone too far. + if nPos[0] > lnum | break | endif + if nPos[0] == lnum && nPos[1] > col + let nPos[1] -= changeLen + endif + endfor + if lnum == curLine && col > start + let col -= changeLen + let g:snipPos[s:curPos][3][i][1] = col + endif + let i += 1 + endif + + " "Very nomagic" is used here to allow special characters. + call setline(lnum, substitute(getline(lnum), '\%'.col.'c\V'. + \ escape(s:oldWord, '\'), escape(newWord, '\&'), '')) + endfor + if oldStartSnip != s:startCol + call cursor(0, startCol + s:startCol - oldStartSnip) + endif + + let s:oldWord = newWord + let g:snipPos[s:curPos][2] = newWordLen +endf +" vim:noet:sw=4:ts=4:ft=vim Added: configs/trunk/src/vim/ftplugin/html_snip_helper.vim =================================================================== --- configs/trunk/src/vim/ftplugin/html_snip_helper.vim (rev 0) +++ configs/trunk/src/vim/ftplugin/html_snip_helper.vim 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,10 @@ +" Helper function for (x)html snippets +if exists('s:did_snip_helper') || &cp || !exists('loaded_snips') + finish +endif +let s:did_snip_helper = 1 + +" Automatically closes tag if in xhtml +fun! Close() + return stridx(&ft, 'xhtml') == -1 ? '' : ' /' +endf Added: configs/trunk/src/vim/plugin/snipMate.vim =================================================================== --- configs/trunk/src/vim/plugin/snipMate.vim (rev 0) +++ configs/trunk/src/vim/plugin/snipMate.vim 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,247 @@ +" File: snipMate.vim +" Author: Michael Sanders +" Last Updated: July 13, 2009 +" Version: 0.83 +" Description: snipMate.vim implements some of TextMate's snippets features in +" Vim. A snippet is a piece of often-typed text that you can +" insert into your document using a trigger word followed by a "<tab>". +" +" For more help see snipMate.txt; you can do this by using: +" :helptags ~/.vim/doc +" :h snipMate.txt + +if exists('loaded_snips') || &cp || version < 700 + finish +endif +let loaded_snips = 1 +if !exists('snips_author') | let snips_author = 'Me' | endif + +au BufRead,BufNewFile *.snippets\= set ft=snippet +au FileType snippet setl noet fdm=indent + +let s:snippets = {} | let s:multi_snips = {} + +if !exists('snippets_dir') + let snippets_dir = substitute(globpath(&rtp, 'snippets/'), "\n", ',', 'g') +endif + +fun! MakeSnip(scope, trigger, content, ...) + let multisnip = a:0 && a:1 != '' + let var = multisnip ? 's:multi_snips' : 's:snippets' + if !has_key({var}, a:scope) | let {var}[a:scope] = {} | endif + if !has_key({var}[a:scope], a:trigger) + let {var}[a:scope][a:trigger] = multisnip ? [[a:1, a:content]] : a:content + elseif multisnip | let {var}[a:scope][a:trigger] += [[a:1, a:content]] + else + echom 'Warning in snipMate.vim: Snippet '.a:trigger.' is already defined.' + \ .' See :h multi_snip for help on snippets with multiple matches.' + endif +endf + +fun! ExtractSnips(dir, ft) + for path in split(globpath(a:dir, '*'), "\n") + if isdirectory(path) + let pathname = fnamemodify(path, ':t') + for snipFile in split(globpath(path, '*.snippet'), "\n") + call s:ProcessFile(snipFile, a:ft, pathname) + endfor + elseif fnamemodify(path, ':e') == 'snippet' + call s:ProcessFile(path, a:ft) + endif + endfor +endf + +" Processes a single-snippet file; optionally add the name of the parent +" directory for a snippet with multiple matches. +fun s:ProcessFile(file, ft, ...) + let keyword = fnamemodify(a:file, ':t:r') + if keyword == '' | return | endif + try + let text = join(readfile(a:file), "\n") + catch /E484/ + echom "Error in snipMate.vim: couldn't read file: ".a:file + endtry + return a:0 ? MakeSnip(a:ft, a:1, text, keyword) + \ : MakeSnip(a:ft, keyword, text) +endf + +fun! ExtractSnipsFile(file, ft) + if !filereadable(a:file) | return | endif + let text = readfile(a:file) + let inSnip = 0 + for line in text + ["\n"] + if inSnip && (line[0] == "\t" || line == '') + let content .= strpart(line, 1)."\n" + continue + elseif inSnip + call MakeSnip(a:ft, trigger, content[:-2], name) + let inSnip = 0 + endif + + if line[:6] == 'snippet' + let inSnip = 1 + let trigger = strpart(line, 8) + let name = '' + let space = stridx(trigger, ' ') + 1 + if space " Process multi snip + let name = strpart(trigger, space) + let trigger = strpart(trigger, 0, space - 1) + endif + let content = '' + endif + endfor +endf + +fun! ResetSnippets() + let s:snippets = {} | let s:multi_snips = {} | let g:did_ft = {} +endf + +let g:did_ft = {} +fun! GetSnippets(dir, filetypes) + for ft in split(a:filetypes, '\.') + if has_key(g:did_ft, ft) | continue | endif + call s:DefineSnips(a:dir, ft, ft) + if ft == 'objc' || ft == 'cpp' || ft == 'cs' + call s:DefineSnips(a:dir, 'c', ft) + elseif ft == 'xhtml' + call s:DefineSnips(a:dir, 'html', 'xhtml') + endif + let g:did_ft[ft] = 1 + endfor +endf + +" Define "aliasft" snippets for the filetype "realft". +fun s:DefineSnips(dir, aliasft, realft) + for path in split(globpath(a:dir, a:aliasft.'/')."\n". + \ globpath(a:dir, a:aliasft.'-*/'), "\n") + call ExtractSnips(path, a:realft) + endfor + for path in split(globpath(a:dir, a:aliasft.'.snippets')."\n". + \ globpath(a:dir, a:aliasft.'-*.snippets'), "\n") + call ExtractSnipsFile(path, a:realft) + endfor +endf + +fun! TriggerSnippet() + if exists('g:SuperTabMappingForward') + if g:SuperTabMappingForward == "<tab>" + let SuperTabKey = "\<c-n>" + elseif g:SuperTabMappingBackward == "<tab>" + let SuperTabKey = "\<c-p>" + endif + endif + + if pumvisible() " Update snippet if completion is used, or deal with supertab + if exists('SuperTabKey') + call feedkeys(SuperTabKey) | return '' + endif + call feedkeys("\<esc>a", 'n') " Close completion menu + call feedkeys("\<tab>") | return '' + endif + + if exists('g:snipPos') | return snipMate#jumpTabStop(0) | endif + + let word = matchstr(getline('.'), '\S\+\%'.col('.').'c') + for scope in [bufnr('%')] + split(&ft, '\.') + ['_'] + let [trigger, snippet] = s:GetSnippet(word, scope) + " If word is a trigger for a snippet, delete the trigger & expand + " the snippet. + if snippet != '' + let col = col('.') - len(trigger) + sil exe 's/\V'.escape(trigger, '/.').'\%#//' + return snipMate#expandSnip(snippet, col) + endif + endfor + + if exists('SuperTabKey') + call feedkeys(SuperTabKey) + return '' + endif + return "\<tab>" +endf + +fun! BackwardsSnippet() + if exists('g:snipPos') | return snipMate#jumpTabStop(1) | endif + + if exists('g:SuperTabMappingForward') + if g:SuperTabMappingBackward == "<s-tab>" + let SuperTabKey = "\<c-p>" + elseif g:SuperTabMappingForward == "<s-tab>" + let SuperTabKey = "\<c-n>" + endif + endif + if exists('SuperTabKey') + call feedkeys(SuperTabKey) + return '' + endif + return "\<s-tab>" +endf + +" Check if word under cursor is snippet trigger; if it isn't, try checking if +" the text after non-word characters is (e.g. check for "foo" in "bar.foo") +fun s:GetSnippet(word, scope) + let word = a:word | let snippet = '' + while snippet == '' + if exists('s:snippets["'.a:scope.'"]["'.escape(word, '\"').'"]') + let snippet = s:snippets[a:scope][word] + elseif exists('s:multi_snips["'.a:scope.'"]["'.escape(word, '\"').'"]') + let snippet = s:ChooseSnippet(a:scope, word) + if snippet == '' | break | endif + else + if match(word, '\W') == -1 | break | endif + let word = substitute(word, '.\{-}\W', '', '') + endif + endw + if word == '' && a:word != '.' && stridx(a:word, '.') != -1 + let [word, snippet] = s:GetSnippet('.', a:scope) + endif + return [word, snippet] +endf + +fun s:ChooseSnippet(scope, trigger) + let snippet = [] + let i = 1 + for snip in s:multi_snips[a:scope][a:trigger] + let snippet += [i.'. '.snip[0]] + let i += 1 + endfor + if i == 2 | return s:multi_snips[a:scope][a:trigger][0][1] | endif + let num = inputlist(snippet) - 1 + return num == -1 ? '' : s:multi_snips[a:scope][a:trigger][num][1] +endf + +fun! ShowAvailableSnips() + let line = getline('.') + let col = col('.') + let word = matchstr(getline('.'), '\S\+\%'.col.'c') + let words = [word] + if stridx(word, '.') + let words += split(word, '\.', 1) + endif + let matchlen = 0 + let matches = [] + for scope in [bufnr('%')] + split(&ft, '\.') + ['_'] + let triggers = has_key(s:snippets, scope) ? keys(s:snippets[scope]) : [] + if has_key(s:multi_snips, scope) + let triggers += keys(s:multi_snips[scope]) + endif + for trigger in triggers + for word in words + if word == '' + let matches += [trigger] " Show all matches if word is empty + elseif trigger =~ '^'.word + let matches += [trigger] + let len = len(word) + if len > matchlen | let matchlen = len | endif + endif + endfor + endfor + endfor + + " This is to avoid a bug with Vim when using complete(col - matchlen, matches) + " (Issue#46 on the Google Code snipMate issue tracker). + call setline(line('.'), substitute(line, repeat('.', matchlen).'\%'.col.'c', '', '')) + call complete(col, matches) + return '' +endf +" vim:noet:sw=4:ts=4:ft=vim Added: configs/trunk/src/vim/snippets/_.snippets =================================================================== --- configs/trunk/src/vim/snippets/_.snippets (rev 0) +++ configs/trunk/src/vim/snippets/_.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,7 @@ +# Global snippets + +# (c) holds no legal value ;) +snippet c) + `&enc[:2] == "utf" ? "©" : "(c)"` Copyright `strftime("%Y")` ${1:`g:snips_author`}. All Rights Reserved.${2} +snippet date + `strftime("%Y-%m-%d")` Added: configs/trunk/src/vim/snippets/autoit.snippets =================================================================== --- configs/trunk/src/vim/snippets/autoit.snippets (rev 0) +++ configs/trunk/src/vim/snippets/autoit.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,66 @@ +snippet if + If ${1:condition} Then + ${2:; True code} + EndIf +snippet el + Else + ${1} +snippet elif + ElseIf ${1:condition} Then + ${2:; True code} +# If/Else block +snippet ifel + If ${1:condition} Then + ${2:; True code} + Else + ${3:; Else code} + EndIf +# If/ElseIf/Else block +snippet ifelif + If ${1:condition 1} Then + ${2:; True code} + ElseIf ${3:condition 2} Then + ${4:; True code} + Else + ${5:; Else code} + EndIf +# Switch block +snippet switch + Switch (${1:condition}) + Case {$2:case1}: + {$3:; Case 1 code} + Case Else: + {$4:; Else code} + EndSwitch +# Select block +snippet select + Select (${1:condition}) + Case {$2:case1}: + {$3:; Case 1 code} + Case Else: + {$4:; Else code} + EndSelect +# While loop +snippet while + While (${1:condition}) + ${2:; code...} + WEnd +# For loop +snippet for + For ${1:n} = ${3:1} to ${2:count} + ${4:; code...} + Next +# New Function +snippet func + Func ${1:fname}(${2:`indent('.') ? 'self' : ''`}): + ${4:Return} + EndFunc +# Message box +snippet msg + MsgBox(${3:MsgType}, ${1:"Title"}, ${2:"Message Text"}) +# Debug Message +snippet debug + MsgBox(0, "Debug", ${1:"Debug Message"}) +# Show Variable Debug Message +snippet showvar + MsgBox(0, "${1:VarName}", $1) Added: configs/trunk/src/vim/snippets/c.snippets =================================================================== --- configs/trunk/src/vim/snippets/c.snippets (rev 0) +++ configs/trunk/src/vim/snippets/c.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,110 @@ +# main() +snippet main + int main(int argc, const char *argv[]) + { + ${1} + return 0; + } +# #include <...> +snippet inc + #include <${1:stdio}.h>${2} +# #include "..." +snippet Inc + #include "${1:`Filename("$1.h")`}"${2} +# #ifndef ... #define ... #endif +snippet Def + #ifndef $1 + #define ${1:SYMBOL} ${2:value} + #endif${3} +snippet def + #define +snippet ifdef + #ifdef ${1:FOO} + ${2:#define } + #endif +snippet #if + #if ${1:FOO} + ${2} + #endif +# Header Include-Guard +# (the randomizer code is taken directly from TextMate; it could probably be +# cleaner, I don't know how to do it in vim script) +snippet once + #ifndef ${1:`toupper(Filename('', 'UNTITLED').'_'.system("/usr/bin/ruby -e 'print (rand * 2821109907455).round.to_s(36)'"))`} + + #define $1 + + ${2} + + #endif /* end of include guard: $1 */ +# If Condition +snippet if + if (${1:/* condition */}) { + ${2:/* code */} + } +snippet el + else { + ${1} + } +# Tertiary conditional +snippet t + ${1:/* condition */} ? ${2:a} : ${3:b} +# Do While Loop +snippet do + do { + ${2:/* code */} + } while (${1:/* condition */}); +# While Loop +snippet wh + while (${1:/* condition */}) { + ${2:/* code */} + } +# For Loop +snippet for + for (${2:i} = 0; $2 < ${1:count}; $2${3:++}) { + ${4:/* code */} + } +# Custom For Loop +snippet forr + for (${1:i} = ${2:0}; ${3:$1 < 10}; $1${4:++}) { + ${5:/* code */} + } +# Function +snippet fun + ${1:void} ${2:function_name}(${3}) + { + ${4:/* code */} + } +# Function Declaration +snippet fund + ${1:void} ${2:function_name}(${3});${4} +# Typedef +snippet td + typedef ${1:int} ${2:MyCustomType};${3} +# Struct +snippet st + struct ${1:`Filename('$1_t', 'name')`} { + ${2:/* data */} + }${3: /* optional variable list */};${4} +# Typedef struct +snippet tds + typedef struct ${2:_$1 }{ + ${3:/* data */} + } ${1:`Filename('$1_t', 'name')`}; +# Typdef enum +snippet tde + typedef enum { + ${1:/* data */} + } ${2:foo}; +# printf +# unfortunately version this isn't as nice as TextMates's, given the lack of a +# dynamic `...` +snippet pr + printf("${1:%s}\n"${2});${3} +# fprintf (again, this isn't as nice as TextMate's version, but it works) +snippet fpr + fprintf(${1:stderr}, "${2:%s}\n"${3});${4} +snippet . + [${1}]${2} +snippet un + unsigned Added: configs/trunk/src/vim/snippets/cpp.snippets =================================================================== --- configs/trunk/src/vim/snippets/cpp.snippets (rev 0) +++ configs/trunk/src/vim/snippets/cpp.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,30 @@ +# Read File Into Vector +snippet readfile + std::vector<char> v; + if (FILE *${2:fp} = fopen(${1:"filename"}, "r")) { + char buf[1024]; + while (size_t len = fread(buf, 1, sizeof(buf), $2)) + v.insert(v.end(), buf, buf + len); + fclose($2); + }${3} +# std::map +snippet map + std::map<${1:key}, ${2:value}> map${3}; +# std::vector +snippet vector + std::vector<${1:char}> v${2}; +# Namespace +snippet ns + namespace ${1:`Filename('', 'my')`} { + ${2} + } /* $1 */ +# Class +snippet cl + class ${1:`Filename('$1_t', 'name')`} { + public: + $1 (${2:arguments}); + virtual ~$1 (); + + private: + ${3:/* data */} + }; Added: configs/trunk/src/vim/snippets/html.snippets =================================================================== --- configs/trunk/src/vim/snippets/html.snippets (rev 0) +++ configs/trunk/src/vim/snippets/html.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,190 @@ +# Some useful Unicode entities +# Non-Breaking Space +snippet nbs + +# ← +snippet left + ← +# → +snippet right + → +# ↑ +snippet up + ↑ +# ↓ +snippet down + ↓ +# ↩ +snippet return + ↩ +# ⇤ +snippet backtab + ⇤ +# ⇥ +snippet tab + ⇥ +# ⇧ +snippet shift + ⇧ +# ⌃ +snippet control + ⌃ +# ⌅ +snippet enter + ⌅ +# ⌘ +snippet command + ⌘ +# ⌥ +snippet option + ⌥ +# ⌦ +snippet delete + ⌦ +# ⌫ +snippet backspace + ⌫ +# ⎋ +snippet escape + ⎋ +# Generic Doctype +snippet doctype HTML 4.01 Strict + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" + "http://www.w3.org/TR/html4/strict.dtd"> +snippet doctype HTML 4.01 Transitional + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"" + "http://www.w3.org/TR/html4/loose.dtd"> +snippet doctype HTML 5 + <!DOCTYPE HTML> +snippet doctype XHTML 1.0 Frameset + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +snippet doctype XHTML 1.0 Strict + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +snippet doctype XHTML 1.0 Transitional + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +snippet doctype XHTML 1.1 + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" + "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> +# HTML Doctype 4.01 Strict +snippet docts + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" + "http://www.w3.org/TR/html4/strict.dtd"> +# HTML Doctype 4.01 Transitional +snippet doct + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"" + "http://www.w3.org/TR/html4/loose.dtd"> +# HTML Doctype 5 +snippet doct5 + <!DOCTYPE HTML> +# XHTML Doctype 1.0 Frameset +snippet docxf + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> +# XHTML Doctype 1.0 Strict +snippet docxs + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +# XHTML Doctype 1.0 Transitional +snippet docxt + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +# XHTML Doctype 1.1 +snippet docx + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" + "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> +snippet html + <html> + ${1} + </html> +snippet xhtml + <html xmlns="http://www.w3.org/1999/xhtml"> + ${1} + </html> +snippet body + <body> + ${1} + </body> +snippet head + <head> + <meta http-equiv="content-type" content="text/html; charset=utf-8"`Close()`> + + <title>${1:`substitute(Filename('', 'Page Title'), '^.', '\u&', '')`}</title> + ${2} + </head> +snippet title + <title>${1:`substitute(Filename('', 'Page Title'), '^.', '\u&', '')`}</title>${2} +snippet script + <script type="text/javascript" charset="utf-8"> + ${1} + </script>${2} +snippet scriptsrc + <script src="${1}.js" type="text/javascript" charset="utf-8"></script>${2} +snippet style + <style type="text/css" media="${1:screen}"> + ${2} + </style>${3} +snippet base + <base href="${1}" target="${2}"`Close()`> +snippet r + <br`Close()[1:]`> +snippet div + <div id="${1:name}"> + ${2} + </div> +# Embed QT Movie +snippet movie + <object width="$2" height="$3" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" + codebase="http://www.apple.com/qtactivex/qtplugin.cab"> + <param name="src" value="$1"`Close()`> + <param name="controller" value="$4"`Close()`> + <param name="autoplay" value="$5"`Close()`> + <embed src="${1:movie.mov}" + width="${2:320}" height="${3:240}" + controller="${4:true}" autoplay="${5:true}" + scale="tofit" cache="true" + pluginspage="http://www.apple.com/quicktime/download/" + `Close()[1:]`> + </object>${6} +snippet fieldset + <fieldset id="$1"> + <legend>${1:name}</legend> + + ${3} + </fieldset> +snippet form + <form action="${1:`Filename('$1_submit')`}" method="${2:get}" accept-charset="utf-8"> + ${3} + + + <p><input type="submit" value="Continue →"`Close()`></p> + </form> +snippet h1 + <h1 id="${1:heading}">${2:$1}</h1> +snippet input + <input type="${1:text/submit/hidden/button}" name="${2:some_name}" value="${3}"`Close()`>${4} +snippet label + <label for="${2:$1}">${1:name}</label><input type="${3:text/submit/hidden/button}" name="${4:$2}" value="${5}" id="${6:$2}"`Close()`>${7} +snippet link + <link rel="${1:stylesheet}" href="${2:/css/master.css}" type="text/css" media="${3:screen}" charset="utf-8"`Close()`>${4} +snippet mailto + <a href="mailto:${1:jo...@ex...}?subject=${2:feedback}">${3:email me}</a> +snippet meta + <meta name="${1:name}" content="${2:content}"`Close()`>${3} +snippet opt + <option value="${1:option}">${2:$1}</option>${3} +snippet optt + <option>${1:option}</option>${2} +snippet select + <select name="${1:some_name}" id="${2:$1}"> + <option value="${3:option}">${4:$3}</option> + </select>${5} +snippet table + <table border="${1:0}"> + <tr><th>${2:Header}</th></tr> + <tr><th>${3:Data}</th></tr> + </table>${4} +snippet textarea + <textarea name="${1:Name}" rows="${2:8}" cols="${3:40}">${4}</textarea>${5} Added: configs/trunk/src/vim/snippets/java.snippets =================================================================== --- configs/trunk/src/vim/snippets/java.snippets (rev 0) +++ configs/trunk/src/vim/snippets/java.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,78 @@ +snippet main + public static void main (String [] args) + { + ${1:/* code */} + } +snippet pu + public +snippet po + protected +snippet pr + private +snippet st + static +snippet fi + final +snippet ab + abstract +snippet re + return +snippet br + break; +snippet de + default: + ${1} +snippet ca + catch(${1:Exception} ${2:e}) ${3} +snippet th + throw +snippet sy + synchronized +snippet im + import +snippet j.u + java.util +snippet j.i + java.io. +snippet j.b + java.beans. +snippet j.n + java.net. +snippet j.m + java.math. +snippet if + if (${1}) ${2} +snippet el + else +snippet elif + else if (${1}) ${2} +snippet wh + while (${1}) ${2} +snippet for + for (${1}; ${2}; ${3}) ${4} +snippet fore + for (${1} : ${2}) ${3} +snippet sw + switch (${1}) ${2} +snippet cs + case ${1}: + ${2} + ${3} +snippet tc + public class ${1:`Filename()`} extends ${2:TestCase} +snippet t + public void test${1:Name}() throws Exception ${2} +snippet cl + class ${1:`Filename("", "untitled")`} ${2} +snippet in + interface ${1:`Filename("", "untitled")`} ${2:extends Parent}${3} +snippet m + ${1:void} ${2:method}(${3}) ${4:throws }${5} +snippet v + ${1:String} ${2:var}${3: = null}${4};${5} +snippet co + static public final ${1:String} ${2:var} = ${3};${4} +snippet cos + static public final String ${1:var} = "${2}";${3} +snippet as + assert ${1:test} : "${2:Failure message}";${3} Added: configs/trunk/src/vim/snippets/javascript.snippets =================================================================== --- configs/trunk/src/vim/snippets/javascript.snippets (rev 0) +++ configs/trunk/src/vim/snippets/javascript.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,74 @@ +# Prototype +snippet proto + ${1:class_name}.prototype.${2:method_name} = + function(${3:first_argument}) { + ${4:// body...} + }; +# Function +snippet fun + function ${1:function_name} (${2:argument}) { + ${3:// body...} + } +# Anonymous Function +snippet f + function(${1}) {${2}}; +# if +snippet if + if (${1:true}) {${2}}; +# if ... else +snippet ife + if (${1:true}) {${2}} + else{${3}}; +# tertiary conditional +snippet t + ${1:/* condition */} ? ${2:a} : ${3:b} +# switch +snippet switch + switch(${1:expression}) { + case '${3:case}': + ${4:// code} + break; + ${5} + default: + ${2:// code} + } +# case +snippet case + case '${1:case}': + ${2:// code} + break; + ${3} +# for (...) {...} +snippet for + for (var ${2:i} = 0; $2 < ${1:Things}.length; $2${3:++}) { + ${4:$1[$2]} + }; +# for (...) {...} (Improved Native For-Loop) +snippet forr + for (var ${2:i} = ${1:Things}.length - 1; $2 >= 0; $2${3:--}) { + ${4:$1[$2]} + }; +# while (...) {...} +snippet wh + while (${1:/* condition */}) { + ${2:/* code */} + } +# do...while +snippet do + do { + ${2:/* code */} + } while (${1:/* condition */}); +# Object Method +snippet :f + ${1:method_name}: function(${2:attribute}) { + ${4} + }${3:,} +# setTimeout function +snippet timeout + setTimeout(function() {${3}}${2}, ${1:10}; +# Get Elements +snippet get + getElementsBy${1:TagName}('${2}')${3} +# Get Element +snippet gett + getElementBy${1:Id}('${2}')${3} Added: configs/trunk/src/vim/snippets/mako.snippets =================================================================== --- configs/trunk/src/vim/snippets/mako.snippets (rev 0) +++ configs/trunk/src/vim/snippets/mako.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,54 @@ +snippet def + <%def name="${1:name}"> + ${2:} + </%def> +snippet call + <%call expr="${1:name}"> + ${2:} + </%call> +snippet doc + <%doc> + ${1:} + </%doc> +snippet text + <%text> + ${1:} + </%text> +snippet for + % for ${1:i} in ${2:iter}: + ${3:} + % endfor +snippet if if + % if ${1:condition}: + ${2:} + % endif +snippet if if/else + % if ${1:condition}: + ${2:} + % else: + ${3:} + % endif +snippet try + % try: + ${1:} + % except${2:}: + ${3:pass} + % endtry +snippet wh + % while ${1:}: + ${2:} + % endwhile +snippet $ + ${ ${1:} } +snippet <% + <% ${1:} %> +snippet <!% + <!% ${1:} %> +snippet inherit + <%inherit file="${1:filename}" /> +snippet include + <%include file="${1:filename}" /> +snippet namespace + <%namespace file="${1:name}" /> +snippet page + <%page args="${1:}" /> Added: configs/trunk/src/vim/snippets/objc.snippets =================================================================== --- configs/trunk/src/vim/snippets/objc.snippets (rev 0) +++ configs/trunk/src/vim/snippets/objc.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,184 @@ +# #import <...> +snippet Imp + #import <${1:Cocoa/Cocoa.h}>${2} +# #import "..." +snippet imp + #import "${1:`Filename()`.h}"${2} +# @selector(...) +snippet sel + @selector(${1:method}:)${3} +# @"..." string +snippet s + @"${1}"${2} +# Object +snippet o + ${1:NSObject} *${2:foo} = [${3:$1 alloc}]${4};${5} +# NSLog(...) +snippet log + NSLog(@"${1:%@}"${2});${3} +# Class +snippet objc + @interface ${1:`Filename('', 'someClass')`} : ${2:NSObject} + { + } + @end + + @implementation $1 + ${3} + @end +# Class Interface +snippet int + @interface ${1:`Filename('', 'someClass')`} : ${2:NSObject} + {${3} + } + ${4} + @end +# Class Implementation +snippet impl + @implementation ${1:`Filename('', 'someClass')`} + ${2} + @end +snippet init + - (id)init + { + [super init]; + return self; + } +snippet ifself + if (self = [super init]) { + ${1:/* code */} + } + return self; +snippet ibo + IBOutlet ${1:NSSomeClass} *${2:$1};${3} +# Category +snippet cat + @interface ${1:NSObject} (${2:Category}) + @end + + @implementation $1 ($2) + ${3} + @end +# Category Interface +snippet cath + @interface ${1:NSObject} (${2:Category}) + ${3} + @end +# NSArray +snippet array + NSMutableArray *${1:array} = [NSMutable array];${2} +# NSDictionary +snippet dict + NSMutableDictionary *${1:dict} = [NSMutableDictionary dictionary];${2} +# NSBezierPath +snippet bez + NSBezierPath *${1:path} = [NSBezierPath bezierPath];${2} +# Method +snippet m + - (${1:id})${2:method} + { + ${3} + } +# Method declaration +snippet md + - (${1:id})${2:method};${3} +# IBAction declaration +snippet ibad + - (IBAction)${1:method}:(${2:id})sender;${3} +# IBAction method +snippet iba + - (IBAction)${1:method}:(${2:id})sender + { + ${3} + } +# awakeFromNib method +snippet wake + - (void)awakeFromNib + { + ${1} + } +# Class Method +snippet M + + (${1:id})${2:method} + {${3} + return nil; + } +# Sub-method (Call super) +snippet sm + - (${1:id})${2:method} + { + [super $2];${3} + return self; + } +# Method: Initialize +snippet I + + (void) initialize + { + [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWIthObjectsAndKeys: + ${1}@"value", @"key", + nil]]; + } +# Accessor Methods For: +# Object +snippet objacc + - (${1:id})${2:thing} + { + return $2; + } + + - (void)set$2:($1)${3:new$2} + { + [$3 retain]; + [$2 release]; + $2 = $3; + }${4} +# for (object in array) +snippet forin + for (${1:Class} *${2:some$1} in ${3:array}) { + ${4} + } +snippet forarray + unsigned int ${1:object}Count = [${2:array} count]; + + for (unsigned int index = 0; index < $1Count; index++) { + ${3:id} $1 = [$2 $1AtIndex:index]; + ${4} + } +# IBOutlet +# @property (Objective-C 2.0) +snippet prop + @property (${1:retain}) ${2:NSSomeClass} ${3:*$2};${4} +# @synthesize (Objective-C 2.0) +snippet syn + @synthesize ${1:property};${2} +# [[ alloc] init] +snippet alloc + [[${1:foo} alloc] init${2}];${3} +# retain +snippet ret + [${1:foo} retain];${2} +# release +snippet rel + [${1:foo} release]; + ${2:$1 = nil;} +# autorelease +snippet arel + [${1:foo} autorelease]; +# autorelease pool +snippet pool + NSAutoreleasePool *${1:pool} = [[NSAutoreleasePool alloc] init]; + ${2:/* code */} + [$1 drain]; +# Throw an exception +snippet except + NSException *${1:badness}; + $1 = [NSException exceptionWithName:@"${2:$1Name}" + reason:@"${3}" + userInfo:nil]; + [$1 raise]; +snippet prag + #pragma mark ${1:foo} +snippet cl + @class ${1:Foo};${2} +snippet color + [[NSColor ${1:blackColor}] set]; Added: configs/trunk/src/vim/snippets/perl.snippets =================================================================== --- configs/trunk/src/vim/snippets/perl.snippets (rev 0) +++ configs/trunk/src/vim/snippets/perl.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,91 @@ +# #!/usr/bin/perl +snippet #! + #!/usr/bin/perl + +# Hash Pointer +snippet . + => +# Function +snippet sub + sub ${1:function_name} { + ${2:#body ...} + } +# Conditional +snippet if + if (${1}) { + ${2:# body...} + } +# Conditional if..else +snippet ife + if (${1}) { + ${2:# body...} + } else { + ${3:# else...} + } +# Conditional if..elsif..else +snippet ifee + if (${1}) { + ${2:# body...} + } elsif (${3}) { + ${4:# elsif...} + } else { + ${5:# else...} + } +# Conditional One-line +snippet xif + ${1:expression} if ${2:condition};${3} +# Unless conditional +snippet unless + unless (${1}) { + ${2:# body...} + } +# Unless conditional One-line +snippet xunless + ${1:expression} unless ${2:condition};${3} +# Try/Except +snippet eval + eval { + ${1:# do something risky...} + }; + if ($@) { + ${2:# handle failure...} + } +# While Loop +snippet wh + while (${1}) { + ${2:# body...} + } +# While Loop One-line +snippet xwh + ${1:expression} while ${2:condition};${3} +# For Loop +snippet for + for (my $${2:var} = 0; $$2 < ${1:count}; $$2${3:++}) { + ${4:# body...} + } +# Foreach Loop +snippet fore + foreach my $${1:x} (@${2:array}) { + ${3:# body...} + } +# Foreach Loop One-line +snippet xfore + ${1:expression} foreach @${2:array};${3} +# Package +snippet cl + package ${1:ClassName}; + + use base qw(${2:ParentClass}); + + sub new { + my $class = shift; + $class = ref $class if ref $class; + my $self = bless {}, $class; + $self; + } + + 1;${3} +# Read File +snippet slurp + my $${1:var}; + { local $/ = undef; local *FILE; open FILE, "<${2:file}"; $$1 = <FILE>; close FILE }${3} Added: configs/trunk/src/vim/snippets/php.snippets =================================================================== --- configs/trunk/src/vim/snippets/php.snippets (rev 0) +++ configs/trunk/src/vim/snippets/php.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,216 @@ +snippet php + <?php + ${1} + ?> +snippet ec + echo "${1:string}"${2}; +snippet inc + include '${1:file}';${2} +snippet inc1 + include_once '${1:file}';${2} +snippet req + require '${1:file}';${2} +snippet req1 + require_once '${1:file}';${2} +# $GLOBALS['...'] +snippet globals + $GLOBALS['${1:variable}']${2: = }${3:something}${4:;}${5} +snippet $_ COOKIE['...'] + $_COOKIE['${1:variable}']${2} +snippet $_ ENV['...'] + $_ENV['${1:variable}']${2} +snippet $_ FILES['...'] + $_FILES['${1:variable}']${2} +snippet $_ Get['...'] + $_GET['${1:variable}']${2} +snippet $_ POST['...'] + $_POST['${1:variable}']${2} +snippet $_ REQUEST['...'] + $_REQUEST['${1:variable}']${2} +snippet $_ SERVER['...'] + $_SERVER['${1:variable}']${2} +snippet $_ SESSION['...'] + $_SESSION['${1:variable}']${2} +# Start Docblock +snippet /* + /** + * ${1} + **/ +# Class - post doc +snippet doc_cp + /** + * ${1:undocumented class} + * + * @package ${2:default} + * @author ${3:`g:snips_author`} + **/${4} +# Class Variable - post doc +snippet doc_vp + /** + * ${1:undocumented class variable} + * + * @var ${2:string} + **/${3} +# Class Variable +snippet doc_v + /** + * ${3:undocumented class variable} + * + * @var ${4:string} + **/ + ${1:var} $${2};${5} +# Class +snippet doc_c + /** + * ${3:undocumented class} + * + * @packaged ${4:default} + * @author ${5:`g:snips_author`} + **/ + ${1:}class ${2:} + {${6} + } // END $1class $2 +# Constant Definition - post doc +snippet doc_dp + /** + * ${1:undocumented constant} + **/${2} +# Constant Definition +snippet doc_d + /** + * ${3:undocumented constant} + **/ + define(${1}, ${2});${4} +# Function - post doc +snippet doc_fp + /** + * ${1:undocumented function} + * + * @return ${2:void} + * @author ${3:`g:snips_author`} + **/${4} +# Function signature +snippet doc_s + /** + * ${4:undocumented function} + * + * @return ${5:void} + * @author ${6:`g:snips_author`} + **/ + ${1}function ${2}(${3});${7} +# Function +snippet doc_f + /** + * ${4:undocumented function} + * + * @return ${5:void} + * @author ${6:`g:snips_author`} + **/ + ${1}function ${2}(${3}) + {${7} + } +# Header +snippet doc_h + /** + * ${1} + * + * @author ${2:`g:snips_author`} + * @version ${3:$Id$} + * @copyright ${4:$2}, `strftime('%d %B, %Y')` + * @package ${5:default} + **/ + + /** + * Define DocBlock + *// +# Interface +snippet doc_i + /** + * ${2:undocumented class} + * + * @package ${3:default} + * @author ${4:`g:snips_author`} + **/ + interface ${1:} + {${5} + } // END interface $1 +# class ... +snippet class + /** + * ${1} + **/ + class ${2:ClassName} + { + ${3} + function ${4:__construct}(${5:argument}) + { + ${6:// code...} + } + } +# define(...) +snippet def + define('${1}'${2});${3} +# defined(...) +snippet def? + ${1}defined('${2}')${3} +snippet wh + while (${1:/* condition */}) { + ${2:// code...} + } +# do ... while +snippet do + do { + ${2:// code... } + } while (${1:/* condition */}); +snippet if + if (${1:/* condition */}) { + ${2:// code...} + } +snippet ife + if (${1:/* condition */}) { + ${2:// code...} + } else { + ${3:// code...} + } + ${4} +snippet else + else { + ${1:// code...} + } +snippet elseif + elseif (${1:/* condition */}) { + ${2:// code...} + } +# Tertiary conditional +snippet t + $${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};${5} +snippet switch + switch ($${1:variable}) { + case '${2:value}': + ${3:// code...} + break; + ${5} + default: + ${4:// code...} + break; + } +snippet case + case '${1:value}': + ${2:// code...} + break;${3} +snippet for + for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) { + ${4: // code...} + } +snippet foreach + foreach ($${1:variable} as $${2:key}) { + ${3:// code...} + } +snippet fun + ${1:public }function ${2:FunctionName}(${3}) + { + ${4:// code...} + } +# $... = array (...) +snippet array + $${1:arrayName} = array('${2}' => ${3});${4} Added: configs/trunk/src/vim/snippets/python.snippets =================================================================== --- configs/trunk/src/vim/snippets/python.snippets (rev 0) +++ configs/trunk/src/vim/snippets/python.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,86 @@ +snippet #! + #!/usr/bin/python + +snippet imp + import ${1:module} +# Module Docstring +snippet docs + ''' + File: ${1:`Filename('$1.py', 'foo.py')`} + Author: ${2:`g:snips_author`} + Description: ${3} + ''' +snippet wh + while ${1:condition}: + ${2:# code...} +snippet for + for ${1:needle} in ${2:haystack}: + ${3:# code...} +# New Class +snippet cl + class ${1:ClassName}(${2:object}): + """${3:docstring for $1}""" + def __init__(self, ${4:arg}): + ${5:super($1, self).__init__()} + self.$4 = $4 + ${6} +# New Function +snippet def + def ${1:fname}(${2:`indent('.') ? 'self' : ''`}): + """${3:docstring for $1}""" + ${4:pass} +snippet deff + def ${1:fname}(${2:`indent('.') ? 'self' : ''`}): + ${3} +# New Method +snippet defs + def ${1:mname}(self, ${2:arg}): + ${3:pass} +# New Property +snippet property + def ${1:foo}(): + doc = "${2:The $1 property.}" + def fget(self): + ${3:return self._$1} + def fset(self, value): + ${4:self._$1 = value} +# Lambda +snippet ld + ${1:var} = lambda ${2:vars} : ${3:action} +snippet . + self. +snippet try Try/Except + try: + ${1:pass} + except ${2:Exception}, ${3:e}: + ${4:raise $3} +snippet try Try/Except/Else + try: + ${1:pass} + except ${2:Exception}, ${3:e}: + ${4:raise $3} + else: + ${5:pass} +snippet try Try/Except/Finally + try: + ${1:pass} + except ${2:Exception}, ${3:e}: + ${4:raise $3} + finally: + ${5:pass} +snippet try Try/Except/Else/Finally + try: + ${1:pass} + except ${2:Exception}, ${3:e}: + ${4:raise $3} + else: + ${5:pass} + finally: + ${6:pass} +# if __name__ == '__main__': +snippet ifmain + if __name__ == '__main__': + ${1:main()} +# __magic__ +snippet _ + __${1:init}__${2} Added: configs/trunk/src/vim/snippets/ruby.snippets =================================================================== --- configs/trunk/src/vim/snippets/ruby.snippets (rev 0) +++ configs/trunk/src/vim/snippets/ruby.snippets 2010-01-25 03:39:43 UTC (rev 1551) @@ -0,0 +1,420 @@ +# #!/usr/bin/ruby +snippet #! + #!/usr/bin/ruby + +# New Block +snippet =b + =begin rdoc + ${1} + =end +snippet y + :yields: ${1:arguments} +snippet rb + #!/usr/bin/env ruby -wKU + +snippet req + require "${1}"${2} +snippet # + # => +snippet end + __END__ +snippet case + case ${1:object} + when ${2:condition} + ${3} + end +snippet when + when ${1:condition} + ${2} +snippet def + def ${1:method_name} + ${2} + end +snippet deft + def test_${1:case_name} + ${2} + end +snippet if + if ${1:condition} + ${2} + end +snippet ife + if ${1:condition} + ${2} + else + ${3} + end +snippet elsif + elsif ${1:condition} + ${2} +snippet unless + unless ${1:condition} + ${2} + end +snippet while + while ${1:condition} + ${2} + end +snippet until + until ${1:condition} + ${2} + end +snippet cla class .. end + class ${1:`substitute(Filename(), '^.', '\u&', '')`} + ${2} + end +snippet cla class .. initialize .. end + class ${1:`substitute(Filename(), '^.', '\u&', '')`} + def initialize(${2:args}) + ${3} + end + + + end +snippet cla class .. < ParentClass .. initialize .. end + class ${1:`substitute(Filename(), '^.', '\u&', '')`} < ${2:ParentClass} + def initialize(${3:args}) + ${4} + end + + + end +snippet cla ClassName = Struct .. do .. end + ${1:`substitute(Filename(), '^.', '\u&', '')`} = Struct.new(:${2:attr_names}) do + def ${3:method_name} + ${4} + end + + + end +snippet cla class BlankSlate .. initialize .. end + class ${1:BlankSlate} + instance_methods.each { |meth| undef_method(meth) unless meth =~ /\A__/ } +snippet cla class << self .. end + class << ${1:self} + ${2} + end +# class .. < DelegateClass .. initialize .. end +snippet cla- + class ${1:`substitute(Filename(), '^.', '\u&', '')`} < DelegateClass(${2:ParentClass}) + def initialize(${3:args}) + super(${4:del_obj}) + + ${5} + end + + + end +snippet mod module .. end + module ${1:`substitute(Filename(), '^.', '\u&', '')`} + ${2} + end +snippet mod module .. module_function .. end + module ${1:`substitute(Filename(), '^.', '\u&', '')`} + module_function + + ${2} + end +snippet mod module .. ClassMethods .. end + module ${1:`substitute(Filename(), '^.', '\u&', '')`} + module ClassMethods + ${2} + end + + module InstanceMethods + + end + + def self.included(receiver) + receiver.extend ClassMethods + receiver.send :include, InstanceMethods + end + end +# attr_reader +snippet r + attr_reader :${1:attr_names} +# attr_writer +snippet w + attr_writer :${1:attr_names} +# attr_accessor +snippet rw + attr_accessor :${1:attr_names} +# include Enumerable +snippet Enum + include Enumerable + + def each(&block) + ${1} + end +# include Comparable +snippet Comp + include Comparable + + def <=>(other) + ${1} + end +# extend Forwardable +snippet Forw- + extend Forwardable +# def self +snippet defs + def self.${1:class_method_name} + ${2} + end +# def method_missing +snippet defmm + def method_missing(meth, *args, &blk) + ${1} + end +snippet defd + def_delegator :${1:@del_obj}, :${2:del_meth}, :${3:new_name} +snippet defds + def_delegators :${1:@del_obj}, :${2:del_methods} +snippet am + alias_method :${1:new_name}, :${2:old_name} +snippet app + if __FILE__ == $PROGRAM_NAME + ${1} + end +# usage_if() +snippet usai + if ARGV.${1} + abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${3} + end +# usage_unless() +snippet usau + unless ARGV.${1} + abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${3} + end +snippet array + Array.new(${1:10}) { |${2:i}| ${3} } +snippet hash + Hash.new { |${1:hash}, ${2:key}| $1[$2] = ${3} } +snippet file File.foreach() { |line| .. } + File.foreach(${1:"path/to/file"}) { |${2:line}| ${3} } +snippet file File.read() + File.read(${1:"path/to/file"})${2} +snippet Dir Dir.global() { |file| .. } + Dir.glob(${1:"dir/glob/*"}) { |${2:file}| ${3} } +snippet Dir Dir[".."] + Dir[${1:"glob/**/*.rb"}]${2} +snippet dir + Filename.dirname(__FILE__) +snippet deli + delete_if { |${1:e}| ${2} } +snippet fil + fill(${1:range}) { |${2:i}| ${3} } +# flatten_once() +snippet flao + inject(Array.new) { |${1:arr}, ${2:a}| $1.push(*$2)}${3} +snippet zip + zip(${1:enums}) { |${2:row}| ${3} } +# downto(0) { |n| .. } +snippet dow + downto(${1:0}) { |${2:n}| ${3} } +snippet ste + step(${1:2}) { |${2:n}| ${3} } +snippet tim + times { |${1:n}| ${2} } +snippet upt + upto(${1:1.0/0.0}) { |${2:n}| ${3} } +snippet loo + loop { ${1} } +snippet ea + each { |${1:e}| ${2} } +snippet eab + each_byte { |${1:byte}| ${2} } +snippet eac- each_char { |chr| .. } + each_char { |${1:chr}| ${2} } +snippet eac- each_cons(..) { |group| .. } + each_cons(${1:2}) { |${2:group}| ${3} } +snippet eai + each_index { |${1:i}| ${2} } +snippet eak + each_key { |${1:key}| ${2} } +snippet eal + each_line { |${1:line}| ${2} } +snippet eap + each_pair { |${1:name}, ${2:val}| ${3} } +snippet eas- + each_slice(${1:2}) { |${2:group}| ${3} } +snippet eav + each_value { |${1:val}| ${2} } +snippet eawi + each_with_index { |${1:e}, ${2:i}| ${3} } +snippet reve + reverse_each { |${1:e}| ${2} } +snippet inj + inject(${1:init}) { |${2:mem}, ${3:var}| ${4} } +snippet map + map { |${1:e}| ${2} } +snippet mapwi- + enum_with_index.map { |${1:e}, ${2:i}| ${3} } +snippet sor + sort { |a, b| ${1} } +snippet sorb + sort_by { |${1:e}| ${2} } +snippet ran + sort_by { rand } +snippet all + all? { |${1:e}| ${2} } +snippet any + any? { |${1:e}| ${2} } +snippet cl + classify { |${1:e}| ${2} } +snippet col + collect { |${1:e}| ${2} } +snippet det + detect { |${1:e}| ${2} } +snippet fet + fetch(${1:name}) { |${2:key}| ${3} } +snippet fin + find { |${1:e}| ${2} } +snippet fina + find_all { |${1:e}| ${2} } +snippet gre + grep(${1:/pattern/}) { |${2:match}| ${3} } +snippet sub + ${1:g}sub(${2:/pattern/}) { |${3:match}| ${4} } +snippet sca + scan(${1:/pattern/}) { |${2:match}| ${3} } +snippet max + max { |a, b|, ${1} } +snippet min + min { |a, b|, ${1} } +snippet par + partition { |${1:e}|, ${2} } +snippet rej + reject { |${1:e}|, ${2} } +snippet sel + select { |${1:e}|, ${2} } +snippet lam + lambda { |${1:args}| ${2} } +snippet do + do |${1:variable}| + ${2} + end +snippet : + :${1:key} => ${2:"value"}${3} +snippet ope + open(${1:"path/or/url/or/pipe"}, "${2:w}") { |${3:io}| ${4} } +# path_from_here() +snippet patfh + File.join(File.dirname(__FILE__), *%2[${1:rel path here}])${2} +# unix_filter {} +snippet unif + ARGF.each_line${1} do |${2:line}| + ${3} + end +# opti... [truncated message content] |
From: <yan...@us...> - 2010-01-25 03:44:58
|
Revision: 1555 http://assorted.svn.sourceforge.net/assorted/?rev=1555&view=rev Author: yangzhang Date: 2010-01-25 03:44:49 +0000 (Mon, 25 Jan 2010) Log Message: ----------- added surround.vim Added Paths: ----------- configs/trunk/src/vim/doc/surround.txt configs/trunk/src/vim/plugin/surround.vim Added: configs/trunk/src/vim/doc/surround.txt =================================================================== --- configs/trunk/src/vim/doc/surround.txt (rev 0) +++ configs/trunk/src/vim/doc/surround.txt 2010-01-25 03:44:49 UTC (rev 1555) @@ -0,0 +1,218 @@ +*surround.txt* Plugin for deleting, changing, and adding "surroundings" + +Author: Tim Pope <vim...@tp...> *surround-author* +License: Same terms as Vim itself (see |license|) + +This plugin is only available if 'compatible' is not set. + +INTRODUCTION *surround* + +This plugin is a tool for dealing with pairs of "surroundings." Examples +of surroundings include parentheses, quotes, and HTML tags. They are +closely related to what Vim refers to as |text-objects|. Provided +are mappings to allow for removing, changing, and adding surroundings. + +Details follow on the exact semantics, but first, consider the following +examples. An asterisk (*) is used to denote the cursor position. + + Old text Command New text ~ + "Hello *world!" ds" Hello world! + [123+4*56]/2 cs]) (123+456)/2 + "Look ma, I'm *HTML!" cs"<q> <q>Look ma, I'm HTML!</q> + if *x>3 { ysW( if ( x>3 ) { + my $str = *whee!; vlllls' my $str = 'whee!'; + +While a few features of this plugin will work in older versions of Vim, +Vim 7 is recommended for full functionality. + +MAPPINGS *surround-mappings* + +Delete surroundings is *ds* . The next character given determines the target +to delete. The exact nature of the target are explained in |surround-targets| +but essentially it is the last character of a |text-object|. This mapping +deletes the difference between the "inner" object and "an" object. This is +easiest to understand with some examples: + + Old text Command New text ~ + "Hello *world!" ds" Hello world! + (123+4*56)/2 ds) 123+456/2 + <div>Yo!*</div> dst Yo! + +Change surroundings is *cs* . It takes two arguments, a target like with +|ds|, and a replacement. Details about the second argument can be found +below in |surround-replacements|. Once again, examples are in order. + + Old text Command New text ~ + "Hello *world!" cs"' 'Hello world!' + "Hello *world!" cs"<q> <q>Hello world!</q> + (123+4*56)/2 cs)] [123+456]/2 + (123+4*56)/2 cs)[ [ 123+456 ]/2 + <div>Yo!*</div> cst<p> <p>Yo!</p> + +*ys* takes an valid Vim motion or text object as the first object, and wraps +it using the second argument as with |cs|. (Unfortunately there's no good +mnemonic for "ys".) + + Old text Command New text ~ + Hello w*orld! ysiw) Hello (world)! + +As a special case, *yss* operates on the current line, ignoring leading +whitespace. + + Old text Command New text ~ + Hello w*orld! yssB {Hello world!} + +There is also *yS* and *ySS* which indent the surrounded text and place it +on a line of its own. + +In visual mode, a simple "s" with an argument wraps the selection. This is +referred to as the *vs* mapping, although ordinarily there will be +additional keystrokes between the v and s. In linewise visual mode, the +surroundings are placed on separate lines. In blockwise visual mode, each +line is surrounded. + +An "S" in visual mode (*vS*) behaves similarly but always places the +surroundings on separate lines. Additionally, the surrounded text is +indented. In blockwise visual mode, using "S" instead of "s" instead skips +trailing whitespace. + +Note that "s" and "S" already have valid meaning in visual mode, but it is +identical to "c". If you have muscle memory for "s" and would like to use a +different key, add your own mapping and the existing one will be disabled. +> + vmap <Leader>s <Plug>Vsurround + vmap <Leader>S <Plug>VSurround +< + *i_CTRL-G_s* *i_CTRL-G_S* +Finally, there is an experimental insert mode mapping on <C-G>s and <C-S>. +Beware that the latter won't work on terminals with flow control (if you +accidentally freeze your terminal, use <C-Q> to unfreeze it). The mapping +inserts the specified surroundings and puts the cursor between them. If, +immediately after the mapping and before the replacement, a second <C-S> or +carriage return is pressed, the prefix, cursor, and suffix will be placed on +three separate lines. <C-G>S (not <C-G>s) also exhibits this behavior. + +TARGETS *surround-targets* + +The |ds| and |cs| commands both take a target as their first argument. The +possible targets are based closely on the |text-objects| provided by Vim. +In order for a target to work, the corresponding text object must be +supported in the version of Vim used (Vim 7 adds several text objects, and +thus is highly recommended). All targets are currently just one character. + +Eight punctuation marks, (, ), {, }, [, ], <, and >, represent themselves +and their counterpart. If the opening mark is used, contained whitespace is +also trimmed. The targets b, B, r, and a are aliases for ), }, ], and > +(the first two mirror Vim; the second two are completely arbitrary and +subject to change). + +Three quote marks, ', ", `, represent themselves, in pairs. They are only +searched for on the current line. + +A t is a pair of HTML or XML tags. See |tag-blocks| for details. Remember +that you can specify a numerical argument if you want to get to a tag other +than the innermost one. + +The letters w, W, and s correspond to a |word|, a |WORD|, and a |sentence|, +respectively. These are special in that they have nothing to delete, and +used with |ds| they are a no-op. With |cs|, one could consider them a +slight shortcut for ysi (cswb == ysiwb, more or less). + +A p represents a |paragraph|. This behaves similarly to w, W, and s above; +however, newlines are sometimes added and/or removed. + +REPLACEMENTS *surround-replacements* + +A replacement argument is a single character, and is required by |cs|, |ys|, +and |vs|. Undefined replacement characters (with the exception of alphabetic +characters) default to placing themselves at the beginning and end of the +destination, which can be useful for characters like / and |. + +If either ), }, ], or > is used, the text is wrapped in the appropriate pair +of characters. Similar behavior can be found with (, {, and [ (but not <), +which append an additional space to the inside. Like with the targets above, +b, B, r, and a are aliases for ), }, ], and >. To fulfill the common need for +code blocks in C-style languages, <C-}> (which is really <C-]>) adds braces on +lines separate from the content. + +If t or < is used, Vim prompts for an HTML/XML tag to insert. You may specify +attributes here and they will be stripped from the closing tag. End your +input by pressing <CR> or >. If <C-T> is used, the tags will appear on lines +by themselves. + +A deprecated replacement of a LaTeX environment is provided on \ and l. The +name of the environment and any arguments will be input from a prompt. This +will be removed once a more fully functional customization system is +implemented. The following shows the resulting environment from +csp\tabular}{lc<CR> +> + \begin{tabular}{lc} + \end{tabular} +< +CUSTOMIZING *surround-customizing* + +The following adds a potential replacement on "-" (ASCII 45) in PHP files. +(To determine the ASCII code to use, :echo char2nr("-")). The carriage +return will be replaced by the original text. +> + autocmd FileType php let b:surround_45 = "<?php \r ?>" +< +This can be used in a PHP file as in the following example. + + Old text Command New text ~ + print "Hello *world!" yss- <?php print "Hello world!" ?> + +Additionally, one can use a global variable for globally available +replacements. +> + let g:surround_45 = "<% \r %>" + let g:surround_61 = "<%= \r %>" +< +Advanced, experimental, and subject to change: One can also prompt for +replacement text. The syntax for this is to surround the replacement in pairs +of low numbered control characters. If this sounds confusing, that's because +it is (but it makes the parsing easy). Consider the following example for a +LaTeX environment on the "l" replacement. +> + let g:surround_108 = "\\begin{\1environment: \1}\r\\end{\1\1}" +< +When this replacement is used, the user is prompted with an "environment: " +prompt for input. This input is inserted between each set of \1's. +Additional inputs up to \7 can be used. + +Furthermore, one can specify a regular expression substitution to apply. +> + let g:surround_108 = "\\begin{\1environment: \1}\r\\end{\1\r}.*\r\1}" +< +This will remove anything after the first } in the input when the text is +placed within the \end{} slot. The first \r marks where the pattern begins, +and the second where the replacement text begins. + +Here's a second example for creating an HTML <div>. The substitution cleverly +prompts for an id, but only adds id="" if it is non-blank. You may have to +read this one a few times slowly before you understand it. +> + let g:surround_{char2nr("d")} = "<div\1id: \r..*\r id=\"&\"\1>\r</div>" +< +Inputting text replacements is a proof of concept at this point. The ugly, +unintuitive interface and the brevity of the documentation reflect this. + +Finally, It is possible to always append a string to surroundings in insert +mode (and only insert mode). This is useful with certain plugins and mappings +that allow you to jump to such markings. +> + let g:surround_insert_tail = "<++>" +< +ISSUES *surround-issues* + +Vim could potentially get confused when deleting/changing occurs at the very +end of the line. Please report any repeatable instances of this. + +Do we need to use |inputsave()|/|inputrestore()| with the tag replacement? + +Indenting is handled haphazardly. Need to decide the most appropriate +behavior and implement it. Right now one can do :let b:surround_indent = 1 +(or the global equivalent) to enable automatic re-indenting by Vim via |=|; +should this be the default? + + vim:tw=78:ts=8:ft=help:norl: Added: configs/trunk/src/vim/plugin/surround.vim =================================================================== --- configs/trunk/src/vim/plugin/surround.vim (rev 0) +++ configs/trunk/src/vim/plugin/surround.vim 2010-01-25 03:44:49 UTC (rev 1555) @@ -0,0 +1,628 @@ +" surround.vim - Surroundings +" Author: Tim Pope <vim...@tp...> +" GetLatestVimScripts: 1697 1 :AutoInstall: surround.vim +" $Id: surround.vim,v 1.34 2008-02-15 21:43:42 tpope Exp $ +" +" See surround.txt for help. This can be accessed by doing +" +" :helptags ~/.vim/doc +" :help surround +" +" Licensed under the same terms as Vim itself. + +" ============================================================================ + +" Exit quickly when: +" - this plugin was already loaded or disabled +" - when 'compatible' is set +if (exists("g:loaded_surround") && g:loaded_surround) || &cp + finish +endif +let g:loaded_surround = 1 + +let s:cpo_save = &cpo +set cpo&vim + +" Input functions {{{1 + +function! s:getchar() + let c = getchar() + if c =~ '^\d\+$' + let c = nr2char(c) + endif + return c +endfunction + +function! s:inputtarget() + let c = s:getchar() + while c =~ '^\d\+$' + let c = c . s:getchar() + endwhile + if c == " " + let c = c . s:getchar() + endif + if c =~ "\<Esc>\|\<C-C>\|\0" + return "" + else + return c + endif +endfunction + +function! s:inputreplacement() + "echo '-- SURROUND --' + let c = s:getchar() + if c == " " + let c = c . s:getchar() + endif + if c =~ "\<Esc>" || c =~ "\<C-C>" + return "" + else + return c + endif +endfunction + +function! s:beep() + exe "norm! \<Esc>" + return "" +endfunction + +function! s:redraw() + redraw + return "" +endfunction + +" }}}1 + +" Wrapping functions {{{1 + +function! s:extractbefore(str) + if a:str =~ '\r' + return matchstr(a:str,'.*\ze\r') + else + return matchstr(a:str,'.*\ze\n') + endif +endfunction + +function! s:extractafter(str) + if a:str =~ '\r' + return matchstr(a:str,'\r\zs.*') + else + return matchstr(a:str,'\n\zs.*') + endif +endfunction + +function! s:repeat(str,count) + let cnt = a:count + let str = "" + while cnt > 0 + let str = str . a:str + let cnt = cnt - 1 + endwhile + return str +endfunction + +function! s:fixindent(str,spc) + let str = substitute(a:str,'\t',s:repeat(' ',&sw),'g') + let spc = substitute(a:spc,'\t',s:repeat(' ',&sw),'g') + let str = substitute(str,'\(\n\|\%^\).\@=','\1'.spc,'g') + if ! &et + let str = substitute(str,'\s\{'.&ts.'\}',"\t",'g') + endif + return str +endfunction + +function! s:process(string) + let i = 0 + while i < 7 + let i = i + 1 + let repl_{i} = '' + let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i)) + if m != '' + let m = substitute(strpart(m,1),'\r.*','','') + let repl_{i} = input(substitute(m,':\s*$','','').': ') + endif + endwhile + let s = "" + let i = 0 + while i < strlen(a:string) + let char = strpart(a:string,i,1) + if char2nr(char) < 8 + let next = stridx(a:string,char,i+1) + if next == -1 + let s = s . char + else + let insertion = repl_{char2nr(char)} + let subs = strpart(a:string,i+1,next-i-1) + let subs = matchstr(subs,'\r.*') + while subs =~ '^\r.*\r' + let sub = matchstr(subs,"^\r\\zs[^\r]*\r[^\r]*") + let subs = strpart(subs,strlen(sub)+1) + let r = stridx(sub,"\r") + let insertion = substitute(insertion,strpart(sub,0,r),strpart(sub,r+1),'') + endwhile + let s = s . insertion + let i = next + endif + else + let s = s . char + endif + let i = i + 1 + endwhile + return s +endfunction + +function! s:wrap(string,char,type,...) + let keeper = a:string + let newchar = a:char + let type = a:type + let linemode = type ==# 'V' ? 1 : 0 + let special = a:0 ? a:1 : 0 + let before = "" + let after = "" + if type == "V" + let initspaces = matchstr(keeper,'\%^\s*') + else + let initspaces = matchstr(getline('.'),'\%^\s*') + endif + " Duplicate b's are just placeholders (removed) + let pairs = "b()B{}r[]a<>" + let extraspace = "" + if newchar =~ '^ ' + let newchar = strpart(newchar,1) + let extraspace = ' ' + endif + let idx = stridx(pairs,newchar) + if newchar == ' ' + let before = '' + let after = '' + elseif exists("b:surround_".char2nr(newchar)) + let all = s:process(b:surround_{char2nr(newchar)}) + let before = s:extractbefore(all) + let after = s:extractafter(all) + elseif exists("g:surround_".char2nr(newchar)) + let all = s:process(g:surround_{char2nr(newchar)}) + let before = s:extractbefore(all) + let after = s:extractafter(all) + elseif newchar ==# "p" + let before = "\n" + let after = "\n\n" + elseif newchar =~# "[tT\<C-T><,]" + let dounmapp = 0 + let dounmapb = 0 + if !maparg(">","c") + let dounmapb= 1 + " Hide from AsNeeded + exe "cn"."oremap > <CR>" + exe "cn"."oremap % %<C-V>" + "cm ap > <C-R>=getcmdline() =~ '^[^%?].*[%?]$' ? "\026\076" : "\026\076\015"<CR> + endif + let default = "" + if !maparg("%","c") + " This is to help when typing things like + " <a href="/images/<%= @image.filename %>"> + " The downside is it breaks backspace, so lets disable it for now + "let dounmapp= 1 + "exe "cn"."oremap % %<C-V>" + endif + if newchar ==# "T" + if !exists("s:lastdel") + let s:lastdel = "" + endif + let default = matchstr(s:lastdel,'<\zs.\{-\}\ze>') + endif + let tag = input("<",default) + echo "<".substitute(tag,'>*$','>','') + "if dounmapr + "silent! cunmap <CR> + "endif + if dounmapb + silent! cunmap > + endif + if dounmapp + silent! cunmap % + endif + if tag != "" + let tag = substitute(tag,'>*$','','') + let before = '<'.tag.'>' + if tag =~ '/$' + let after = '' + else + let after = '</'.substitute(tag,' .*','','').'>' + endif + if newchar == "\<C-T>" || newchar == "," + if type ==# "v" || type ==# "V" + let before = before . "\n\t" + endif + if type ==# "v" + let after = "\n". after + endif + endif + endif + elseif newchar ==# 'l' || newchar == '\' + " LaTeX + let env = input('\begin{') + let env = '{' . env + let env = env . s:closematch(env) + echo '\begin'.env + if env != "" + let before = '\begin'.env + let after = '\end'.matchstr(env,'[^}]*').'}' + endif + "if type ==# 'v' || type ==# 'V' + "let before = before ."\n\t" + "endif + "if type ==# 'v' + "let after = "\n".initspaces.after + "endif + elseif newchar ==# 'f' || newchar ==# 'F' + let fnc = input('function: ') + if fnc != "" + let before = substitute(fnc,'($','','').'(' + let after = ')' + if newchar ==# 'F' + let before = before . ' ' + let after = ' ' . after + endif + endif + elseif idx >= 0 + let spc = (idx % 3) == 1 ? " " : "" + let idx = idx / 3 * 3 + let before = strpart(pairs,idx+1,1) . spc + let after = spc . strpart(pairs,idx+2,1) + elseif newchar == "\<C-[>" || newchar == "\<C-]>" + let before = "{\n\t" + let after = "\n}" + elseif newchar !~ '\a' + let before = newchar + let after = newchar + else + let before = '' + let after = '' + endif + "let before = substitute(before,'\n','\n'.initspaces,'g') + let after = substitute(after ,'\n','\n'.initspaces,'g') + "let after = substitute(after,"\n\\s*\<C-U>\\s*",'\n','g') + if type ==# 'V' || (special && type ==# "v") + let before = substitute(before,' \+$','','') + let after = substitute(after ,'^ \+','','') + if after !~ '^\n' + let after = initspaces.after + endif + if keeper !~ '\n$' && after !~ '^\n' + let keeper = keeper . "\n" + elseif keeper =~ '\n$' && after =~ '^\n' + let after = strpart(after,1) + endif + if before !~ '\n\s*$' + let before = before . "\n" + if special + let before = before . "\t" + endif + endif + endif + if type ==# 'V' + let before = initspaces.before + endif + if before =~ '\n\s*\%$' + if type ==# 'v' + let keeper = initspaces.keeper + endif + let padding = matchstr(before,'\n\zs\s\+\%$') + let before = substitute(before,'\n\s\+\%$','\n','') + let keeper = s:fixindent(keeper,padding) + endif + if type ==# 'V' + let keeper = before.keeper.after + elseif type =~ "^\<C-V>" + " Really we should be iterating over the buffer + let repl = substitute(before,'[\\~]','\\&','g').'\1'.substitute(after,'[\\~]','\\&','g') + let repl = substitute(repl,'\n',' ','g') + let keeper = substitute(keeper."\n",'\(.\{-\}\)\('.(special ? '\s\{-\}' : '').'\n\)',repl.'\n','g') + let keeper = substitute(keeper,'\n\%$','','') + else + let keeper = before.extraspace.keeper.extraspace.after + endif + return keeper +endfunction + +function! s:wrapreg(reg,char,...) + let orig = getreg(a:reg) + let type = substitute(getregtype(a:reg),'\d\+$','','') + let special = a:0 ? a:1 : 0 + let new = s:wrap(orig,a:char,type,special) + call setreg(a:reg,new,type) +endfunction +" }}}1 + +function! s:insert(...) " {{{1 + " Optional argument causes the result to appear on 3 lines, not 1 + "call inputsave() + let linemode = a:0 ? a:1 : 0 + let char = s:inputreplacement() + while char == "\<CR>" || char == "\<C-S>" + " TODO: use total count for additional blank lines + let linemode = linemode + 1 + let char = s:inputreplacement() + endwhile + "call inputrestore() + if char == "" + return "" + endif + "call inputsave() + let cb_save = &clipboard + let reg_save = @@ + call setreg('"',"\r",'v') + call s:wrapreg('"',char,linemode) + " If line mode is used and the surrounding consists solely of a suffix, + " remove the initial newline. This fits a use case of mine but is a + " little inconsistent. Is there anyone that would prefer the simpler + " behavior of just inserting the newline? + if linemode && match(getreg('"'),'^\n\s*\zs.*') == 0 + call setreg('"',matchstr(getreg('"'),'^\n\s*\zs.*'),getregtype('"')) + endif + " This can be used to append a placeholder to the end + if exists("g:surround_insert_tail") + call setreg('"',g:surround_insert_tail,"a".getregtype('"')) + endif + "if linemode + "call setreg('"',substitute(getreg('"'),'^\s\+','',''),'c') + "endif + if col('.') >= col('$') + norm! ""p + else + norm! ""P + endif + if linemode + call s:reindent() + endif + norm! `] + call search('\r','bW') + let @@ = reg_save + let &clipboard = cb_save + return "\<Del>" +endfunction " }}}1 + +function! s:reindent() " {{{1 + if exists("b:surround_indent") ? b:surround_indent : (exists("g:surround_indent") && g:surround_indent) + silent norm! '[='] + endif +endfunction " }}}1 + +function! s:dosurround(...) " {{{1 + let scount = v:count1 + let char = (a:0 ? a:1 : s:inputtarget()) + let spc = "" + if char =~ '^\d\+' + let scount = scount * matchstr(char,'^\d\+') + let char = substitute(char,'^\d\+','','') + endif + if char =~ '^ ' + let char = strpart(char,1) + let spc = 1 + endif + if char == 'a' + let char = '>' + endif + if char == 'r' + let char = ']' + endif + let newchar = "" + if a:0 > 1 + let newchar = a:2 + if newchar == "\<Esc>" || newchar == "\<C-C>" || newchar == "" + return s:beep() + endif + endif + let cb_save = &clipboard + set clipboard-=unnamed + let append = "" + let original = getreg('"') + let otype = getregtype('"') + call setreg('"',"") + let strcount = (scount == 1 ? "" : scount) + if char == '/' + exe 'norm '.strcount.'[/d'.strcount.']/' + else + exe 'norm d'.strcount.'i'.char + endif + let keeper = getreg('"') + let okeeper = keeper " for reindent below + if keeper == "" + call setreg('"',original,otype) + let &clipboard = cb_save + return "" + endif + let oldline = getline('.') + let oldlnum = line('.') + if char ==# "p" + call setreg('"','','V') + elseif char ==# "s" || char ==# "w" || char ==# "W" + " Do nothing + call setreg('"','') + elseif char =~ "[\"'`]" + exe "norm! i \<Esc>d2i".char + call setreg('"',substitute(getreg('"'),' ','','')) + elseif char == '/' + norm! "_x + call setreg('"','/**/',"c") + let keeper = substitute(substitute(keeper,'^/\*\s\=','',''),'\s\=\*$','','') + else + " One character backwards + call search('.','bW') + exe "norm da".char + endif + let removed = getreg('"') + let rem2 = substitute(removed,'\n.*','','') + let oldhead = strpart(oldline,0,strlen(oldline)-strlen(rem2)) + let oldtail = strpart(oldline, strlen(oldline)-strlen(rem2)) + let regtype = getregtype('"') + if char =~# '[\[({<T]' || spc + let keeper = substitute(keeper,'^\s\+','','') + let keeper = substitute(keeper,'\s\+$','','') + endif + if col("']") == col("$") && col('.') + 1 == col('$') + if oldhead =~# '^\s*$' && a:0 < 2 + let keeper = substitute(keeper,'\%^\n'.oldhead.'\(\s*.\{-\}\)\n\s*\%$','\1','') + endif + let pcmd = "p" + else + let pcmd = "P" + endif + if line('.') < oldlnum && regtype ==# "V" + let pcmd = "p" + endif + call setreg('"',keeper,regtype) + if newchar != "" + call s:wrapreg('"',newchar) + endif + silent exe 'norm! ""'.pcmd.'`[' + if removed =~ '\n' || okeeper =~ '\n' || getreg('"') =~ '\n' + call s:reindent() + endif + if getline('.') =~ '^\s\+$' && keeper =~ '^\s*\n' + silent norm! cc + endif + call setreg('"',removed,regtype) + let s:lastdel = removed + let &clipboard = cb_save + if newchar == "" + silent! call repeat#set("\<Plug>Dsurround".char,scount) + else + silent! call repeat#set("\<Plug>Csurround".char.newchar,scount) + endif +endfunction " }}}1 + +function! s:changesurround() " {{{1 + let a = s:inputtarget() + if a == "" + return s:beep() + endif + let b = s:inputreplacement() + if b == "" + return s:beep() + endif + call s:dosurround(a,b) +endfunction " }}}1 + +function! s:opfunc(type,...) " {{{1 + let char = s:inputreplacement() + if char == "" + return s:beep() + endif + let reg = '"' + let sel_save = &selection + let &selection = "inclusive" + let cb_save = &clipboard + set clipboard-=unnamed + let reg_save = getreg(reg) + let reg_type = getregtype(reg) + "call setreg(reg,"\n","c") + let type = a:type + if a:type == "char" + silent exe 'norm! v`[o`]"'.reg.'y' + let type = 'v' + elseif a:type == "line" + silent exe 'norm! `[V`]"'.reg.'y' + let type = 'V' + elseif a:type ==# "v" || a:type ==# "V" || a:type ==# "\<C-V>" + silent exe 'norm! gv"'.reg.'y' + elseif a:type =~ '^\d\+$' + let type = 'v' + silent exe 'norm! ^v'.a:type.'$h"'.reg.'y' + if mode() == 'v' + norm! v + return s:beep() + endif + else + let &selection = sel_save + let &clipboard = cb_save + return s:beep() + endif + let keeper = getreg(reg) + if type == "v" && a:type != "v" + let append = matchstr(keeper,'\_s\@<!\s*$') + let keeper = substitute(keeper,'\_s\@<!\s*$','','') + endif + call setreg(reg,keeper,type) + call s:wrapreg(reg,char,a:0) + if type == "v" && a:type != "v" && append != "" + call setreg(reg,append,"ac") + endif + silent exe 'norm! gv'.(reg == '"' ? '' : '"' . reg).'p`[' + if type == 'V' || (getreg(reg) =~ '\n' && type == 'v') + call s:reindent() + endif + call setreg(reg,reg_save,reg_type) + let &selection = sel_save + let &clipboard = cb_save + if a:type =~ '^\d\+$' + silent! call repeat#set("\<Plug>Y".(a:0 ? "S" : "s")."surround".char,a:type) + endif +endfunction + +function! s:opfunc2(arg) + call s:opfunc(a:arg,1) +endfunction " }}}1 + +function! s:closematch(str) " {{{1 + " Close an open (, {, [, or < on the command line. + let tail = matchstr(a:str,'.[^\[\](){}<>]*$') + if tail =~ '^\[.\+' + return "]" + elseif tail =~ '^(.\+' + return ")" + elseif tail =~ '^{.\+' + return "}" + elseif tail =~ '^<.+' + return ">" + else + return "" + endif +endfunction " }}}1 + +nnoremap <silent> <Plug>Dsurround :<C-U>call <SID>dosurround(<SID>inputtarget())<CR> +nnoremap <silent> <Plug>Csurround :<C-U>call <SID>changesurround()<CR> +nnoremap <silent> <Plug>Yssurround :<C-U>call <SID>opfunc(v:count1)<CR> +nnoremap <silent> <Plug>YSsurround :<C-U>call <SID>opfunc2(v:count1)<CR> +" <C-U> discards the numerical argument but there's not much we can do with it +nnoremap <silent> <Plug>Ysurround :<C-U>set opfunc=<SID>opfunc<CR>g@ +nnoremap <silent> <Plug>YSurround :<C-U>set opfunc=<SID>opfunc2<CR>g@ +vnoremap <silent> <Plug>Vsurround :<C-U>call <SID>opfunc(visualmode())<CR> +vnoremap <silent> <Plug>VSurround :<C-U>call <SID>opfunc2(visualmode())<CR> +inoremap <silent> <Plug>Isurround <C-R>=<SID>insert()<CR> +inoremap <silent> <Plug>ISurround <C-R>=<SID>insert(1)<CR> + +if !exists("g:surround_no_mappings") || ! g:surround_no_mappings + nmap ds <Plug>Dsurround + nmap cs <Plug>Csurround + nmap ys <Plug>Ysurround + nmap yS <Plug>YSurround + nmap yss <Plug>Yssurround + nmap ySs <Plug>YSsurround + nmap ySS <Plug>YSsurround + if !hasmapto("<Plug>Vsurround","v") + if exists(":xmap") + xmap s <Plug>Vsurround + else + vmap s <Plug>Vsurround + endif + endif + if !hasmapto("<Plug>VSurround","v") + if exists(":xmap") + xmap S <Plug>VSurround + else + vmap S <Plug>VSurround + endif + endif + if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i") + imap <C-S> <Plug>Isurround + endif + imap <C-G>s <Plug>Isurround + imap <C-G>S <Plug>ISurround + "Implemented internally instead + "imap <C-S><C-S> <Plug>ISurround +endif + +let &cpo = s:cpo_save + +" vim:set ft=vim sw=4 sts=4 et: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-12-06 08:13:20
|
Revision: 1727 http://assorted.svn.sourceforge.net/assorted/?rev=1727&view=rev Author: yangzhang Date: 2010-12-06 08:13:13 +0000 (Mon, 06 Dec 2010) Log Message: ----------- Added unimpaired.vim Added Paths: ----------- configs/trunk/src/vim/doc/unimpaired.txt configs/trunk/src/vim/plugin/unimpaired.vim Added: configs/trunk/src/vim/doc/unimpaired.txt =================================================================== --- configs/trunk/src/vim/doc/unimpaired.txt (rev 0) +++ configs/trunk/src/vim/doc/unimpaired.txt 2010-12-06 08:13:13 UTC (rev 1727) @@ -0,0 +1,101 @@ +*unimpaired.txt* Pairs of handy bracket mappings + +Author: Tim Pope <vim...@tp...> *unimpaired-author* +License: Same terms as Vim itself (see |license|) + +This plugin is only available if 'compatible' is not set. + +INTRODUCTION *unimpaired* + +This plugin provides several pairs of bracket maps. + +NEXT AND PREVIOUS *unimpaired-next* + +The following maps all correspond to normal mode commands. If a count is +given, it becomes an argument to the command. A mnemonic for the "a" commands +is "args" and for the "q" commands is "quickfix". + +*[a* |:previous| +*]a* |:next| +*[A* |:first| +*]A* |:last| +*[b* |:bprevious| +*]b* |:bnext| +*[B* |:bfirst| +*]B* |:blast| +*[l* |:lprevious| +*]l* |:lnext| +*[L* |:lfirst| +*]L* |:llast| +*[q* |:cprevious| +*]q* |:cnext| +*[Q* |:cfirst| +*]Q* |:clast| + + *[o* +[o Go to the file preceding the current one + alphabetically in the current file's directory. + + *]o* +]o Go to the file succeeding the current one + alphabetically in the current file's directory. + +LINE OPERATIONS *unimpaired-lines* + + *[<Space>* +[<Space> Add [count] blank lines above the cursor. + + *]<Space>* +]<Space> Add [count] blank lines below the cursor. + + *[e* *v_[e* +[e Exchange the current line with [count] lines above it. + + *]e* *v_]e* +]e Exchange the current line with [count] lines below it. + +ENCODING AND DECODING *unimpaired-encoding* + +Each of these operations has a map that takes a motion, a map that +targets [count] lines, and a visual mode map. The linewise variant integrates +with repeat.vim. + +Mnenomic: encoding always comes before decoding; "[" always comes before "]". + + *[x* *[xx* *v_[x* +[x{motion} XML encode. +[xx <foo bar="baz"> => <foo bar="baz"> +{Visual}[x + + *]x* *]xx* *v_]x* +]x{motion} XML decode. HTML entities are handled as well. +]xx +{Visual}]x + + *[u* *[uu* *v_[u* +[u{motion} URL encode. +[uu foo bar => foo%20bar +{Visual}[u + + *]u* *]uu* *v_]u* +]u{motion} URL decode. +]uu +{Visual}]u + + *[y* *[yy* *v_[y* +[y{motion} C String encode. Backslash escape control +[yy characters, quotation marks, and backslashes. +{Visual}[y + + *]y* *]yy* *v_]y* +]y{motion} C String decode. +]yy +{Visual}]y + +TODO *unimpaired-todo* + +Descend into and ascend from directories with |[o| and |]o|. + +Avoid munging null characters when encoding and decoding. + + vim:tw=78:et:ft=help:norl: Added: configs/trunk/src/vim/plugin/unimpaired.vim =================================================================== --- configs/trunk/src/vim/plugin/unimpaired.vim (rev 0) +++ configs/trunk/src/vim/plugin/unimpaired.vim 2010-12-06 08:13:13 UTC (rev 1727) @@ -0,0 +1,260 @@ +" unimpaired.vim - Pairs of handy bracket mappings +" Maintainer: Tim Pope <vim...@tp...> +" Version: 1.1 + +if exists("g:loaded_unimpaired") || &cp || v:version < 700 + finish +endif +let g:loaded_unimpaired = 1 + +let s:cpo_save = &cpo +set cpo&vim + +" Next and previous {{{1 + +function! s:MapNextFamily(map,cmd) + let map = '<Plug>unimpaired'.toupper(a:map) + let end = ' ".(v:count ? v:count : "")<CR>' + execute 'nmap <silent> '.map.'Previous :<C-U>exe "'.a:cmd.'previous'.end + execute 'nmap <silent> '.map.'Next :<C-U>exe "'.a:cmd.'next'.end + execute 'nmap <silent> '.map.'First :<C-U>exe "'.a:cmd.'first'.end + execute 'nmap <silent> '.map.'Last :<C-U>exe "'.a:cmd.'last'.end + execute 'nmap <silent> ['. a:map .' '.map.'Previous' + execute 'nmap <silent> ]'. a:map .' '.map.'Next' + execute 'nmap <silent> ['.toupper(a:map).' '.map.'First' + execute 'nmap <silent> ]'.toupper(a:map).' '.map.'Last' +endfunction + +call s:MapNextFamily('a','') +call s:MapNextFamily('b','b') +call s:MapNextFamily('l','l') +call s:MapNextFamily('q','c') + +function! s:FileByOffset(num) + let original = expand("%") + if a:num == 0 + return original + endif + let dir = fnamemodify(original,':h') + if dir == '.' + let dir = '' + elseif dir != '' + let dir .= '/' + endif + let files = split(glob(dir.".*"),"\n") + let files += split(glob(dir."*"),"\n") + call filter(files,'v:val !=# "." && v:val !=# ".."') + call filter(files,'v:val[-4:-1] !=# ".swp" && v:val[-1:-1] !=# "~"') + if a:num < 0 + call reverse(sort(filter(files,'v:val < original'))) + else + call sort(filter(files,'v:val > original')) + end + let num = a:num < 0 ? -a:num : a:num + let file = get(files,num-1,get(files,-1,original)) + return file +endfunction + +nnoremap <silent> <Plug>unimpairedONext :<C-U>edit `=<SID>FileByOffset(v:count1)`<CR> +nnoremap <silent> <Plug>unimpairedOPrevious :<C-U>edit `=<SID>FileByOffset(-v:count1)`<CR> + +nmap ]o <Plug>unimpairedONext +nmap [o <Plug>unimpairedOPrevious + +" }}}1 +" Line operations {{{1 + +nnoremap <silent> <Plug>unimpairedBlankUp :<C-U>put!=repeat(nr2char(10),v:count)<Bar>']+1<CR> +nnoremap <silent> <Plug>unimpairedBlankDown :<C-U>put =repeat(nr2char(10),v:count)<Bar>'[-1<CR> + +nmap [<Space> <Plug>unimpairedBlankUp +nmap ]<Space> <Plug>unimpairedBlankDown + +nnoremap <silent> <Plug>unimpairedMoveUp :<C-U>exe 'norm m`'<Bar>exe 'move--'.v:count1<CR>`` +nnoremap <silent> <Plug>unimpairedMoveDown :<C-U>exe 'norm m`'<Bar>exe 'move+'.v:count1<CR>`` +xnoremap <silent> <Plug>unimpairedMoveUp :<C-U>exe 'norm m`'<Bar>exe '''<,''>move--'.v:count1<CR>`` +xnoremap <silent> <Plug>unimpairedMoveDown :<C-U>exe 'norm m`'<Bar>exe '''<,''>move''>+'.v:count1<CR>`` + +nmap [e <Plug>unimpairedMoveUp +nmap ]e <Plug>unimpairedMoveDown +xmap [e <Plug>unimpairedMoveUp +xmap ]e <Plug>unimpairedMoveDown + +" }}}1 +" Encoding and decoding {{{1 + +function! s:StringEncode(str) + let map = {"\n": 'n', "\r": 'r', "\t": 't', "\b": 'b', "\f": '\f', '"': '"', '\': '\'} + return substitute(a:str,"[\001-\033\\\\\"]",'\="\\".get(map,submatch(0),printf("%03o",char2nr(submatch(0))))','g') +endfunction + +function! s:StringDecode(str) + let map = {'n': "\n", 'r': "\r", 't': "\t", 'b': "\b", 'f': "\f", 'e': "\e", 'a': "\001", 'v': "\013", '"': '"', '\': '\', "'": "'"} + let str = a:str + if str =~ '^\s*".\{-\}\\\@<!\%(\\\\\)*"\s*\n\=$' + let str = substitute(substitute(str,'^\s*\zs"','',''),'"\ze\s*\n\=$','','') + endif + let str = substitute(str,'\\n\%(\n$\)\=','\n','g') + return substitute(str,'\\\(\o\{1,3\}\|x\x\{1,2\}\|u\x\{1,4\}\|.\)','\=get(map,submatch(1),nr2char("0".substitute(submatch(1),"^[Uu]","x","")))','g') +endfunction + +function! s:UrlEncode(str) + return substitute(a:str,'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g') +endfunction + +function! s:UrlDecode(str) + let str = substitute(substitute(substitute(a:str,'%0[Aa]\n$','%0A',''),'%0[Aa]','\n','g'),'+',' ','g') + return substitute(str,'%\(\x\x\)','\=nr2char("0x".submatch(1))','g') +endfunction + +" HTML entities {{{2 + +let g:unimpaired_html_entities = { + \ 'nbsp': 160, 'iexcl': 161, 'cent': 162, 'pound': 163, + \ 'curren': 164, 'yen': 165, 'brvbar': 166, 'sect': 167, + \ 'uml': 168, 'copy': 169, 'ordf': 170, 'laquo': 171, + \ 'not': 172, 'shy': 173, 'reg': 174, 'macr': 175, + \ 'deg': 176, 'plusmn': 177, 'sup2': 178, 'sup3': 179, + \ 'acute': 180, 'micro': 181, 'para': 182, 'middot': 183, + \ 'cedil': 184, 'sup1': 185, 'ordm': 186, 'raquo': 187, + \ 'frac14': 188, 'frac12': 189, 'frac34': 190, 'iquest': 191, + \ 'Agrave': 192, 'Aacute': 193, 'Acirc': 194, 'Atilde': 195, + \ 'Auml': 196, 'Aring': 197, 'AElig': 198, 'Ccedil': 199, + \ 'Egrave': 200, 'Eacute': 201, 'Ecirc': 202, 'Euml': 203, + \ 'Igrave': 204, 'Iacute': 205, 'Icirc': 206, 'Iuml': 207, + \ 'ETH': 208, 'Ntilde': 209, 'Ograve': 210, 'Oacute': 211, + \ 'Ocirc': 212, 'Otilde': 213, 'Ouml': 214, 'times': 215, + \ 'Oslash': 216, 'Ugrave': 217, 'Uacute': 218, 'Ucirc': 219, + \ 'Uuml': 220, 'Yacute': 221, 'THORN': 222, 'szlig': 223, + \ 'agrave': 224, 'aacute': 225, 'acirc': 226, 'atilde': 227, + \ 'auml': 228, 'aring': 229, 'aelig': 230, 'ccedil': 231, + \ 'egrave': 232, 'eacute': 233, 'ecirc': 234, 'euml': 235, + \ 'igrave': 236, 'iacute': 237, 'icirc': 238, 'iuml': 239, + \ 'eth': 240, 'ntilde': 241, 'ograve': 242, 'oacute': 243, + \ 'ocirc': 244, 'otilde': 245, 'ouml': 246, 'divide': 247, + \ 'oslash': 248, 'ugrave': 249, 'uacute': 250, 'ucirc': 251, + \ 'uuml': 252, 'yacute': 253, 'thorn': 254, 'yuml': 255, + \ 'OElig': 338, 'oelig': 339, 'Scaron': 352, 'scaron': 353, + \ 'Yuml': 376, 'circ': 710, 'tilde': 732, 'ensp': 8194, + \ 'emsp': 8195, 'thinsp': 8201, 'zwnj': 8204, 'zwj': 8205, + \ 'lrm': 8206, 'rlm': 8207, 'ndash': 8211, 'mdash': 8212, + \ 'lsquo': 8216, 'rsquo': 8217, 'sbquo': 8218, 'ldquo': 8220, + \ 'rdquo': 8221, 'bdquo': 8222, 'dagger': 8224, 'Dagger': 8225, + \ 'permil': 8240, 'lsaquo': 8249, 'rsaquo': 8250, 'euro': 8364, + \ 'fnof': 402, 'Alpha': 913, 'Beta': 914, 'Gamma': 915, + \ 'Delta': 916, 'Epsilon': 917, 'Zeta': 918, 'Eta': 919, + \ 'Theta': 920, 'Iota': 921, 'Kappa': 922, 'Lambda': 923, + \ 'Mu': 924, 'Nu': 925, 'Xi': 926, 'Omicron': 927, + \ 'Pi': 928, 'Rho': 929, 'Sigma': 931, 'Tau': 932, + \ 'Upsilon': 933, 'Phi': 934, 'Chi': 935, 'Psi': 936, + \ 'Omega': 937, 'alpha': 945, 'beta': 946, 'gamma': 947, + \ 'delta': 948, 'epsilon': 949, 'zeta': 950, 'eta': 951, + \ 'theta': 952, 'iota': 953, 'kappa': 954, 'lambda': 955, + \ 'mu': 956, 'nu': 957, 'xi': 958, 'omicron': 959, + \ 'pi': 960, 'rho': 961, 'sigmaf': 962, 'sigma': 963, + \ 'tau': 964, 'upsilon': 965, 'phi': 966, 'chi': 967, + \ 'psi': 968, 'omega': 969, 'thetasym': 977, 'upsih': 978, + \ 'piv': 982, 'bull': 8226, 'hellip': 8230, 'prime': 8242, + \ 'Prime': 8243, 'oline': 8254, 'frasl': 8260, 'weierp': 8472, + \ 'image': 8465, 'real': 8476, 'trade': 8482, 'alefsym': 8501, + \ 'larr': 8592, 'uarr': 8593, 'rarr': 8594, 'darr': 8595, + \ 'harr': 8596, 'crarr': 8629, 'lArr': 8656, 'uArr': 8657, + \ 'rArr': 8658, 'dArr': 8659, 'hArr': 8660, 'forall': 8704, + \ 'part': 8706, 'exist': 8707, 'empty': 8709, 'nabla': 8711, + \ 'isin': 8712, 'notin': 8713, 'ni': 8715, 'prod': 8719, + \ 'sum': 8721, 'minus': 8722, 'lowast': 8727, 'radic': 8730, + \ 'prop': 8733, 'infin': 8734, 'ang': 8736, 'and': 8743, + \ 'or': 8744, 'cap': 8745, 'cup': 8746, 'int': 8747, + \ 'there4': 8756, 'sim': 8764, 'cong': 8773, 'asymp': 8776, + \ 'ne': 8800, 'equiv': 8801, 'le': 8804, 'ge': 8805, + \ 'sub': 8834, 'sup': 8835, 'nsub': 8836, 'sube': 8838, + \ 'supe': 8839, 'oplus': 8853, 'otimes': 8855, 'perp': 8869, + \ 'sdot': 8901, 'lceil': 8968, 'rceil': 8969, 'lfloor': 8970, + \ 'rfloor': 8971, 'lang': 9001, 'rang': 9002, 'loz': 9674, + \ 'spades': 9824, 'clubs': 9827, 'hearts': 9829, 'diams': 9830, + \ 'apos': 39} + +" }}}2 + +function! s:XmlEncode(str) + let str = a:str + let str = substitute(str,'&','\&','g') + let str = substitute(str,'<','\<','g') + let str = substitute(str,'>','\>','g') + let str = substitute(str,'"','\"','g') + return str +endfunction + +function! s:XmlEntityDecode(str) + let str = substitute(a:str,'\c&#\%(0*38\|x0*26\);','&','g') + let str = substitute(str,'\c&#\(\d\+\);','\=nr2char(submatch(1))','g') + let str = substitute(str,'\c&#\(x\x\+\);','\=nr2char("0".submatch(1))','g') + let str = substitute(str,'\c'',"'",'g') + let str = substitute(str,'\c"','"','g') + let str = substitute(str,'\c>','>','g') + let str = substitute(str,'\c<','<','g') + let str = substitute(str,'\C&\(\%(amp;\)\@!\w*\);','\=nr2char(get(g:unimpaired_html_entities,submatch(1),63))','g') + return substitute(str,'\c&','\&','g') +endfunction + +function! s:XmlDecode(str) + let str = substitute(a:str,'<\%([[:alnum:]-]\+=\%("[^"]*"\|''[^'']*''\)\|.\)\{-\}>','','g') + return s:XmlEntityDecode(str) +endfunction + +function! s:Transform(algorithm,type) + let sel_save = &selection + let cb_save = &clipboard + set selection=inclusive clipboard-=unnamed + let reg_save = @@ + if a:type =~ '^\d\+$' + silent exe 'norm! ^v'.a:type.'$hy' + elseif a:type =~ '^.$' + silent exe "normal! `<" . a:type . "`>y" + elseif a:type == 'line' + silent exe "normal! '[V']y" + elseif a:type == 'block' + silent exe "normal! `[\<C-V>`]y" + else + silent exe "normal! `[v`]y" + endif + let @@ = s:{a:algorithm}(@@) + norm! gvp + let @@ = reg_save + let &selection = sel_save + let &clipboard = cb_save + if a:type =~ '^\d\+$' + silent! call repeat#set("\<Plug>unimpairedLine".a:algorithm,a:type) + endif +endfunction + +function! s:TransformOpfunc(type) + return s:Transform(s:encode_algorithm, a:type) +endfunction + +function! s:TransformSetup(algorithm) + let s:encode_algorithm = a:algorithm + let &opfunc = matchstr(expand('<sfile>'), '<SNR>\d\+_').'TransformOpfunc' +endfunction + +function! s:MapTransform(algorithm, key) + exe 'nnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>TransformSetup("'.a:algorithm.'")<CR>g@' + exe 'xnoremap <silent> <Plug>unimpaired' .a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",visualmode())<CR>' + exe 'nnoremap <silent> <Plug>unimpairedLine'.a:algorithm.' :<C-U>call <SID>Transform("'.a:algorithm.'",v:count1)<CR>' + exe 'nmap '.a:key.' <Plug>unimpaired'.a:algorithm + exe 'xmap '.a:key.' <Plug>unimpaired'.a:algorithm + exe 'nmap '.a:key.a:key[strlen(a:key)-1].' <Plug>unimpairedLine'.a:algorithm +endfunction + +call s:MapTransform('StringEncode','[y') +call s:MapTransform('StringDecode',']y') +call s:MapTransform('UrlEncode','[u') +call s:MapTransform('UrlDecode',']u') +call s:MapTransform('XmlEncode','[x') +call s:MapTransform('XmlDecode',']x') + +" }}}1 + +let &cpo = s:cpo_save + +" vim:set ft=vim ts=8 sw=2 sts=2: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-12-06 08:14:51
|
Revision: 1728 http://assorted.svn.sourceforge.net/assorted/?rev=1728&view=rev Author: yangzhang Date: 2010-12-06 08:14:38 +0000 (Mon, 06 Dec 2010) Log Message: ----------- Added abolish.vim Added Paths: ----------- configs/trunk/src/vim/doc/abolish.txt configs/trunk/src/vim/plugin/abolish.vim Added: configs/trunk/src/vim/doc/abolish.txt =================================================================== --- configs/trunk/src/vim/doc/abolish.txt (rev 0) +++ configs/trunk/src/vim/doc/abolish.txt 2010-12-06 08:14:38 UTC (rev 1728) @@ -0,0 +1,162 @@ +*abolish.txt* Language friendly searches, substitutions, and abbreviations + +Author: Tim Pope <vim...@tp...> *abolish-author* +License: Same terms as Vim itself (see |license|) + +This plugin is only available if 'compatible' is not set. + +INTRODUCTION *abolish* *:Abolish* *:Subvert* + +Abolish lets you quickly find, substitute, and abbreviate several variations +of a word at once. By default, three case variants (foo, Foo, and FOO) are +operated on by every command. + +Two commands are provided. :Abolish is the most general interface. +:Subvert provides an alternative, more concise syntax for searching and +substituting. +> + :Abolish [options] {abbreviation} {replacement} + :Abolish -delete [options] {abbreviation} + + :Abolish -search [options] {pattern} + :Subvert/{pattern}[/flags] + :Abolish!-search [options] {pattern} + :Subvert?{pattern}[?flags] + + :Abolish -search [options] {pattern} {grep-arguments} + :Subvert /{pattern}/[flags] {grep-options} + :Abolish!-search [options] {pattern} {grep-arguments} + :Subvert!/{pattern}/[flags] {grep-options} + + :[range]Abolish -substitute [options] {pattern} {replacement} + :[range]Subvert/{pattern}/{replacement}[/flags] +< + *:S* +In addition to the :Subvert command, a :S synonym is provided if not +already defined. This will be used in examples below. + +PATTERNS *abolish-patterns* + +Patterns can include brace pairs that contain comma separated alternatives: + + box{,es} => box, boxes, Box, Boxes, BOX, BOXES + +For commands with a replacement, corresponding brace pairs are used in both +halves. If the replacement should be identical to the pattern, an empty +brace pair may be used. If fewer replacements are given than were given in +the pattern, they are looped. That is, {a,b} on the replacement side is the +same as {a,b,a,b,a,b,...} repeated indefinitely. + +The following replaces several different misspellings of "necessary": +> + :%S/{,un}nec{ce,ces,e}sar{y,ily}/{}nec{es}sar{}/g +< +ABBREVIATING *abolish-abbrev* + +By default :Abolish creates abbreviations, which replace words automatically +as you type. This is good for words you frequently misspell, or as +shortcuts for longer words. Since these are just Vim abbreviations, only +whole words will match. +> + :Abolish anomol{y,ies} anomal{} + :Abolish {,in}consistant{,ly} {}consistent{} + :Abolish Tqbf The quick, brown fox jumps over the lazy dog +< +Accepts the following options: + + -buffer: buffer local + -cmdline: work in command line in addition to insert mode + +A good place to define abbreviations is "after/plugin/abolish.vim", +relative to ~\vimfiles on Windows and ~/.vim everywhere else. + +With a bang (:Abolish!) the abbreviation is also appended to the file in +g:abolish_save_file. The default is "after/plugin/abolish.vim", relative +to the install directory. + +Abbreviations can be removed with :Abolish -delete: +> + Abolish -delete -buffer -cmdline anomol{y,ies} +< +SEARCHING *abolish-search* + +The -search command does a search in a manner similar to / key. +search. After searching, you can use |n| and |N| as you would with a normal +search. + +The following will search for box, Box, and BOX: +> + :Abolish -search box +< +When given a single word to operate on, :Subvert defaults to doing a +search as well: +> + :S/box/ +< +This one searches for box, boxes, boxed, boxing, Box, Boxes, Boxed, Boxing, +BOX, BOXES, BOXED, and BOXING: +> + :S/box{,es,ed,ing}/ +< +The following syntaxes search in reverse. +> + :Abolish! -search box + :S?box? +< +Flags can be given with the -flags= option to :Abolish, or by appending them +after the separator to :Subvert. The flags trigger the following behaviors: + + I: Disable case variations (box, Box, BOX) + v: Match inside variable names (match my_box, myBox, but not mybox) + w: Match whole words (like surrounding with \< and \>) + +A |search-offset| may follow the flags. +> + :Abolish -search -flags=avs+1 box + :S?box{,es,ed,ing}?we +< +GREPPING *abolish-grep* + +Grepping works similar to searching, and is invoked when additional options +are given. These options are passed directly to the :grep command. +> + :Abolish -search box{,es} + :S /box{,es}/ * + :S /box/aw *.txt *.html +< +The slash delimiters must both be present if used with :Subvert. They may +both be omitted if no flags are used. + +Both an external grepprg and vimgrep (via grepprg=internal) are supported. +With an external grep, the "v" flag behaves less intelligently, due to the +lack of look ahead and look behind support in grep regexps. + +SUBSTITUTING *abolish-substitute* + +Giving a range switches :Subvert into substitute mode. This command will +change box -> bag, boxes -> bags, Box -> Bag, Boxes -> Bags, BOX -> BAG, +BOXES -> BAGS across the entire document: +> + :%Abolish -substitute -flags=g box{,es} bag{,s} + :%S/box{,es}/bag{,s}/g +< +The "c", "e", "g", and "n" flags can be used from the substitute command +|:s_flags|, along with the "a", "I", "v", and "w" flags from searching. + +COERCION *abolish-coercion* *cr* + +Abolish's case mutating algorithms can be applied to the word under the cursor +using the cr mapping (mnemonic: CoeRce) followed by one of the following +characters: + + c: camelCase + m: MixedCase + _: snake_case + s: snake_case + u: SNAKE_UPPERCASE + -: dash-case (not reversible) + +For example, cru on a lowercase word is a slightly easier to type equivalent +to gUiw. + + vim:tw=78:ts=8:ft=help:norl: Added: configs/trunk/src/vim/plugin/abolish.vim =================================================================== --- configs/trunk/src/vim/plugin/abolish.vim (rev 0) +++ configs/trunk/src/vim/plugin/abolish.vim 2010-12-06 08:14:38 UTC (rev 1728) @@ -0,0 +1,613 @@ +" abolish.vim - Language friendly searches, substitutions, and abbreviations +" Maintainer: Tim Pope +" Version: 1.0 + +" Install this file as plugin/abolish.vim. See doc/abolish.txt for details. +" To access it from Vim, see :help add-local-help (hint: :helptags ~/.vim/doc) +" Afterwards, you should be able to do :help abolish + +" Initialization {{{1 + +" Exit quickly when: +" - this plugin was already loaded (or disabled) +" - when 'compatible' is set +" - Vim is older than 7.0 +if (exists("g:loaded_abolish") && g:loaded_abolish) || &cp || v:version < 700 + finish +endif +let g:loaded_abolish = 1 + +let s:cpo_save = &cpo +set cpo&vim + +if !exists("g:abolish_save_file") + if strpart(expand("<sfile>"),0,strlen(expand("~"))) == expand("~") + let g:abolish_save_file = expand("<sfile>:h:h")."/after/plugin/abolish.vim" + elseif isdirectory(expand("~/.vim")) + let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim") + elseif isdirectory(expand("~/vimfiles")) || has("win32") + let g:abolish_save_file = expand("~/vimfiles/after/plugin/abolish.vim") + else + let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim") + endif +endif + +" }}}1 +" Utility functions {{{1 + +function! s:function(name) + return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) +endfunction + +function! s:send(self,func,...) + if type(a:func) == type('') || type(a:func) == type(0) + let Func = get(a:self,a:func,'') + else + let Func = a:func + endif + let s = type(a:self) == type({}) ? a:self : {} + if type(Func) == type(function('tr')) + return call(Func,a:000,s) + elseif type(Func) == type({}) && has_key(Func,'apply') + return call(Func.apply,a:000,Func) + elseif type(Func) == type({}) && has_key(Func,'call') + return call(Func.call,a:000,s) + elseif type(Func) == type('') && Func == '' && has_key(s,'function missing') + return call('s:send',[s,'function missing',a:func] + a:000) + else + return Func + endif +endfunction + +let s:object = {} +function! s:object.clone(...) + let sub = deepcopy(self) + return a:0 ? extend(sub,a:1) : sub +endfunction + +if !exists("g:Abolish") + let Abolish = {} +endif +call extend(Abolish, s:object, 'force') +call extend(Abolish, {'Coercions': {}}, 'keep') + +function! s:throw(msg) + let v:errmsg = a:msg + throw "Abolish: ".a:msg +endfunction + +function! s:words() + let words = [] + let lnum = line('w0') + while lnum <= line('w$') + let line = getline(lnum) + let col = 0 + while match(line,'\<\k\k\+\>',col) != -1 + let words += [matchstr(line,'\<\k\k\+\>',col)] + let col = matchend(line,'\<\k\k\+\>',col) + endwhile + let lnum += 1 + endwhile + return words +endfunction + +function! s:extractopts(list,opts) + let i = 0 + while i < len(a:list) + if a:list[i] =~ '^-[^=]' && has_key(a:opts,matchstr(a:list[i],'-\zs[^=]*')) + let key = matchstr(a:list[i],'-\zs[^=]*') + let value = matchstr(a:list[i],'=\zs.*') + if type(get(a:opts,key)) == type([]) + let a:opts[key] += [value] + elseif type(get(a:opts,key)) == type(0) + let a:opts[key] = 1 + else + let a:opts[key] = value + endif + else + let i += 1 + continue + endif + call remove(a:list,i) + endwhile + return a:opts +endfunction + +" }}}1 +" Dictionary creation {{{1 + +function! s:mixedcase(word) + return substitute(s:camelcase(a:word),'^.','\u&','') +endfunction + +function! s:camelcase(word) + if a:word !~# '_' && a:word =~# '\l' + return substitute(a:word,'^.','\l&','') + else + return substitute(a:word,'\C\(_\)\=\(.\)','\=submatch(1)==""?tolower(submatch(2)) : toupper(submatch(2))','g') + endif +endfunction + +function! s:snakecase(word) + let word = substitute(a:word,'::','/','g') + let word = substitute(word,'\(\u\+\)\(\u\l\)','\1_\2','g') + let word = substitute(word,'\(\l\|\d\)\(\u\)','\1_\2','g') + let word = substitute(word,'-','_','g') + let word = tolower(word) + return word +endfunction + +function! s:uppercase(word) + return toupper(s:snakecase(a:word)) +endfunction + +function! s:dashcase(word) + return substitute(s:snakecase(a:word),'_','-','') +endfunction + +call extend(Abolish, { + \ 'camelcase': s:function('s:camelcase'), + \ 'mixedcase': s:function('s:mixedcase'), + \ 'snakecase': s:function('s:snakecase'), + \ 'uppercase': s:function('s:uppercase'), + \ 'dashcase': s:function('s:dashcase') + \ }, 'keep') + +function! s:create_dictionary(lhs,rhs,opts) + let dictionary = {} + let i = 0 + let expanded = s:expand_braces({a:lhs : a:rhs}) + for [lhs,rhs] in items(expanded) + if get(a:opts,'case',1) + let dictionary[s:mixedcase(lhs)] = s:mixedcase(rhs) + let dictionary[tolower(lhs)] = tolower(rhs) + let dictionary[toupper(lhs)] = toupper(rhs) + endif + let dictionary[lhs] = rhs + endfor + let i += 1 + return dictionary +endfunction + +function! s:expand_braces(dict) + let new_dict = {} + for [key,val] in items(a:dict) + if key =~ '{.*}' + let redo = 1 + let [all,kbefore,kmiddle,kafter;crap] = matchlist(key,'\(.\{-\}\){\(.\{-\}\)}\(.*\)') + let [all,vbefore,vmiddle,vafter;crap] = matchlist(val,'\(.\{-\}\){\(.\{-\}\)}\(.*\)') + ["","","",""] + if all == "" + let [vbefore,vmiddle,vafter] = [val, ",", ""] + endif + let targets = split(kmiddle,',',1) + let replacements = split(vmiddle,',',1) + if replacements == [""] + let replacements = targets + endif + for i in range(0,len(targets)-1) + let new_dict[kbefore.targets[i].kafter] = vbefore.replacements[i%len(replacements)].vafter + endfor + else + let new_dict[key] = val + endif + endfor + if exists("redo") + return s:expand_braces(new_dict) + else + return new_dict + " old_dict + endif +endfunction + +" }}}1 +" Abolish Dispatcher {{{1 + +function! s:SubComplete(A,L,P) + if a:A =~ '^[/?]\k\+$' + let char = strpart(a:A,0,1) + return join(map(s:words(),'char . v:val'),"\n") + elseif a:A =~# '^\k\+$' + return join(s:words(),"\n") + endif +endfunction + +function! s:Complete(A,L,P) + let g:L = a:L + " Vim bug: :Abolish -<Tab> calls this function with a:A equal to 0 + if a:A =~# '^[^/?-]' && type(a:A) != type(0) + return join(s:words(),"\n") + elseif a:L =~# '^\w\+\s\+\%(-\w*\)\=$' + return "-search\n-substitute\n-delete\n-buffer\n-cmdline\n" + elseif a:L =~# ' -\%(search\|substitute\)\>' + return "-flags=" + else + return "-buffer\n-cmdline" + endif +endfunction + +let s:commands = {} +let s:commands.abstract = s:object.clone() + +function! s:commands.abstract.dispatch(bang,line1,line2,count,args) + return self.clone().go(a:bang,a:line1,a:line2,a:count,a:args) +endfunction + +function! s:commands.abstract.go(bang,line1,line2,count,args) + let self.bang = a:bang + let self.line1 = a:line1 + let self.line2 = a:line2 + let self.count = a:count + return self.process(a:bang,a:line1,a:line2,a:count,a:args) +endfunction + +function! s:dispatcher(bang,line1,line2,count,args) + let i = 0 + let args = copy(a:args) + let command = s:commands.abbrev + while i < len(args) + if args[i] =~# '^-\w\+$' && has_key(s:commands,matchstr(args[i],'-\zs.*')) + let command = s:commands[matchstr(args[i],'-\zs.*')] + call remove(args,i) + break + endif + let i += 1 + endwhile + try + return command.dispatch(a:bang,a:line1,a:line2,a:count,args) + catch /^Abolish: / + echohl ErrorMsg + echo v:errmsg + echohl NONE + return "" + endtry +endfunction + +" }}}1 +" Subvert Dispatcher {{{1 + +function! s:subvert_dispatcher(bang,line1,line2,count,args) + try + return s:parse_subvert(a:bang,a:line1,a:line2,a:count,a:args) + catch /^Subvert: / + echohl ErrorMsg + echo v:errmsg + echohl NONE + return "" + endtry +endfunction + +function! s:parse_subvert(bang,line1,line2,count,args) + if a:args =~ '^\%(\w\|$\)' + let args = (a:bang ? "!" : "").a:args + else + let args = a:args + endif + let separator = matchstr(args,'^.') + let split = split(args,separator,1)[1:] + if a:count || split == [""] + return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split) + elseif len(split) == 1 + return s:find_command(separator,"",split[0]) + elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*n[A-Za-z]*$' + return s:parse_substitute(a:bang,a:line1,a:line2,a:count,[split[0],"",split[1]]) + elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*\%([+-]\d\+\)\=$' + return s:find_command(separator,split[1],split[0]) + elseif len(split) >= 2 && split[1] =~# '^[A-Za-z]* ' + let flags = matchstr(split[1],'^[A-Za-z]*') + let rest = matchstr(join(split[1:],separator),' \zs.*') + return s:grep_command(rest,a:bang,flags,split[0]) + elseif len(split) >= 2 && separator == ' ' + return s:grep_command(join(split[1:],' '),a:bang,"",split[0]) + else + return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split) + endif +endfunction + +function! s:normalize_options(flags) + if type(a:flags) == type({}) + let opts = a:flags + let flags = get(a:flags,"flags","") + else + let opts = {} + let flags = a:flags + endif + let g:op1 = copy(opts) + if flags =~# 'w' + let opts.boundaries = 2 + elseif flags =~# 'v' + let opts.boundaries = 1 + elseif !has_key(opts,'boundaries') + let opts.boundaries = 0 + endif + let opts.case = (flags !~# 'I' ? get(opts,'case',1) : 0) + let opts.flags = substitute(flags,'\C[avIiw]','','g') + let g:op2 = copy(opts) + return opts +endfunction + +" }}}1 +" Searching {{{1 + +function! s:subesc(pattern) + return substitute(a:pattern,'[][\\/.*~]','\\&','g') +endfunction + +function! s:sort(a,b) + if a:a ==? a:b + return a:a == a:b ? 0 : a:a > a:b ? 1 : -1 + elseif strlen(a:a) == strlen(a:b) + return a:a >? a:b ? 1 : -1 + else + return strlen(a:a) < strlen(a:b) ? 1 : -1 + endif +endfunction + +function! s:pattern(dict,boundaries) + if a:boundaries == 2 + let a = '<' + let b = '>' + elseif a:boundaries + let a = '%(<|_@<=|[[:lower:]]@<=[[:upper:]]@=)' + let b = '%(>|_@=|[[:lower:]]@<=[[:upper:]]@=)' + else + let a = '' + let b = '' + endif + return '\v\C'.a.'%('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'|').')'.b +endfunction + +function! s:egrep_pattern(dict,boundaries) + if a:boundaries == 2 + let a = '\<' + let b = '\>' + elseif a:boundaries + let a = '(\<\|_)' + let b = '(\>\|_\|[[:upper:]][[:lower:]])' + else + let a = '' + let b = '' + endif + return a.'('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'\|').')'.b +endfunction + +function! s:c() + call histdel('search',-1) + return "" +endfunction + +function! s:find_command(cmd,flags,word) + let opts = s:normalize_options(a:flags) + let dict = s:create_dictionary(a:word,"",opts) + " This is tricky. If we use :/pattern, the search drops us at the + " beginning of the line, and we can't use position flags (e.g., /foo/e). + " If we use :norm /pattern, we leave ourselves vulnerable to "press enter" + " prompts (even with :silent). + let cmd = (a:cmd =~ '[?!]' ? '?' : '/') + let @/ = s:pattern(dict,opts.boundaries) + if opts.flags == "" || !search(@/,'n') + return "norm! ".cmd."\<CR>" + elseif opts.flags =~ ';[/?]\@!' + call s:throw("E386: Expected '?' or '/' after ';'") + else + return "exe 'norm! ".cmd.cmd.opts.flags."\<CR>'|call histdel('search',-1)" + return "" + endif +endfunction + +function! s:grep_command(args,bang,flags,word) + let opts = s:normalize_options(a:flags) + let dict = s:create_dictionary(a:word,"",opts) + if &grepprg == "internal" + let lhs = "'".s:pattern(dict,opts.boundaries)."'" + else + let lhs = "-E '".s:egrep_pattern(dict,opts.boundaries)."'" + endif + return "grep".(a:bang ? "!" : "")." ".lhs." ".a:args +endfunction + +let s:commands.search = s:commands.abstract.clone() +let s:commands.search.options = {"word": 0, "variable": 0, "flags": ""} + +function! s:commands.search.process(bang,line1,line2,count,args) + call s:extractopts(a:args,self.options) + if self.options.word + let self.options.flags .= "w" + elseif self.options.variable + let self.options.flags .= "v" + endif + let opts = s:normalize_options(self.options) + if len(a:args) > 1 + return s:grep_command(join(a:args[1:]," "),a:bang,opts,a:args[0]) + elseif len(a:args) == 1 + return s:find_command(a:bang ? "!" : " ",opts,a:args[0]) + else + call s:throw("E471: Argument required") + endif +endfunction + +" }}}1 +" Substitution {{{1 + +function! Abolished() + return get(g:abolish_last_dict,submatch(0),submatch(0)) +endfunction + +function! s:substitute_command(cmd,bad,good,flags) + let opts = s:normalize_options(a:flags) + let dict = s:create_dictionary(a:bad,a:good,opts) + let lhs = s:pattern(dict,opts.boundaries) + let g:abolish_last_dict = dict + return a:cmd.'/'.lhs.'/\=Abolished()'."/".opts.flags +endfunction + +function! s:parse_substitute(bang,line1,line2,count,args) + if get(a:args,0,'') =~ '^[/?'']' + let separator = matchstr(a:args[0],'^.') + let args = split(join(a:args,' '),separator,1) + call remove(args,0) + else + let args = a:args + endif + if len(args) < 2 + call s:throw("E471: Argument required") + elseif len(args) > 3 + call s:throw("E488: Trailing characters") + endif + let [bad,good,flags] = (args + [""])[0:2] + if a:count == 0 + let cmd = "substitute" + else + let cmd = a:line1.",".a:line2."substitute" + endif + return s:substitute_command(cmd,bad,good,flags) +endfunction + +let s:commands.substitute = s:commands.abstract.clone() +let s:commands.substitute.options = {"word": 0, "variable": 0, "flags": "g"} + +function! s:commands.substitute.process(bang,line1,line2,count,args) + call s:extractopts(a:args,self.options) + if self.options.word + let self.options.flags .= "w" + elseif self.options.variable + let self.options.flags .= "v" + endif + let opts = s:normalize_options(self.options) + if len(a:args) <= 1 + call s:throw("E471: Argument required") + else + let good = join(a:args[1:],"") + let cmd = a:bang ? "." : "%" + return s:substitute_command(cmd,a:args[0],good,self.options) + endif +endfunction + +" }}}1 +" Abbreviations {{{1 + +function! s:badgood(args) + let words = filter(copy(a:args),'v:val !~ "^-"') + call filter(a:args,'v:val =~ "^-"') + if empty(words) + call s:throw("E471: Argument required") + elseif !empty(a:args) + call s:throw("Unknown argument: ".a:args[0]) + endif + let [bad; words] = words + return [bad, join(words," ")] +endfunction + +function! s:abbreviate_from_dict(cmd,dict) + for [lhs,rhs] in items(a:dict) + exe a:cmd lhs rhs + endfor +endfunction + +let s:commands.abbrev = s:commands.abstract.clone() +let s:commands.abbrev.options = {"buffer":0,"cmdline":0,"delete":0} +function! s:commands.abbrev.process(bang,line1,line2,count,args) + call s:extractopts(a:args,self.options) + if self.options.delete + let cmd = "unabbrev" + let good = "" + else + let cmd = "noreabbrev" + endif + if !self.options.cmdline + let cmd = "i" . cmd + endif + if self.options.delete + let cmd = "silent! ".cmd + endif + if self.options.buffer + let cmd = cmd . " <buffer>" + endif + let [bad, good] = s:badgood(a:args) + if substitute(bad,'{.\{-\}.}','','g') !~ '^\k\+$' + call s:throw("E474: Invalid argument (not a keyword: ".string(bad).")") + endif + if !self.options.delete && good == "" + call s:throw("E471: Argument required".a:args[0]) + endif + let dict = s:create_dictionary(bad,good,self.options) + call s:abbreviate_from_dict(cmd,dict) + if a:bang + let i = 0 + let str = "Abolish ".join(a:000," ") + let file = g:abolish_save_file + call s:mkdir(fnamemodify(file,':h'),"p") + if filereadable(file) + let old = readfile(file) + else + let old = ["\" Exit if :Abolish isn't available.","if !exists(':Abolish')"," finish","endif",""] + endif + call writefile(old + [str],file) + endif + return "" +endfunction + +let s:commands.delete = s:commands.abbrev.clone() +let s:commands.delete.options.delete = 1 + +" }}}1 +" Maps {{{1 + +function! s:unknown_coercion(letter,word) + return a:word +endfunction + +call extend(Abolish.Coercions, { + \ 'c': Abolish.camelcase, + \ 'm': Abolish.mixedcase, + \ 's': Abolish.snakecase, + \ '_': Abolish.snakecase, + \ 'u': Abolish.uppercase, + \ '-': Abolish.dashcase, + \ "function missing": s:function("s:unknown_coercion") + \}, "keep") + +function! s:coerce(transformation) + let regbody = getreg('"') + let regtype = getregtype('"') + let c = v:count1 + while c > 0 + let c -= 1 + norm! yiw + let word = @@ + let @@ = s:send(g:Abolish.Coercions,a:transformation,word) + if !exists('begin') + let begin = getpos("'[") + endif + if word !=# @@ + let changed = 1 + norm! viwpw + else + norm! w + endif + endwhile + call setreg('"',regbody,regtype) + call setpos("'[",begin) + call setpos(".",begin) + if exists("changed") + silent! call repeat#set("\<Plug>Coerce".a:transformation) + endif +endfunction + +nnoremap <silent> <Plug>Coerce :<C-U>call <SID>coerce(nr2char(getchar()))<CR> + +" }}}1 + +nmap cr <Plug>Coerce + +command! -nargs=+ -bang -bar -range=0 -complete=custom,s:Complete Abolish + \ :exec s:dispatcher(<bang>0,<line1>,<line2>,<count>,[<f-args>]) +command! -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete Subvert + \ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>) +if exists(':S') != 2 + command -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete S + \ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>) +endif + +let &cpo = s:cpo_save + +" vim:set ft=vim ts=8 sw=4 sts=4: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-12-06 08:16:39
|
Revision: 1729 http://assorted.svn.sourceforge.net/assorted/?rev=1729&view=rev Author: yangzhang Date: 2010-12-06 08:16:29 +0000 (Mon, 06 Dec 2010) Log Message: ----------- Added speeddating.vim Added Paths: ----------- configs/trunk/src/vim/doc/speeddating.txt configs/trunk/src/vim/plugin/speeddating.vim Added: configs/trunk/src/vim/doc/speeddating.txt =================================================================== --- configs/trunk/src/vim/doc/speeddating.txt (rev 0) +++ configs/trunk/src/vim/doc/speeddating.txt 2010-12-06 08:16:29 UTC (rev 1729) @@ -0,0 +1,101 @@ +*speeddating.vim* Use CTRL-A/CTRL-X to increment dates, times, and more + +Author: Tim Pope <vim...@tp...> *speeddating-author* +License: Same terms as Vim itself (see |license|) + +This plugin is only available if 'compatible' is not set. + +INTRODUCTION *speeddating* + +The easiest way to get a feel for this plugin is to copy the following lines +to a temp file and go to town on them with <C-A> and <C-X>. When you're done, +come back here and read about some of the more advanced features, like +incrementing lists and custom formats. > + + Fri, 31 Dec 1999 23:59:59 +0000 + Fri Dec 31 23:59:59 UTC 1999 + 2008-01-05T04:59:59Z + 1865-04-15 + 11/Sep/01 + January 14th, 1982 + 11:55 AM + 3rd + XXXVIII +< +MAPS *speeddating-maps* + +Here, "component" refers to any year, month, day, hour, minute, or second +written as either a number or a word ("January") in any recognized format, or +a number or ordinal ("1st") outside of a time. + + *speeddating-CTRL-A* +<C-A> Increment by [count] the component under the cursor. + + *speeddating-CTRL-X* +<C-X> Decrement by [count] the component under the cursor. + + *speeddating-d_CTRL-A* +d<C-A> Change the time under the cursor to the current time + in UTC. + + *speeddating-d_CTRL-X* +d<C-X> Change the time under the cursor to the current local + time. + + *speeddating-v_CTRL-A* +{Visual}<C-A> Increment by [count] the component under the cursor on + each line of the linewise visual selection. If a + component is absent on a line, it is filled in as + being [count] higher than on the line above it. This + can be used to create sequences. For example, place a + "0" on a line followed by 4 blank lines, visually + select all 5 lines, and press <C-A> to get a sequence + of 1 through 5. You can use letters in visual mode + too: make the first entry Z if you want a list + starting with A. + + *speeddating-v_CTRL-X* +{Visual}<C-X> Like |v_CTRL-A|, but decrement. + + *speeddating-.* +. If you want to use |.| to repeat a speeddating.vim + mapping, install repeat.vim. + +FORMATS *speeddating-formats* + +One can use the :SpeedDatingFormat command to list, add, and remove formats. + + *:SpeedDatingFormat* +:SpeedDatingFormat List defined formats. + +:SpeedDatingFormat! Help for defining formats. + +:SpeedDatingFormat {format} + Define a new format. + +:{count}SpeedDatingFormat {format} + Define a new format with the specified priority. + +:SpeedDatingFormat! {format} + Remove an existing format. + +:{count}SpeedDatingFormat! + Remove an existing format by priority. + +Of note is that the built-in support for Roman numerals is actually +implemented with a Roman numeral year format and can be removed. + +CAVEATS *speeddating-caveats* + +Gregorian calendar always used. + +Time zone abbreviation support is limited to a few predefined codes on Windows +and other platforms without strftime("%Z") support. If your time zone +abbreviation is not correctly identified set the g:speeddating_zone and +g:speeddating_zone_dst variables. + +Beginning a format with a digit causes Vim to treat leading digits as a count +instead. To work around this escape it with %[] (e.g., %[2]0%0y%0m%0d%* is a +decent format for DNS serials). + + vim:tw=78:et:ft=help:norl: Added: configs/trunk/src/vim/plugin/speeddating.vim =================================================================== --- configs/trunk/src/vim/plugin/speeddating.vim (rev 0) +++ configs/trunk/src/vim/plugin/speeddating.vim 2010-12-06 08:16:29 UTC (rev 1729) @@ -0,0 +1,833 @@ +" speeddating.vim - Use CTRL-A/CTRL-X to increment dates, times, and more +" Maintainer: Tim Pope <vim...@tp...> +" Version: 20100301 +" GetLatestVimScripts: 2120 1 :AutoInstall: speeddating.vim + +" Initialization {{{1 + +if exists("g:loaded_speeddating") || &cp || v:version < 700 + finish +endif +let g:loaded_speeddating = 1 + +let s:cpo_save = &cpo +set cpo&vim + +let g:speeddating_handlers = [] + +let s:install_dir = expand("<sfile>:p:h:h") + +" }}}1 +" Utility Functions {{{1 + +function! s:function(name) + return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),'')) +endfunction + +" In Vim, -4 % 3 == -1. Let's return 2 instead. +function! s:mod(a,b) + if (a:a < 0 && a:b > 0 || a:a > 0 && a:b < 0) && a:a % a:b != 0 + return (a:a % a:b) + a:b + else + return a:a % a:b + endif +endfunction + +" In Vim, -4 / 3 == -1. Let's return -2 instead. +function! s:div(a,b) + if a:a < 0 && a:b > 0 + return (a:a-a:b+1)/a:b + elseif a:a > 0 && a:b < 0 + return (a:a-a:b-1)/a:b + else + return a:a / a:b + endif +endfunction + +function! s:match(...) + let b = call("match",a:000) + let e = call("matchend",a:000) + let s = call("matchlist",a:000) + if s == [] + let s = ["","","","","","","","","",""] + endif + return [b,e] + s +endfunction + +function! s:findatoffset(string,pattern,offset) + let line = a:string + let curpos = 0 + let offset = a:offset + while strpart(line,offset,1) == " " + let offset += 1 + endwhile + let [start,end,string;caps] = s:match(line,a:pattern,curpos,0) + while start >= 0 + if offset >= start && offset < end + break + endif + let curpos = start + 1 + let [start,end,string;caps] = s:match(line,a:pattern,curpos,0) + endwhile + return [start,end,string] + caps +endfunction + +function! s:findinline(pattern) + return s:findatoffset(getline('.'),a:pattern,col('.')-1) +endfunction + +function! s:replaceinline(start,end,new) + let line = getline('.') + let before_text = strpart(line,0,a:start) + let after_text = strpart(line,a:end) + " If this generates a warning it will be attached to an ugly backtrace. + " No warning at all is preferable to that. + silent call setline('.',before_text.a:new.after_text) + call setpos("'[",[0,line('.'),strlen(before_text)+1,0]) + call setpos("']",[0,line('.'),a:start+strlen(a:new),0]) +endfunction + +" }}}1 +" Normal Mode {{{1 + +function! s:increment(increment) + for handler in s:time_handlers + g:speeddating_handlers + let pattern = type(handler.regexp) == type(function('tr')) ? handler.regexp() : handler.regexp + let [start,end,string;caps] = s:findinline('\C'.pattern) + if string != "" + let [repl,offset] = handler.increment(string,col('.')-1-start,a:increment) + if offset < 0 + let offset += strlen(repl) + 1 + endif + if repl != "" + call s:replaceinline(start,end,repl) + call setpos('.',[0,line('.'),start+offset,0]) + silent! call repeat#set("\<Plug>SpeedDating" . (a:increment < 0 ? "Down" : "Up"),a:increment < 0 ? -a:increment : a:increment) + return + endif + endif + endfor + if a:increment > 0 + exe "norm! ". a:increment."\<C-A>" + else + exe "norm! ".-a:increment."\<C-X>" + endif + silent! call repeat#set("\<Plug>SpeedDating" . (a:increment < 0 ? "Down" : "Up"),a:increment < 0 ? -a:increment : a:increment) +endfunction + +" }}}1 +" Visual Mode {{{1 + +function! s:setvirtcol(line,col) + call setpos('.',[0,a:line,a:col,0]) + while virtcol('.') < a:col + call setpos('.',[0,a:line,col('.')+1,0]) + endwhile + while virtcol('.') > a:col + call setpos('.',[0,a:line,col('.')-1,0]) + endwhile + return col('.') + getpos('.')[3] +endfunction + +function! s:chars(string) + return strlen(substitute(a:string,'.','.','g')) +endfunction + +function! s:incrementstring(string,offset,count) + let repl = "" + let offset = -1 + for handler in s:time_handlers + g:speeddating_handlers + s:visual_handlers + let pattern = type(handler.regexp) == type(function('tr')) ? handler.regexp() : handler.regexp + let [start,end,string;caps] = s:findatoffset(a:string,'\C'.pattern,a:offset) + if string != "" + let [repl,offset] = handler.increment(string,a:offset,a:count) + if repl != "" + break + endif + endif + endfor + if offset < 0 + let offset += strlen(repl) + 1 + endif + + if repl != "" + let before_text = strpart(a:string,0,start) + let change = s:chars(repl) - s:chars(string) + if change < 0 && before_text !~ '\w$' + let offset -= change + let repl = repeat(' ',-change) . repl + elseif change > 0 && before_text =~ ' $' + let before_text = substitute(before_text,' \{1,'.change.'\}$','','') + let before_text = substitute(before_text,'\w$','& ','') + let start = strlen(before_text) + endif + let offset += start + let repl = before_text.repl.strpart(a:string,end) + endif + return [repl,offset,start,end] +endfunction + +function! s:incrementvisual(count) + let ve = &ve + set virtualedit=all + exe "norm! gv\<Esc>" + let vcol = virtcol('.') + let lnum = line("'<") + let lastrepl = "" + call s:setvirtcol(lnum,vcol) + call setpos("'[",[0,line("'<"),1,0]) + while lnum <= line("'>") + call s:setvirtcol(lnum,vcol) + let [repl,offset,start,end] = s:incrementstring(getline('.'),col('.')-1,a:count) + if repl == "" && lastrepl != "" + call setpos(".",[0,lnum-1,laststart,0]) + let start = s:setvirtcol(lnum,virtcol('.')) + call setpos(".",[0,lnum-1,lastend,0]) + let end = s:setvirtcol(lnum,virtcol('.')) + call s:setvirtcol(lnum,vcol) + if strpart(getline('.'),start,end-start) =~ '^\s*$' + let before_padded = printf("%-".start."s",strpart(getline('.'),0,start)) + let tweaked_line = before_padded.strpart(lastrepl,laststart,lastend-laststart).strpart(getline('.'),end) + let [repl,offset,start,end] = s:incrementstring(tweaked_line,col('.')-1,a:count*(lnum-lastlnum)) + endif + elseif repl != "" + let [lastrepl,laststart,lastend,lastlnum] = [repl,start,end,lnum] + endif + if repl != "" + silent call setline('.',repl) + endif + let lnum += 1 + endwhile + let &ve = ve + call setpos("']",[0,line('.'),col('$'),0]) +endfunction + +" }}}1 +" Visual Mode Handlers {{{1 + +let s:visual_handlers = [] + +function! s:numberincrement(string,offset,increment) + let n = (a:string + a:increment) + if a:string =~# '^0x.*[A-F]' + return [printf("0x%X",n),-1] + elseif a:string =~# '^0x' + return [printf("0x%x",n),-1] + elseif a:string =~# '^00*[^0]' + return [printf("0%o",n),-1] + else + return [printf("%d",n),-1] + endif +endfunction + +let s:visual_handlers += [{'regexp': '-\=\<\%(0x\x\+\|\d\+\)\>', 'increment': s:function("s:numberincrement")}] + +function! s:letterincrement(string,offset,increment) + return [nr2char((char2nr(toupper(a:string)) - char2nr('A') + a:increment) % 26 + (a:string =~# '[A-Z]' ? char2nr('A') : char2nr('a'))),-1] +endfunction + +let s:visual_handlers += [{'regexp': '\<[A-Za-z]\>', 'increment': s:function("s:letterincrement")}] + +" }}}1 +" Ordinals {{{1 + +function! s:ordinalize(number) + let n = a:number + let a = n < 0 ? -n : +n + if a % 100 == 11 || a % 100 == 12 || a % 100 == 13 + return n."th" + elseif a % 10 == 1 + return n."st" + elseif a % 10 == 2 + return n."nd" + elseif a % 10 == 3 + return n."rd" + else + return n."th" + endif +endfunction + +function! s:ordinalincrement(string,offset,increment) + return [s:ordinalize(a:string+a:increment),-1] +endfunction + +let g:speeddating_handlers += [{'regexp': '-\=\<\d\+\%(st\|nd\|rd\|th\)\>', 'increment': s:function("s:ordinalincrement")}] + +" }}}1 +" Roman Numerals {{{1 + +" Based on similar functions from VisIncr.vim + +let s:a2r = [[1000, 'm'], [900, 'cm'], [500, 'd'], [400, 'cd'], [100, 'c'], + \ [90 , 'xc'], [50 , 'l'], [40 , 'xl'], [10 , 'x'], + \ [9 , 'ix'], [5 , 'v'], [4 , 'iv'], [1 , 'i']] + +function! s:roman2arabic(roman) + let roman = tolower(a:roman) + let sign = 1 + let arabic = 0 + while roman != '' + if roman =~ '^[-n]' + let sign = -sign + endif + for [numbers,letters] in s:a2r + if roman =~ '^'.letters + let arabic += sign * numbers + let roman = strpart(roman,strlen(letters)-1) + break + endif + endfor + let roman = strpart(roman,1) + endwhile + + return arabic +endfunction + +function! s:arabic2roman(arabic) + if a:arabic <= 0 + let arabic = -a:arabic + let roman = "n" + else + let arabic = a:arabic + let roman = "" + endif + for [numbers, letters] in s:a2r + let roman .= repeat(letters,arabic/numbers) + let arabic = arabic % numbers + endfor + return roman +endfunction + +" }}}1 +" Time Helpers {{{1 + +function! s:ary2pat(array) + return '\%('.join(a:array,'\|').'\)' + return '\%('.join(map(copy(a:array),'substitute(v:val,"[[:alpha:]]","[\\u&\\l&]","g")'),'\|').'\)' +endfunction + +function! s:initializetime(time) + call extend(a:time,{'y': '','b':1,'d':0,'h':0,'m':0,'s':0,'o':0},"keep") + if get(a:time,'b','') !~ '^\d*$' + let full = index(s:months_full ,a:time.b,0,1) + 1 + let engl = index(s:months_engl ,a:time.b,0,1) + 1 + let abbr = index(s:months_abbr ,a:time.b,0,1) + 1 + if full + let a:time.b = full + elseif engl + let a:time.b = engl + elseif abbr + let a:time.b = abbr + else + let a:time.b = 1 + endif + endif + if has_key(a:time,'p') + let a:time.h = a:time.h % 12 + if a:time.p ==? "PM" + let a:time.h += 12 + endif + call remove(a:time,"p") + endif + if a:time.y !~ '^\d*$' + let a:time.y = s:roman2arabic(a:time.y) + elseif a:time.y =~ '^-\=0..' + let a:time.y = substitute(a:time.y,'0\+','','') + elseif a:time.y < 38 && a:time.y >= 0 && ''.a:time.y != '' + let a:time.y += 2000 + elseif a:time.y < 100 && a:time.y >= 38 + let a:time.y += 1900 + endif + if has_key(a:time,'w') + let full = index(s:days_full,a:time.w,0,1) + let engl = index(s:days_engl,a:time.w,0,1) + let abbr = index(s:days_abbr,a:time.w,0,1) + let a:time.w = full > 0 ? full : (engl > 0 ? engl : (abbr > 0 ? abbr : a:time.w)) + if a:time.d == 0 + let a:time.d = s:mod(a:time.w - s:jd(a:time.y,a:time.b,1),7) + elseif a:time.y == '' && a:time.b * a:time.d > 0 + let a:time.y = strftime("%Y")-2 + while s:mod(s:jd(a:time.y,a:time.b,a:time.d)+1,7) != a:time.w + let a:time.y += 1 + endwhile + endif + call remove(a:time,'w') + endif + if a:time.d == 0 + let a:time.d = 1 + endif + if ''.a:time.y == '' + let a:time.y = 2000 + endif + if a:time.o =~ '^[+-]\d\d:\=\d\d$' + let a:time.o = (a:time.o[0]=="-" ? -1 : 1)*(a:time.o[1:2]*60+matchstr(a:time.o,'\d\d$')) + elseif get(a:time,'z','') == g:speeddating_zone + let a:time.o = s:offset + elseif get(a:time,'z','') == g:speeddating_zone_dst + let a:time.o = s:offset_dst + endif + return a:time +endfunction + +" Julian day (always Gregorian calendar) +function! s:jd(year,mon,day) + let y = a:year + 4800 - (a:mon <= 2) + let m = a:mon + (a:mon <= 2 ? 9 : -3) + let jul = a:day + (153*m+2)/5 + s:div(1461*y,4) - 32083 + return jul - s:div(y,100) + s:div(y,400) + 38 +endfunction + +function! s:gregorian(jd) + let l = a:jd + 68569 + let n = s:div(4 * l, 146097) + let l = l - s:div(146097 * n + 3, 4) + let i = ( 4000 * ( l + 1 ) ) / 1461001 + let l = l - ( 1461 * i ) / 4 + 31 + let j = ( 80 * l ) / 2447 + let d = l - ( 2447 * j ) / 80 + let l = j / 11 + let m = j + 2 - ( 12 * l ) + let y = 100 * ( n - 49 ) + i + l + return {'y':y,'b':m,'d':d} +endfunction + +function! s:normalizetime(time) + let a:time.y += s:div(a:time.b-1,12) + let a:time.b = s:mod(a:time.b-1,12)+1 + let seconds = a:time.h * 3600 + a:time.m * 60 + a:time.s + let a:time.s = s:mod(seconds,60) + let a:time.m = s:mod(s:div(seconds,60),60) + let a:time.h = s:mod(s:div(seconds,3600),24) + if seconds != 0 || a:time.b != 1 || a:time.d != 1 + let day = s:gregorian(s:jd(a:time.y,a:time.b,a:time.d)+s:div(seconds,86400)) + return extend(a:time,day) + else + return a:time + endif +endfunction + +function! s:applymodifer(number,modifier,width) + if a:modifier == '-' + return substitute(a:number,'^0*','','') + elseif a:modifier == '_' + return printf('%'.a:width.'d',a:number) + elseif a:modifier == '^' + return toupper(a:number) + else + return printf('%0'.a:width.'s',a:number) + endif +endfunction + +function! s:modyear(y) + return printf('%02d',s:mod(a:y,100)) +endfunction + +function! s:strftime(pattern,time) + if type(a:time) == type({}) + let time = s:normalizetime(copy(a:time)) + else + let time = s:normalizetime(s:initializetime({'y':1970,'s':a:time})) + endif + let time.w = s:mod(s:jd(time.y,time.b,time.d)+1,7) + let time.p = time.h + let expanded = "" + let remaining = a:pattern + while remaining != "" + if remaining =~ '^%' + let modifier = matchstr(remaining,'%\zs[-_0^]\=\ze.') + let specifier = matchstr(remaining,'%[-_0^]\=\zs.') + let remaining = matchstr(remaining,'%[-_0^]\=.\zs.*') + if specifier == '%' + let expanded .= '%' + elseif has_key(s:strftime_items,specifier) + let item = s:strftime_items[specifier] + let number = time[item[1]] + if type(item[4]) == type([]) + let expanded .= s:applymodifer(item[4][number % len(item[4])],modifier,1) + elseif type(item[4]) == type(function('tr')) + let expanded .= s:applymodifer(call(item[4],[number]),modifier,1) + else + let expanded .= s:applymodifer(number,modifier,item[4]) + endif + else + let expanded .= '%'.modifier.specifier + endif + else + let expanded .= matchstr(remaining,'[^%]*') + let remaining = matchstr(remaining,'[^%]*\zs.*') + endif + endwhile + return expanded +endfunction + +function! s:localtime(...) + let ts = a:0 ? a:1 : localtime() + let time = { + \ 'y': +strftime('%Y',ts), + \ 'b': +strftime('%m',ts), + \ 'd': +strftime('%d',ts), + \ 'h': +strftime('%H',ts), + \ 'm': +strftime('%M',ts), + \ 's': +strftime('%S',ts)} + let jd = s:jd(time.y,time.b,time.d) - s:jd(1970,1,1) + let real_ts = jd * 86400 + time.h * 3600 + time.m * 60 + time.s + let time.o = (real_ts - ts) / 60 + return time +endfunction + +function! s:formattz(offset) + if a:offset < 0 + let offset = -a:offset + let sign = "-" + else + let offset = a:offset + let sign = "+" + endif + return printf("%s%02d%02d",sign,offset/60,offset%60) +endfunction + +" }}}1 +" Time Data {{{1 + +let s:offset = s:localtime(( 0+30*365)*86400).o +if !exists("g:speeddating_zone") + let g:speeddating_zone = strftime("%Z",30*365*86400) + if g:speeddating_zone == "" + let g:speeddating_zone = get({-8:'PST',-7:'MST',-6:'CST',-5:'EST',0:'WET',1:'CET',2:'EET'},s:offset/60,"XST") + endif +endif + +let s:offset_dst = s:localtime((180+30*365)*86400).o +if !exists("g:speeddating_zone_dst") + let g:speeddating_zone_dst = strftime("%Z",(180+30*365)*86400) + if g:speeddating_zone_dst == "" + if s:offset == s:offset_dst + let g:speeddating_zone_dst = g:speeddating_zone + else + let g:speeddating_zone_dst = get({-7:'PDT',-6:'MDT',-5:'CDT',-4:'EDT',1:'WEST',2:'CEST',3:'EEST'},s:offset_dst/60,"XDT") + endif + endif +endif + +let s:days_engl =["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] +let s:days_abbr =map(range(86400*3+43200-s:offset*60,86400*12,86400),'strftime("%a",v:val)')[0:6] +let s:days_full =map(range(86400*3+43200-s:offset*60,86400*12,86400),'strftime("%A",v:val)')[0:6] + +let s:months_engl =["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] +let s:months_abbr =map(range(86400*2,86400*365,86400*31),'strftime("%b",v:val)') +let s:months_full =map(range(86400*2,86400*365,86400*31),'strftime("%B",v:val)') + +let s:strftime_items = { + \ "a": ['d','w',s:ary2pat(s:days_abbr), 'weekday (abbreviation)',s:days_abbr], + \ "A": ['d','w',s:ary2pat(s:days_full), 'weekday (full name)',s:days_full], + \ "i": ['d','w',s:ary2pat(s:days_engl), 'weekday (English abbr)',s:days_engl], + \ "b": ['b','b',s:ary2pat(s:months_abbr), 'month (abbreviation)',[""]+s:months_abbr], + \ "B": ['b','b',s:ary2pat(s:months_full), 'month (full name)',[""]+s:months_full], + \ "h": ['b','b',s:ary2pat(s:months_engl), 'month (English abbr)',[""]+s:months_engl], + \ "d": ['d','d','[ 0-3]\=\d', 'day (01-31)',2], + \ "H": ['h','h','[ 0-2]\=\d', 'hour (00-23)',2], + \ "I": ['h','h','[ 0-2]\=\d', 'hour (01-12)',['12', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']], + \ "m": ['b','b','[ 0-1]\=\d', 'month (01-12)',2], + \ "M": ['m','m','[ 0-5]\=\d', 'minutes',2], + \ "o": ['d','d','[ 0-3]\=\d\%(st\|nd\|rd\|th\)','day (1st-31st)',s:function("s:ordinalize")], + \ "P": ['h','p','[ap]m', 'am/pm',repeat(['am'],12) + repeat(['pm'],12)], + \ "S": ['s','s','[ 0-5]\=\d', 'seconds',2], + \ "v": ['y','y','[ivxlcdmn]\+','year (roman numerals)',s:function("s:arabic2roman")], + \ "y": ['y','y','\d\d','year (00-99)',s:function("s:modyear")], + \ "Y": ['y','y','-\=\d\d\d\=\d\=','year',4], + \ "z": ['o','o','[+-]\d\d\d\d','timezone offset',s:function("s:formattz")], + \ "Z": [' ','z','[A-Z]\{3,5}','timezone (incomplete)',3]} + +" }}}1 +" Time Handler {{{1 + +function! s:timestamp(utc,count) + for handler in s:time_handlers + let [start,end,string;caps] = s:findinline('\C'.join(handler.groups,'')) + if string != "" + let format = substitute(handler.strftime,'\\\([1-9]\)','\=caps[submatch(1)-1]','g') + if a:utc || a:count + let offset = (a:utc ? 1 : -1) * a:count * 15 + let time = s:initializetime({'y':1970,'s':localtime()+offset*60,'o':offset}) + else + let time = s:localtime() + endif + if a:utc && !a:count + let time.z = 'UTC' + elseif time.o == s:offset + let time.z = g:speeddating_zone + elseif time.o == s:offset_dst + let time.z = g:speeddating_zone_dst + elseif time.o == 0 + let time.z = 'UTC' + else + let time.z = 'XXT' + endif + let newstring = s:strftime(format,time) + call s:replaceinline(start,end,newstring) + call setpos('.',[0,line('.'),start+strlen(newstring),0]) + silent! call repeat#set("\<Plug>SpeedDatingNow".(a:utc ? "UTC" : "Local"),a:count) + return "" + endif + endfor + let [start,end,string;caps] = s:findinline('-\=\<\d\+\>') + if string != "" + let newstring = localtime() + (a:utc ? 1 : -1) * a:count * 60*15 + call s:replaceinline(start,end,newstring) + call setpos('.',[0,line('.'),start+strlen(newstring),0]) + silent! call repeat#set("\<Plug>SpeedDatingNow".(a:utc ? "UTC" : "Local"),a:count) + endif +endfunction + +function! s:dateincrement(string,offset,increment) dict + let [start,end,string;caps] = s:match(a:string,'\C'.join(self.groups,'')) + let string = a:string + let offset = a:offset + let cursor_capture = 1 + let idx = 0 + while idx < len(self.groups) + let partial_matchend = matchend(string,join(self.groups[0:idx],'')) + if partial_matchend > offset + break + endif + let idx += 1 + endwhile + while get(self.targets,idx,"") == " " + let idx += 1 + endwhile + while get(self.targets,idx," ") == " " + let idx -= 1 + endwhile + let partial_pattern = join(self.groups[0:idx],'') + let char = self.targets[idx] + let i = 0 + let time = {} + for cap in caps + if get(self.reader,i," ") !~ '^\s\=$' + let time[self.reader[i]] = substitute(cap,'^\s*','','') + endif + let i += 1 + endfor + call s:initializetime(time) + let inner_offset = 0 + if char == 'o' + let inner_offset = partial_matchend - offset - 1 + let factor = 15 + if inner_offset <= 0 + let inner_offset = 0 + let factor = 1 + elseif inner_offset > 1 + let factor = 60 + let inner_offset = 2 + endif + let time.o += factor * a:increment + let time.m += factor * a:increment + elseif char == 'b' + let time.b += a:increment + let goal = time.y*12 + time.b + call s:normalizetime(time) + while time.y*12 + time.b > goal + let time.d -= 1 + call s:normalizetime(time) + endwhile + else + let time[char] += a:increment + endif + let format = substitute(self.strftime,'\\\([1-9]\)','\=caps[submatch(1)-1]','g') + let time_string = s:strftime(format,time) + return [time_string, matchend(time_string,partial_pattern)-inner_offset] +endfunction + +function! s:timeregexp() dict + return join(self.groups,'') +endfunction + +function! s:createtimehandler(format) + let pattern = '^\%(%?\=\[.\{-\}\]\|%[-_0^]\=.\|[^%]*\)' + let regexp = ['\%(\<\|-\@=\)'] + let reader = [] + let targets = [' '] + let template = "" + let default = "" + let remaining = substitute(a:format,'\C%\@<!%p','%^P','g') + let group = 0 + let usergroups = [] + let userdefaults = [] + while remaining != "" + let fragment = matchstr(remaining,pattern) + let remaining = matchstr(remaining,pattern.'\zs.*') + if fragment =~ '^%\*\W' + let suffix = '*' + let fragment = '%' . strpart(fragment,2) + elseif fragment =~ '^%?\W' + let suffix = '\=' + let fragment = '%' . strpart(fragment,2) + else + let suffix = '' + endif + let targets += [' '] + if fragment =~ '^%' && has_key(s:strftime_items,matchstr(fragment,'.$')) + let item = s:strftime_items[matchstr(fragment,'.$')] + let modifier = matchstr(fragment,'^%\zs.\ze.$') + let targets[-1] = item[0] + let reader += [item[1]] + if modifier == '^' + let pat = substitute(item[2],'\C\\\@<![[:lower:]]','\u&','g') + elseif modifier == '0' + let pat = substitute(item[2],' \|-\@<!\\=','','g') + else + let pat = item[2] + endif + let regexp += ['\('.pat.'\)'] + let group += 1 + let template .= fragment + let default .= fragment + elseif fragment =~ '^%\[.*\]$' + let reader += [' '] + let regexp += ['\('.matchstr(fragment,'\[.*').suffix.'\)'] + let group += 1 + let usergroups += [group] + let template .= "\\".group + if suffix == "" + let default .= strpart(fragment,2,1) + let userdefaults += [strpart(fragment,2,1)] + else + let userdefaults += [""] + endif + elseif fragment =~ '^%\d' + let regexp += ["\\".usergroups[strpart(fragment,1)-1]] + let template .= regexp[-1] + let default .= userdefaults[strpart(fragment,1)-1] + elseif fragment == '%*' + if len(regexp) == 1 + let regexp = [] + let targets = [] + else + let regexp += ['\(.*\)'] + endif + else + let regexp += [escape(fragment,'.*^$[\]~')] + let template .= fragment + let default .= fragment + endif + endwhile + if regexp[-1] == '\(.*\)' + call remove(regexp,-1) + call remove(targets,-1) + else + let regexp += ['\>'] + endif + return {'source': a:format, 'strftime': template, 'groups': regexp, 'regexp': s:function('s:timeregexp'), 'reader': reader, 'targets': targets, 'default': default, 'increment': s:function('s:dateincrement')} +endfunction + +function! s:comparecase(i1, i2) + if a:i1 ==? a:i2 + return a:i1 ==# a:i2 ? 0 : a:i1 ># a:i2 ? 1 : -1 + else + return tolower(a:i1) > tolower(a:i2) ? 1 : -1 + endif +endfunction + +function! s:adddate(master,count,bang) + if a:master == "" + let time = s:initializetime({'y':1970,'s':localtime(),'z': 'UTC'}) + if a:bang && a:count + silent! call remove(s:time_handlers,a:count - 1) + elseif a:bang + echo "SpeedDatingFormat List defined formats" + echo "SpeedDatingFormat! This help" + echo "SpeedDatingFormat %Y-%m-%d Add a format" + echo "1SpeedDatingFormat %Y-%m-%d Add a format before first format" + echo "SpeedDatingFormat! %Y-%m-%d Remove a format" + echo "1SpeedDatingFormat! Remove first format" + echo " " + echo "Expansions:" + for key in sort(keys(s:strftime_items),s:function("s:comparecase")) + echo printf("%2s %-25s %s",'%'.key,s:strftime_items[key][3],s:strftime('%'.key,time)) + endfor + echo '%0x %x with mandatory leading zeros' + echo '%_x %x with spaces rather than leading zeros' + echo '%-x %x with no leading spaces or zeros' + echo '%^x %x in uppercase' + echo '%* at beginning/end, surpress \</\> respectively' + echo '%[..] any one character \([..]\)' + echo '%?[..] up to one character \([..]\=\)' + echo '%1 character from first collection match \1' + echo " " + echo "Examples:" + echo 'SpeedDatingFormat %m%[/-]%d%1%Y " American 12/25/2007' + echo 'SpeedDatingFormat %d%[/-]%m%1%Y " European 25/12/2007' + echo " " + echo "Define formats in ".s:install_dir."/after/plugin/speeddating.vim" + elseif a:count + echo get(s:time_handlers,a:count-1,{'source':''}).source + else + let i = 0 + for handler in s:time_handlers + let i += 1 + echo printf("%3d %-32s %-32s",i,handler.source,s:strftime(handler.default,time)) + endfor + endif + elseif a:bang + call filter(s:time_handlers,'v:val.source != a:master') + else + let handler = s:createtimehandler(a:master) + if a:count + call insert(s:time_handlers,handler,a:count - 1) + else + let s:time_handlers += [handler] + endif + endif +endfunction + +let s:time_handlers = [] + +command! -bar -bang -count=0 -nargs=? SpeedDatingFormat :call s:adddate(<q-args>,<count>,<bang>0) + +" }}}1 +" Default Formats {{{1 + +SpeedDatingFormat %i, %d %h %Y %H:%M:%S %z " RFC822 +SpeedDatingFormat %i, %h %d, %Y at %I:%M:%S%^P %z " mutt default date format +SpeedDatingFormat %a %b %_d %H:%M:%S %Z %Y " default date(1) format +SpeedDatingFormat %a %h %-d %H:%M:%S %Y %z " git +SpeedDatingFormat %h %_d %H:%M:%S " syslog +SpeedDatingFormat %Y-%m-%d%[ T_-]%H:%M:%S %z +SpeedDatingFormat %Y-%m-%d%[ T_-]%H:%M:%S%?[Z] " SQL, etc. +SpeedDatingFormat %Y-%m-%d +SpeedDatingFormat %-I:%M:%S%?[ ]%^P +SpeedDatingFormat %-I:%M%?[ ]%^P +SpeedDatingFormat %-I%?[ ]%^P +SpeedDatingFormat %H:%M:%S +SpeedDatingFormat %B %o, %Y +SpeedDatingFormat %d%[-/ ]%b%1%y +SpeedDatingFormat %d%[-/ ]%b%1%Y " These three are common in the +SpeedDatingFormat %Y %b %d " 'Last Change:' headers of +SpeedDatingFormat %b %d, %Y " Vim runtime files +SpeedDatingFormat %^v +SpeedDatingFormat %v + +" }}}1 +" Maps {{{1 + +nnoremap <silent> <Plug>SpeedDatingUp :<C-U>call <SID>increment(v:count1)<CR> +nnoremap <silent> <Plug>SpeedDatingDown :<C-U>call <SID>increment(-v:count1)<CR> +vnoremap <silent> <Plug>SpeedDatingUp :<C-U>call <SID>incrementvisual(v:count1)<CR> +vnoremap <silent> <Plug>SpeedDatingDown :<C-U>call <SID>incrementvisual(-v:count1)<CR> +nnoremap <silent> <Plug>SpeedDatingNowLocal :<C-U>call <SID>timestamp(0,v:count)<CR> +nnoremap <silent> <Plug>SpeedDatingNowUTC :<C-U>call <SID>timestamp(1,v:count)<CR> + +if !exists("g:speeddating_no_mappings") || !g:speeddating_no_mappings + nmap <C-A> <Plug>SpeedDatingUp + nmap <C-X> <Plug>SpeedDatingDown + xmap <C-A> <Plug>SpeedDatingUp + xmap <C-X> <Plug>SpeedDatingDown + nmap d<C-A> <Plug>SpeedDatingNowUTC + nmap d<C-X> <Plug>SpeedDatingNowLocal +endif + +" }}}1 + +let &cpo = s:cpo_save + +" vim:set et sw=4 sts=4: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2011-07-21 04:50:47
|
Revision: 1801 http://assorted.svn.sourceforge.net/assorted/?rev=1801&view=rev Author: yangzhang Date: 2011-07-21 04:50:40 +0000 (Thu, 21 Jul 2011) Log Message: ----------- Add coffeescript vim support Added Paths: ----------- configs/trunk/src/vim/after/syntax/ configs/trunk/src/vim/after/syntax/html.vim configs/trunk/src/vim/ftdetect/coffee.vim configs/trunk/src/vim/ftdetect/eco.vim configs/trunk/src/vim/ftplugin/coffee.vim configs/trunk/src/vim/indent/coffee.vim configs/trunk/src/vim/syntax/coffee.vim configs/trunk/src/vim/syntax/eco.vim Added: configs/trunk/src/vim/after/syntax/html.vim =================================================================== --- configs/trunk/src/vim/after/syntax/html.vim (rev 0) +++ configs/trunk/src/vim/after/syntax/html.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,19 @@ +" Language: CoffeeScript +" Maintainer: Mick Koch <kc...@gm...> +" URL: http://github.com/kchmck/vim-coffee-script +" License: WTFPL + +if !exists("main_syntax") + let main_syntax = 'html' +endif + +" Syntax highlighting for text/coffeescript script tags +unlet b:current_syntax +syn include @htmlCoffeeScript syntax/coffee.vim +unlet b:current_syntax +syn region javaScript start=+<script [^>]*type *=[^>]*text/coffeescript[^>]*>+ keepend end=+</script>+me=s-1 contains=@htmlCoffeeScript,htmlScriptTag,@htmlPreproc +let b:current_syntax = "html" + +if main_syntax == 'html' + unlet main_syntax +endif Added: configs/trunk/src/vim/ftdetect/coffee.vim =================================================================== --- configs/trunk/src/vim/ftdetect/coffee.vim (rev 0) +++ configs/trunk/src/vim/ftdetect/coffee.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,7 @@ +" Language: CoffeeScript +" Maintainer: Mick Koch <kc...@gm...> +" URL: http://github.com/kchmck/vim-coffee-script +" License: WTFPL + +autocmd BufNewFile,BufRead *.coffee set filetype=coffee +autocmd BufNewFile,BufRead *Cakefile set filetype=coffee Added: configs/trunk/src/vim/ftdetect/eco.vim =================================================================== --- configs/trunk/src/vim/ftdetect/eco.vim (rev 0) +++ configs/trunk/src/vim/ftdetect/eco.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1 @@ +autocmd BufNewFile,BufRead *.eco set filetype=eco Added: configs/trunk/src/vim/ftplugin/coffee.vim =================================================================== --- configs/trunk/src/vim/ftplugin/coffee.vim (rev 0) +++ configs/trunk/src/vim/ftplugin/coffee.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,137 @@ +" Language: CoffeeScript +" Maintainer: Mick Koch <kc...@gm...> +" URL: http://github.com/kchmck/vim-coffee-script +" License: WTFPL + +if exists("b:did_ftplugin") + finish +endif + +let b:did_ftplugin = 1 + +" Don't let new windows overwrite these. +if !exists("s:coffee_compile_prev_buf") + " Buffer and cursor position before the `CoffeeCompile` buffer was opened + let s:coffee_compile_prev_buf = -1 + let s:coffee_compile_prev_pos = [] + " Previously-opened `CoffeeCompile` buffer + let s:coffee_compile_buf = -1 +endif + +setlocal formatoptions-=t formatoptions+=croql +setlocal comments=:# +setlocal commentstring=#\ %s + +setlocal errorformat=Error:\ In\ %f\\,\ %m\ on\ line\ %l, + \Error:\ In\ %f\\,\ Parse\ error\ on\ line\ %l:\ %m, + \SyntaxError:\ In\ %f\\,\ %m, + \%-G%.%# + +" Fold by indentation, but only if enabled. +setlocal foldmethod=indent + +if !exists("coffee_folding") + setlocal nofoldenable +endif + +" Extra options passed to `CoffeeMake` +if !exists("coffee_make_options") + let coffee_make_options = "" +endif + +" Update `makeprg` for the current filename. This is needed to support filenames +" with spaces and quotes while also supporting generic `make`. +function! s:SetMakePrg() + let &l:makeprg = "coffee -c " . g:coffee_make_options . ' $* ' + \ . fnameescape(expand('%')) +endfunction + +" Set `makeprg` initially. +call s:SetMakePrg() +" Reset `makeprg` on rename. +autocmd BufFilePost,BufWritePost,FileWritePost <buffer> call s:SetMakePrg() + +" Save the cursor position. +function! s:CoffeeCompileSavePos() + let buf = bufnr('%') + + if buf != s:coffee_compile_buf + let s:coffee_compile_prev_buf = buf + let s:coffee_compile_prev_pos = getpos('.') + endif +endfunction + +" Try to reset the cursor position. +function! s:CoffeeCompileResetPos() + let win = bufwinnr(s:coffee_compile_prev_buf) + + if win != -1 + exec win 'wincmd w' + call setpos('.', s:coffee_compile_prev_pos) + endif + + autocmd! CoffeeCompileSavePos +endfunction + +" Compile some CoffeeScript and show it in a scratch buffer. We handle ranges +" like this to stop the cursor from being moved before the function is called. +function! s:CoffeeCompile(startline, endline) + " Store the current buffer and cursor. + call s:CoffeeCompileSavePos() + + " Build stdin lines. + let lines = join(getline(a:startline, a:endline), "\n") + " Get compiler output. + let output = system('coffee -scb 2>&1', lines) + + " Use at most half of the screen. + let max_height = winheight('%') / 2 + " Try to get the old window. + let win = bufwinnr(s:coffee_compile_buf) + + if win == -1 + " Make a new window and store its ID. + botright new + let s:coffee_compile_buf = bufnr('%') + + setlocal bufhidden=wipe buftype=nofile + setlocal nobuflisted noswapfile nowrap + + autocmd BufWipeout <buffer> call s:CoffeeCompileResetPos() + nnoremap <buffer> <silent> q :hide<CR> + + " Save the cursor position on each buffer switch. + augroup CoffeeCompileSavePos + autocmd BufEnter,BufLeave * call s:CoffeeCompileSavePos() + augroup END + else + " Move to the old window and clear the buffer. + exec win 'wincmd w' + setlocal modifiable + exec '% delete _' + endif + + " Paste in the output and delete the last empty line. + put! =output + exec '$ delete _' + + exec 'resize' min([max_height, line('$') + 1]) + call cursor(1, 1) + + if v:shell_error + " A compile error occurred. + setlocal filetype= + else + " Coffee was compiled successfully. + setlocal filetype=javascript + endif + + setlocal nomodifiable +endfunction + +" Peek at compiled CoffeeScript. +command! -range=% -bar CoffeeCompile call s:CoffeeCompile(<line1>, <line2>) +" Compile the current file. +command! -bang -bar -nargs=* CoffeeMake make<bang> <args> +" Run some CoffeeScript. +command! -range=% -bar CoffeeRun <line1>,<line2>:w !coffee -s Added: configs/trunk/src/vim/indent/coffee.vim =================================================================== --- configs/trunk/src/vim/indent/coffee.vim (rev 0) +++ configs/trunk/src/vim/indent/coffee.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,322 @@ +" Language: CoffeeScript +" Maintainer: Mick Koch <kc...@gm...> +" URL: http://github.com/kchmck/vim-coffee-script +" License: WTFPL + +if exists("b:did_indent") + finish +endif + +let b:did_indent = 1 + +setlocal autoindent +setlocal indentexpr=GetCoffeeIndent(v:lnum) +" Make sure GetCoffeeIndent is run when these are typed so they can be +" indented or outdented. +setlocal indentkeys+=0],0),0.,=else,=when,=catch,=finally + +" Only define the function once. +if exists("*GetCoffeeIndent") + finish +endif + +" Keywords to indent after +let s:INDENT_AFTER_KEYWORD = '^\%(if\|unless\|else\|for\|while\|until\|' +\ . 'loop\|switch\|when\|try\|catch\|finally\|' +\ . 'class\)\>' + +" Operators to indent after +let s:INDENT_AFTER_OPERATOR = '\%([([{:=]\|[-=]>\)$' + +" Keywords and operators that continue a line +let s:CONTINUATION = '\<\%(is\|isnt\|and\|or\)\>$' +\ . '\|' +\ . '\%(-\@<!-\|+\@<!+\|<\|[-=]\@<!>\|\*\|/\@<!/\|%\||\|' +\ . '&\|,\|\.\@<!\.\)$' + +" Operators that block continuation indenting +let s:CONTINUATION_BLOCK = '[([{:=]$' + +" A continuation dot access +let s:DOT_ACCESS = '^\.' + +" Keywords to outdent after +let s:OUTDENT_AFTER = '^\%(return\|break\|continue\|throw\)\>' + +" A compound assignment like `... = if ...` +let s:COMPOUND_ASSIGNMENT = '[:=]\s*\%(if\|unless\|for\|while\|until\|' +\ . 'switch\|try\|class\)\>' + +" A postfix condition like `return ... if ...`. +let s:POSTFIX_CONDITION = '\S\s\+\zs\<\%(if\|unless\)\>' + +" A single-line else statement like `else ...` but not `else if ... +let s:SINGLE_LINE_ELSE = '^else\s\+\%(\<\%(if\|unless\)\>\)\@!' + +" Max lines to look back for a match +let s:MAX_LOOKBACK = 50 + +" Syntax names for strings +let s:SYNTAX_STRING = 'coffee\%(String\|AssignString\|Embed\|Regex\|Heregex\|' +\ . 'Heredoc\)' + +" Syntax names for comments +let s:SYNTAX_COMMENT = 'coffee\%(Comment\|BlockComment\|HeregexComment\)' + +" Syntax names for strings and comments +let s:SYNTAX_STRING_COMMENT = s:SYNTAX_STRING . '\|' . s:SYNTAX_COMMENT + +" Get the linked syntax name of a character. +function! s:SyntaxName(linenum, col) + return synIDattr(synID(a:linenum, a:col, 1), 'name') +endfunction + +" Check if a character is in a comment. +function! s:IsComment(linenum, col) + return s:SyntaxName(a:linenum, a:col) =~ s:SYNTAX_COMMENT +endfunction + +" Check if a character is in a string. +function! s:IsString(linenum, col) + return s:SyntaxName(a:linenum, a:col) =~ s:SYNTAX_STRING +endfunction + +" Check if a character is in a comment or string. +function! s:IsCommentOrString(linenum, col) + return s:SyntaxName(a:linenum, a:col) =~ s:SYNTAX_STRING_COMMENT +endfunction + +" Check if a whole line is a comment. +function! s:IsCommentLine(linenum) + " Check the first non-whitespace character. + return s:IsComment(a:linenum, indent(a:linenum) + 1) +endfunction + +" Repeatedly search a line for a regex until one is found outside a string or +" comment. +function! s:SmartSearch(linenum, regex) + " Start at the first column. + let col = 0 + + " Search until there are no more matches, unless a good match is found. + while 1 + call cursor(a:linenum, col + 1) + let [_, col] = searchpos(a:regex, 'cn', a:linenum) + + " No more matches. + if !col + break + endif + + if !s:IsCommentOrString(a:linenum, col) + return 1 + endif + endwhile + + " No good match found. + return 0 +endfunction + +" Skip a match if it's in a comment or string, is a single-line statement that +" isn't adjacent, or is a postfix condition. +function! s:ShouldSkip(startlinenum, linenum, col) + if s:IsCommentOrString(a:linenum, a:col) + return 1 + endif + + " Check for a single-line statement that isn't adjacent. + if s:SmartSearch(a:linenum, '\<then\>') && a:startlinenum - a:linenum > 1 + return 1 + endif + + if s:SmartSearch(a:linenum, s:POSTFIX_CONDITION) && + \ !s:SmartSearch(a:linenum, s:COMPOUND_ASSIGNMENT) + return 1 + endif + + return 0 +endfunction + +" Find the farthest line to look back to, capped to line 1 (zero and negative +" numbers cause bad things). +function! s:MaxLookback(startlinenum) + return max([1, a:startlinenum - s:MAX_LOOKBACK]) +endfunction + +" Get the skip expression for searchpair(). +function! s:SkipExpr(startlinenum) + return "s:ShouldSkip(" . a:startlinenum . ", line('.'), col('.'))" +endfunction + +" Search for pairs of text. +function! s:SearchPair(start, end) + " The cursor must be in the first column for regexes to match. + call cursor(0, 1) + + let startlinenum = line('.') + + " Don't need the W flag since MaxLookback caps the search to line 1. + return searchpair(a:start, '', a:end, 'bcn', + \ s:SkipExpr(startlinenum), + \ s:MaxLookback(startlinenum)) +endfunction + +" Try to find a previous matching line. +function! s:GetMatch(curline) + let firstchar = a:curline[0] + + if firstchar == '}' + return s:SearchPair('{', '}') + elseif firstchar == ')' + return s:SearchPair('(', ')') + elseif firstchar == ']' + return s:SearchPair('\[', '\]') + elseif a:curline =~ '^else\>' + return s:SearchPair('\<\%(if\|unless\|when\)\>', '\<else\>') + elseif a:curline =~ '^catch\>' + return s:SearchPair('\<try\>', '\<catch\>') + elseif a:curline =~ '^finally\>' + return s:SearchPair('\<try\>', '\<finally\>') + endif + + return 0 +endfunction + +" Get the nearest previous line that isn't a comment. +function! s:GetPrevNormalLine(startlinenum) + let curlinenum = a:startlinenum + + while curlinenum > 0 + let curlinenum = prevnonblank(curlinenum - 1) + + if !s:IsCommentLine(curlinenum) + return curlinenum + endif + endwhile + + return 0 +endfunction + +" Try to find a comment in a line. +function! s:FindComment(linenum) + let col = 0 + + while 1 + call cursor(a:linenum, col + 1) + let [_, col] = searchpos('#', 'cn', a:linenum) + + if !col + break + endif + + if s:IsComment(a:linenum, col) + return col + endif + endwhile + + return 0 +endfunction + +" Get a line without comments or surrounding whitespace. +function! s:GetTrimmedLine(linenum) + let comment = s:FindComment(a:linenum) + let line = getline(a:linenum) + + if comment + " Subtract 1 to get to the column before the comment and another 1 for + " zero-based indexing. + let line = line[:comment - 2] + endif + + return substitute(substitute(line, '^\s\+', '', ''), + \ '\s\+$', '', '') +endfunction + +function! s:GetCoffeeIndent(curlinenum) + let prevlinenum = s:GetPrevNormalLine(a:curlinenum) + + " Don't do anything if there's no previous line. + if !prevlinenum + return -1 + endif + + let curline = s:GetTrimmedLine(a:curlinenum) + + " Try to find a previous matching statement. This handles outdenting. + let matchlinenum = s:GetMatch(curline) + + if matchlinenum + return indent(matchlinenum) + endif + + " Try to find a matching `when`. + if curline =~ '^when\>' && !s:SmartSearch(prevlinenum, '\<switch\>') + let linenum = a:curlinenum + + while linenum > 0 + let linenum = s:GetPrevNormalLine(linenum) + + if getline(linenum) =~ '^\s*when\>' + return indent(linenum) + endif + endwhile + + return -1 + endif + + let prevline = s:GetTrimmedLine(prevlinenum) + let previndent = indent(prevlinenum) + + " Always indent after these operators. + if prevline =~ s:INDENT_AFTER_OPERATOR + return previndent + &shiftwidth + endif + + " Indent after a continuation if it's the first. + if prevline =~ s:CONTINUATION + let prevprevlinenum = s:GetPrevNormalLine(prevlinenum) + let prevprevline = s:GetTrimmedLine(prevprevlinenum) + + if prevprevline !~ s:CONTINUATION && prevprevline !~ s:CONTINUATION_BLOCK + return previndent + &shiftwidth + endif + + return -1 + endif + + " Indent after these keywords and compound assignments if they aren't a + " single-line statement. + if prevline =~ s:INDENT_AFTER_KEYWORD || prevline =~ s:COMPOUND_ASSIGNMENT + if !s:SmartSearch(prevlinenum, '\<then\>') && prevline !~ s:SINGLE_LINE_ELSE + return previndent + &shiftwidth + endif + + return -1 + endif + + " Indent a dot access if it's the first. + if curline =~ s:DOT_ACCESS && prevline !~ s:DOT_ACCESS + return previndent + &shiftwidth + endif + + " Outdent after these keywords if they don't have a postfix condition or are + " a single-line statement. + if prevline =~ s:OUTDENT_AFTER + if !s:SmartSearch(prevlinenum, s:POSTFIX_CONDITION) || + \ s:SmartSearch(prevlinenum, '\<then\>') + return previndent - &shiftwidth + endif + endif + + " No indenting or outdenting is needed. + return -1 +endfunction + +" Wrap s:GetCoffeeIndent to keep the cursor position. +function! GetCoffeeIndent(curlinenum) + let oldcursor = getpos('.') + let indent = s:GetCoffeeIndent(a:curlinenum) + call setpos('.', oldcursor) + + return indent +endfunction Added: configs/trunk/src/vim/syntax/coffee.vim =================================================================== --- configs/trunk/src/vim/syntax/coffee.vim (rev 0) +++ configs/trunk/src/vim/syntax/coffee.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,214 @@ +" Language: CoffeeScript +" Maintainer: Mick Koch <kc...@gm...> +" URL: http://github.com/kchmck/vim-coffee-script +" License: WTFPL + +if exists("b:current_syntax") + finish +endif + +if version < 600 + syn clear +endif + +" Include JavaScript for coffeeEmbed. +syn include @coffeeJS syntax/javascript.vim + +" Highlight long strings. +syn sync minlines=100 + +" CoffeeScript allows dollar signs in identifiers. +setlocal isident+=$ + +" These are `matches` instead of `keywords` because vim's highlighting +" priority for keywords is higher than matches. This causes keywords to be +" highlighted inside matches, even if a match says it shouldn't contain them -- +" like with coffeeAssign and coffeeDot. +syn match coffeeStatement /\<\%(return\|break\|continue\|throw\)\>/ +hi def link coffeeStatement Statement + +syn match coffeeRepeat /\<\%(for\|while\|until\|loop\)\>/ +hi def link coffeeRepeat Repeat + +syn match coffeeConditional /\<\%(if\|else\|unless\|switch\|when\|then\)\>/ +hi def link coffeeConditional Conditional + +syn match coffeeException /\<\%(try\|catch\|finally\)\>/ +hi def link coffeeException Exception + +syntax match coffeeOperator /\<\%(instanceof\|typeof\|delete\)\>/ +hi def link coffeeOperator Operator + +syn match coffeeKeyword /\<\%(new\|in\|of\|by\|and\|or\|not\|is\|isnt\|class\|extends\|super\|own\|do\)\>/ +hi def link coffeeKeyword Keyword + +syn match coffeeBoolean /\<\%(true\|on\|yes\|false\|off\|no\)\>/ +hi def link coffeeBoolean Boolean + +syn match coffeeGlobal /\<\%(null\|undefined\)\>/ +hi def link coffeeGlobal Type + +" Keywords reserved by the language +syn cluster coffeeReserved contains=coffeeStatement,coffeeRepeat, +\ coffeeConditional,coffeeException, +\ coffeeOperator,coffeeKeyword, +\ coffeeBoolean,coffeeGlobal + +" A special variable +syn match coffeeSpecialVar /\<\%(this\|prototype\|arguments\)\>/ +" An @-variable +syn match coffeeSpecialVar /@\%(\I\i*\)\?/ +hi def link coffeeSpecialVar Type + +" A class-like name that starts with a capital letter +syn match coffeeObject /\<\u\w*\>/ +hi def link coffeeObject Structure + +" A constant-like name in SCREAMING_CAPS +syn match coffeeConstant /\<\u[A-Z0-9_]\+\>/ +hi def link coffeeConstant Constant + +" A variable name +syn cluster coffeeIdentifier contains=coffeeSpecialVar,coffeeObject, +\ coffeeConstant,coffeePrototype + +" A non-interpolated string +syn cluster coffeeBasicString contains=@Spell,coffeeEscape +" An interpolated string +syn cluster coffeeInterpString contains=@coffeeBasicString,coffeeInterp + +" Regular strings +syn region coffeeString start=/"/ skip=/\\\\\|\\"/ end=/"/ +\ contains=@coffeeInterpString +syn region coffeeString start=/'/ skip=/\\\\\|\\'/ end=/'/ +\ contains=@coffeeBasicString +hi def link coffeeString String + +" A integer, including a leading plus or minus +syn match coffeeNumber /\i\@<![-+]\?\d\+\%([eE][+-]\?\d\+\)\?/ +" A hex number +syn match coffeeNumber /\<0[xX]\x\+\>/ +hi def link coffeeNumber Number + +" A floating-point number, including a leading plus or minus +syn match coffeeFloat /\i\@<![-+]\?\d*\.\@<!\.\d\+\%([eE][+-]\?\d\+\)\?/ +hi def link coffeeFloat Float + +syn match coffeeAssignSymbols /:\@<!::\@!\|++\|--\|\%(\s\zs\%(and\|or\)\|&&\|||\|?\|+\|-\|\/\|\*\|%\|<<\|>>\|>>>\|&\||\|\^\)\?=\@<!==\@!>\@!/ +\ contained +hi def link coffeeAssignSymbols SpecialChar + +syn match coffeeAssignBrackets /\[.\+\]/ contained contains=TOP,coffeeAssign + +" A destructuring assignment +syn match coffeeAssign /[}\]]\@<=\s*==\@!>\@!/ contains=coffeeAssignSymbols +" A pre-increment or pre-decrement assignment +syn match coffeeAssign /\%(++\|--\)\s*\%(@\|@\?\I\)\%(\i\|::\|\.\|?\|\[.\+\]\)*/ +\ contains=@coffeeIdentifier,coffeeAssignSymbols, +\ coffeeAssignBrackets +" A normal assignment, or a post-increment or post-decrement assignment +syn match coffeeAssign /\%(@\|@\?\I\)\%(\i\|::\|\.\|?\|\[.\+\]\)*\%(++\|--\|\s*\%(and\|or\|&&\|||\|?\|+\|-\|\/\|\*\|%\|<<\|>>\|>>>\|&\||\|\^\)\?=\@<!==\@!>\@!\)/ +\ contains=@coffeeIdentifier,coffeeAssignSymbols, +\ coffeeAssignBrackets +hi def link coffeeAssign Identifier + +" An error for reserved keywords +if !exists("coffee_no_reserved_words_error") + syn match coffeeReservedError /\<\%(case\|default\|function\|var\|void\|with\|const\|let\|enum\|export\|import\|native\|__hasProp\|__extends\|__slice\|__bind\|__indexOf\)\>/ + hi def link coffeeReservedError Error +endif + +" A normal object assignment +syn match coffeeObjAssign /@\?\I\i*\s*:\@<!::\@!/ +\ contains=@coffeeIdentifier,coffeeAssignSymbols +hi def link coffeeObjAssign coffeeAssign + +" Strings used in string assignments, which can't have interpolations +syn region coffeeAssignString start=/"/ skip=/\\\\\|\\"/ end=/"/ +\ contained contains=@coffeeBasicString +syn region coffeeAssignString start=/'/ skip=/\\\\\|\\'/ end=/'/ +\ contained contains=@coffeeBasicString +hi def link coffeeAssignString String + +" An object-string assignment +syn match coffeeObjStringAssign /\("\|'\)[^\1]*\1\s*;\@<!::\@!'\@!/ +\ contains=coffeeAssignString,coffeeAssignSymbols +" An object-integer assignment +syn match coffeeObjNumberAssign /\d\+\%(\.\d\+\)\?\s*:\@<!::\@!/ +\ contains=coffeeNumber,coffeeAssignSymbols + +syn match coffeePrototype /::/ +hi def link coffeePrototype SpecialChar + +syn match coffeeFunction /[-=]>/ +hi def link coffeeFunction Function + +syn keyword coffeeTodo TODO FIXME XXX contained +hi def link coffeeTodo Todo + +syn match coffeeComment /#.*/ contains=@Spell,coffeeTodo +hi def link coffeeComment Comment + +syn region coffeeBlockComment start=/####\@!/ end=/###/ +\ contains=@Spell,coffeeTodo +hi def link coffeeBlockComment coffeeComment + +" A comment in a heregex +syn region coffeeHeregexComment start=/#/ end=/\ze\/\/\/\|$/ +\ contained contains=@Spell,coffeeTodo +hi def link coffeeHeregexComment coffeeComment + +" Embedded JavaScript +syn region coffeeEmbed matchgroup=coffeeEmbedDelim +\ start=/`/ skip=/\\\\\|\\`/ end=/`/ +\ contains=@coffeeJS +hi def link coffeeEmbedDelim Delimiter + +syn region coffeeInterp matchgroup=coffeeInterpDelim +\ start=/\#{/ end=/}/ +\ contained contains=TOP +hi def link coffeeInterpDelim Delimiter + +" A string escape sequence +syn match coffeeEscape /\\\d\d\d\|\\x\x\{2\}\|\\u\x\{4\}\|\\./ contained +hi def link coffeeEscape SpecialChar + +" A regex -- must not follow a parenthesis, number, or identifier, and must not +" be followed by a number +syn region coffeeRegex start=/\%(\%()\|\i\@<!\d\)\s*\|\i\)\@<!\/\s\@!/ +\ skip=/\[[^\]]\{-}\/[^\]]\{-}\]/ +\ end=/\/[gimy]\{,4}\d\@!/ +\ oneline contains=@coffeeBasicString +hi def link coffeeRegex String + +" A heregex +syn region coffeeHeregex start=/\/\/\// end=/\/\/\/[gimy]\{,4}/ +\ contains=@coffeeInterpString,coffeeHeregexComment +\ fold +hi def link coffeeHeregex coffeeRegex + +" Heredoc strings +syn region coffeeHeredoc start=/"""/ end=/"""/ contains=@coffeeInterpString +\ fold +syn region coffeeHeredoc start=/'''/ end=/'''/ contains=@coffeeBasicString +\ fold +hi def link coffeeHeredoc String + +" An error for trailing whitespace, as long as the line isn't just whitespace +if !exists("coffee_no_trailing_space_error") + syn match coffeeSpaceError /\S\@<=\s\+$/ display + hi def link coffeeSpaceError Error +endif + +" An error for trailing semicolons, for help transitioning from JavaScript +if !exists("coffee_no_trailing_semicolon_error") + syn match coffeeSemicolonError /;$/ display + hi def link coffeeSemicolonError Error +endif + +" Ignore reserved words in dot-properties. +syn match coffeeDot /\.\@<!\.\i\+/ contains=ALLBUT,@coffeeReserved, +\ coffeeReservedError +\ transparent + +let b:current_syntax = "coffee" Property changes on: configs/trunk/src/vim/syntax/coffee.vim ___________________________________________________________________ Added: svn:executable + * Added: configs/trunk/src/vim/syntax/eco.vim =================================================================== --- configs/trunk/src/vim/syntax/eco.vim (rev 0) +++ configs/trunk/src/vim/syntax/eco.vim 2011-07-21 04:50:40 UTC (rev 1801) @@ -0,0 +1,62 @@ +" Vim syntax file +" Language: eco +" Maintainer: Jay Adkisson +" Mostly stolen from eruby.vim + +if !exists("g:eco_default_subtype") + let g:eco_default_subtype = "html" +endif + +if !exists("b:eco_subtype") + let s:lines = getline(1)."\n".getline(2)."\n".getline(3)."\n".getline(4)."\n".getline(5)."\n".getline("$") + let b:eco_subtype = matchstr(s:lines,'eco_subtype=\zs\w\+') + if b:eco_subtype == '' + let b:eco_subtype = matchstr(substitute(expand("%:t"),'\c\%(\.eco\)\+$','',''),'\.\zs\w\+$') + endif + if b:eco_subtype == 'rhtml' + let b:eco_subtype = 'html' + elseif b:eco_subtype == 'rb' + let b:eco_subtype = 'ruby' + elseif b:eco_subtype == 'yml' + let b:eco_subtype = 'yaml' + elseif b:eco_subtype == 'js' || b:eco_subtype == 'json' + let b:eco_subtype = 'javascript' + elseif b:eco_subtype == 'txt' + " Conventional; not a real file type + let b:eco_subtype = 'text' + elseif b:eco_subtype == '' + if exists('b:current_syntax') && b:current_syntax != '' + let b:eco_subtype = b:current_syntax + else + let b:eco_subtype = g:eco_default_subtype + endif + endif +endif + +if exists("b:eco_subtype") && b:eco_subtype != '' && b:eco_subtype != 'eco' + exec "runtime! syntax/".b:eco_subtype.".vim" + let b:current_syntax = "eco" +endif + +syn include @coffeeTop syntax/coffee.vim + +syn cluster ecoRegions contains=ecoBlock,ecoExpression,ecoComment + +syn region ecoBlock matchgroup=ecoDelimiter start=/<%/ end=/%>/ contains=@coffeeTop containedin=ALLBUT,@ecoRegions keepend +syn region ecoExpression matchgroup=ecoDelimiter start=/<%[=\-]/ end=/%>/ contains=@coffeeTop containedin=ALLBUT,@ecoRegions keepend +syn region ecoComment matchgroup=ecoComment start=/<%#/ end=/%>/ contains=@coffeeTodo,@Spell containedin=ALLBUT,@ecoRegions keepend + +" eco features not in coffeescript proper +syn keyword ecoEnd end containedin=@ecoRegions +syn match ecoIndentColon /\s+\w+:/ containedin=@ecoRegions + +" Define the default highlighting. + +hi def link ecoDelimiter Delimiter +hi def link ecoComment Comment +hi def link ecoEnd coffeeConditional +hi def link ecoIndentColon None + +let b:current_syntax = 'eco' + +" vim: nowrap sw=2 sts=2 ts=8: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2011-07-21 05:45:36
|
Revision: 1803 http://assorted.svn.sourceforge.net/assorted/?rev=1803&view=rev Author: yangzhang Date: 2011-07-21 05:45:29 +0000 (Thu, 21 Jul 2011) Log Message: ----------- Add jade vim support Added Paths: ----------- configs/trunk/src/vim/ftdetect/jade.vim configs/trunk/src/vim/ftplugin/jade.vim configs/trunk/src/vim/indent/jade.vim configs/trunk/src/vim/syntax/jade.vim Added: configs/trunk/src/vim/ftdetect/jade.vim =================================================================== --- configs/trunk/src/vim/ftdetect/jade.vim (rev 0) +++ configs/trunk/src/vim/ftdetect/jade.vim 2011-07-21 05:45:29 UTC (rev 1803) @@ -0,0 +1,2 @@ +" Jade +autocmd BufNewFile,BufReadPost *.jade set filetype=jade Added: configs/trunk/src/vim/ftplugin/jade.vim =================================================================== --- configs/trunk/src/vim/ftplugin/jade.vim (rev 0) +++ configs/trunk/src/vim/ftplugin/jade.vim 2011-07-21 05:45:29 UTC (rev 1803) @@ -0,0 +1,53 @@ +" Vim filetype plugin +" Language: Jade +" Maintainer: Joshua Borton +" Credits: Tim Pope + +" Only do this when not done yet for this buffer +if exists("b:did_ftplugin") + finish +endif + +let s:save_cpo = &cpo +set cpo-=C + +" Define some defaults in case the included ftplugins don't set them. +let s:undo_ftplugin = "" +let s:browsefilter = "All Files (*.*)\t*.*\n" +let s:match_words = "" + +runtime! ftplugin/html.vim ftplugin/html_*.vim ftplugin/html/*.vim +unlet! b:did_ftplugin + +" Override our defaults if these were set by an included ftplugin. +if exists("b:undo_ftplugin") + let s:undo_ftplugin = b:undo_ftplugin + unlet b:undo_ftplugin +endif +if exists("b:browsefilter") + let s:browsefilter = b:browsefilter + unlet b:browsefilter +endif +if exists("b:match_words") + let s:match_words = b:match_words + unlet b:match_words +endif + +" Change the browse dialog on Win32 to show mainly Haml-related files +if has("gui_win32") + let b:browsefilter="Jade Files (*.jade)\t*.jade\n" . s:browsefilter +endif + +" Load the combined list of match_words for matchit.vim +if exists("loaded_matchit") + let b:match_words = s:match_words +endif + +setlocal comments= commentstring=-#\ %s + +let b:undo_ftplugin = "setl cms< com< " + \ " | unlet! b:browsefilter b:match_words | " . s:undo_ftplugin + +let &cpo = s:save_cpo + +" vim:set sw=2: Added: configs/trunk/src/vim/indent/jade.vim =================================================================== --- configs/trunk/src/vim/indent/jade.vim (rev 0) +++ configs/trunk/src/vim/indent/jade.vim 2011-07-21 05:45:29 UTC (rev 1803) @@ -0,0 +1,70 @@ +" Vim indent file +" Language: Jade +" Maintainer: Joshua Borton +" Credits: Tim Pope (vim-jade) +" Last Change: 2010 Sep 22 + +if exists("b:did_indent") + finish +endif + +unlet! b:did_indent +let b:did_indent = 1 + +setlocal autoindent sw=2 et +setlocal indentexpr=GetJadeIndent() +setlocal indentkeys=o,O,*<Return>,},],0),!^F + +" Only define the function once. +if exists("*GetJadeIndent") + finish +endif + +let s:attributes = '\%((.\{-\})\)' +let s:tag = '\([%.#][[:alnum:]_-]\+\|'.s:attributes.'\)*[<>]*' + +if !exists('g:jade_self_closing_tags') + let g:jade_self_closing_tags = 'meta|link|img|hr|br' +endif + +setlocal formatoptions+=r +setlocal comments+=n:\| + +function! GetJadeIndent() + let lnum = prevnonblank(v:lnum-1) + if lnum == 0 + return 0 + endif + let line = substitute(getline(lnum),'\s\+$','','') + let cline = substitute(substitute(getline(v:lnum),'\s\+$','',''),'^\s\+','','') + let lastcol = strlen(line) + let line = substitute(line,'^\s\+','','') + let indent = indent(lnum) + let cindent = indent(v:lnum) + let increase = indent + &sw + if indent == indent(lnum) + let indent = cindent <= indent ? -1 : increase + endif + + let group = synIDattr(synID(lnum,lastcol,1),'name') + + if line =~ '^!!!' + return indent + elseif line =~ '^/\%(\[[^]]*\]\)\=$' + return increase + elseif group == 'jadeFilter' + return increase + elseif line =~ '^'.s:tag.'[&!]\=[=~-].*,\s*$' + return increase + elseif line == '-#' + return increase + elseif line =~? '^\v%('.g:jade_self_closing_tags.')>' + return indent + elseif group =~? '\v^%(jadeTag|jadeAttributesDelimiter|jadeClass|jadeId|htmlTagName|htmlSpecialTagName)$' + return increase + else + return indent + endif +endfunction + +" vim:set sw=2: Added: configs/trunk/src/vim/syntax/jade.vim =================================================================== --- configs/trunk/src/vim/syntax/jade.vim (rev 0) +++ configs/trunk/src/vim/syntax/jade.vim 2011-07-21 05:45:29 UTC (rev 1803) @@ -0,0 +1,65 @@ +" Vim syntax file +" Language: Jade +" Maintainer: Joshua Borton +" Credits: Tim Pope +" Filenames: *.jade + +if exists("b:current_syntax") + finish +endif + +if !exists("main_syntax") + let main_syntax = 'jade' +endif + +runtime! syntax/html.vim +unlet! b:current_syntax + +syn case match + +syn cluster jadeTop contains=jadeBegin,jadeComment +syn match jadeBegin "^\s*\%([<>]\|&[^=~ ]\)\@!" nextgroup=jadeTag,jadeClassChar,jadeIdChar,jadePlainChar +syn match jadeTag "\w\+\%(:\w\+\)\=" contained contains=htmlTagName,htmlSpecialTagName nextgroup=@jadeComponent +syn cluster jadeComponent contains=jadeAttributes,jadeIdChar,jadeClassChar,jadePlainChar +syn match jadeComment ' *\/\/.*$' +syn region jadeAttributes matchgroup=jadeAttributesDelimiter start="(" skip=+\%(\\\\\)*\\'+ end=")" contained contains=htmlArg,jadeAttributeString,htmlEvent,htmlCssDefinition nextgroup=@jadeComponent +syn match jadeClassChar "\." contained nextgroup=jadeClass +syn match jadeIdChar "#{\@!" contained nextgroup=jadeId +syn match jadeClass "\%(\w\|-\)\+" contained nextgroup=@jadeComponent +syn match jadeId "\%(\w\|-\)\+" contained nextgroup=@jadeComponent +syn region jadeDocType start="^\s*!!!" end="$" + +syn match jadePlainChar "\\" contained +syn region jadeInterpolation matchgroup=jadeInterpolationDelimiter start="#{" end="}" contains=@htmlJavaScript +syn match jadeInterpolationEscape "\\\@<!\%(\\\\\)*\\\%(\\\ze#{\|#\ze{\)" + +syn region jadeAttributeString start=+\%(=\s*\)\@<='+ skip=+\%(\\\\\)*\\'+ end=+'+ contains=jadeInterpolation +syn region jadeAttributeString start=+\%(:\s*\)\@<='+ skip=+\%(\\\\\)*\\'+ end=+'+ contains=jadeInterpolation +syn region jadeAttributeString start=+\%(=\s*\)\@<="+ skip=+\%(\\\\\)*\\'+ end=+"+ contains=jadeInterpolation +syn region jadeAttributeString start=+\%(:\s*\)\@<="+ skip=+\%(\\\\\)*\\'+ end=+"+ contains=jadeInterpolation + +syn region jadeJavascriptFilter matchgroup=jadeFilter start="^\z(\s*\):javascript\s*$" end="^\%(\z1 \| *$\)\@!" contains=@htmlJavaScript +syn region jadeMarkdownFilter matchgroup=jadeFilter start="^\z(\s*\):markdown\s*$" end="^\%(\z1 \| *$\)\@!" + +syn region jadeJavascriptBlock start="^\z(\s*\)script" nextgroup=@jadeComponent,jadeError end="^\%(\z1 \| *$\)\@!" contains=@jadeTop,@htmlJavascript keepend +syn region jadeCssBlock start="^\z(\s*\)style" nextgroup=@jadeComponent,jadeError end="^\%(\z1 \| *$\)\@!" contains=@jadeTop,@htmlCss keepend + +syn match jadeError "\$" contained + +hi def link jadeTag Special +hi def link jadeAttributeString String +hi def link jadeAttributesDelimiter Identifier +hi def link jadeIdChar Special +hi def link jadeClassChar Special +hi def link jadeId Identifier +hi def link jadeClass Type +hi def link jadeInterpolationDelimiter Delimiter +hi def link jadeFilter PreProc +hi def link jadeDocType PreProc +hi def link jadeComment Comment + +let b:current_syntax = "jade" + +if main_syntax == "jade" + unlet main_syntax +endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |