From 256b0cc80f5b90c12ff8a57420c9afe32f10f65e Mon Sep 17 00:00:00 2001 From: Mathieu Date: Sun, 1 Nov 2009 19:04:42 +0100 Subject: [PATCH] Add vim plugins --- .vim/after/ftplugin/c.vim | 2 + .vim/after/ftplugin/cpp.vim | 2 + .vim/autoload/omni/common/debug.vim | 32 + .vim/autoload/omni/common/utils.vim | 67 + .vim/autoload/omni/cpp/complete.vim | 569 +++++ .vim/autoload/omni/cpp/includes.vim | 126 + .vim/autoload/omni/cpp/items.vim | 660 ++++++ .vim/autoload/omni/cpp/maycomplete.vim | 82 + .vim/autoload/omni/cpp/namespaces.vim | 838 +++++++ .vim/autoload/omni/cpp/settings.vim | 96 + .vim/autoload/omni/cpp/tokenizer.vim | 93 + .vim/autoload/omni/cpp/utils.vim | 587 +++++ .vim/doc/NERD_tree.txt | 980 ++++++++ .vim/doc/omnicppcomplete.txt | 1078 +++++++++ .vim/doc/project.txt | 710 ++++++ .vim/doc/taglist.txt | 1501 ++++++++++++ .vim/doc/tags | 229 ++ .vim/doc/vcscommand.txt | 771 +++++++ .vim/ftplugin/git.vim | 70 + .vim/ftplugin/svn.vim | 57 + .vim/plugin/NERD_tree.vim | 2913 ++++++++++++++++++++++++ .vim/plugin/project.vim | 1293 +++++++++++ .vim/plugin/vcscommand.vim | 1255 ++++++++++ .vim/plugin/vcscvs.vim | 437 ++++ .vim/plugin/vcsgit.vim | 254 +++ .vim/plugin/vcssvk.vim | 258 +++ .vim/plugin/vcssvn.vim | 284 +++ .vim/syntax/CVSAnnotate.vim | 45 + .vim/syntax/SVKAnnotate.vim | 42 + .vim/syntax/SVNAnnotate.vim | 40 + .vim/syntax/git.vim | 36 + .vim/syntax/vcscommit.vim | 31 + 32 files changed, 15438 insertions(+) create mode 100644 .vim/after/ftplugin/c.vim create mode 100644 .vim/after/ftplugin/cpp.vim create mode 100644 .vim/autoload/omni/common/debug.vim create mode 100644 .vim/autoload/omni/common/utils.vim create mode 100644 .vim/autoload/omni/cpp/complete.vim create mode 100644 .vim/autoload/omni/cpp/includes.vim create mode 100644 .vim/autoload/omni/cpp/items.vim create mode 100644 .vim/autoload/omni/cpp/maycomplete.vim create mode 100644 .vim/autoload/omni/cpp/namespaces.vim create mode 100644 .vim/autoload/omni/cpp/settings.vim create mode 100644 .vim/autoload/omni/cpp/tokenizer.vim create mode 100644 .vim/autoload/omni/cpp/utils.vim create mode 100644 .vim/doc/NERD_tree.txt create mode 100644 .vim/doc/omnicppcomplete.txt create mode 100644 .vim/doc/project.txt create mode 100644 .vim/doc/taglist.txt create mode 100644 .vim/doc/tags create mode 100644 .vim/doc/vcscommand.txt create mode 100644 .vim/ftplugin/git.vim create mode 100644 .vim/ftplugin/svn.vim create mode 100644 .vim/plugin/NERD_tree.vim create mode 100644 .vim/plugin/project.vim create mode 100644 .vim/plugin/vcscommand.vim create mode 100644 .vim/plugin/vcscvs.vim create mode 100755 .vim/plugin/vcsgit.vim create mode 100644 .vim/plugin/vcssvk.vim create mode 100644 .vim/plugin/vcssvn.vim create mode 100644 .vim/syntax/CVSAnnotate.vim create mode 100644 .vim/syntax/SVKAnnotate.vim create mode 100644 .vim/syntax/SVNAnnotate.vim create mode 100644 .vim/syntax/git.vim create mode 100644 .vim/syntax/vcscommit.vim diff --git a/.vim/after/ftplugin/c.vim b/.vim/after/ftplugin/c.vim new file mode 100644 index 0000000..66dfc5e --- /dev/null +++ b/.vim/after/ftplugin/c.vim @@ -0,0 +1,2 @@ +" OmniCppComplete initialization +call omni#cpp#complete#Init() diff --git a/.vim/after/ftplugin/cpp.vim b/.vim/after/ftplugin/cpp.vim new file mode 100644 index 0000000..66dfc5e --- /dev/null +++ b/.vim/after/ftplugin/cpp.vim @@ -0,0 +1,2 @@ +" OmniCppComplete initialization +call omni#cpp#complete#Init() diff --git a/.vim/autoload/omni/common/debug.vim b/.vim/autoload/omni/common/debug.vim new file mode 100644 index 0000000..eded649 --- /dev/null +++ b/.vim/autoload/omni/common/debug.vim @@ -0,0 +1,32 @@ +" Description: Omni completion debug functions +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +let s:CACHE_DEBUG_TRACE = [] + +" Start debug, clear the debug file +function! omni#common#debug#Start() + let s:CACHE_DEBUG_TRACE = [] + call extend(s:CACHE_DEBUG_TRACE, ['============ Debug Start ============']) + call writefile(s:CACHE_DEBUG_TRACE, "Omni.dbg") +endfunc + +" End debug, write to debug file +function! omni#common#debug#End() + call extend(s:CACHE_DEBUG_TRACE, ["============= Debug End ============="]) + call extend(s:CACHE_DEBUG_TRACE, [""]) + call writefile(s:CACHE_DEBUG_TRACE, "Omni.dbg") +endfunc + +" Debug trace function +function! omni#common#debug#Trace(szFuncName, ...) + let szTrace = a:szFuncName + let paramNum = a:0 + if paramNum>0 + let szTrace .= ':' + endif + for i in range(paramNum) + let szTrace = szTrace .' ('. string(eval('a:'.string(i+1))).')' + endfor + call extend(s:CACHE_DEBUG_TRACE, [szTrace]) +endfunc diff --git a/.vim/autoload/omni/common/utils.vim b/.vim/autoload/omni/common/utils.vim new file mode 100644 index 0000000..c880ad2 --- /dev/null +++ b/.vim/autoload/omni/common/utils.vim @@ -0,0 +1,67 @@ +" Description: Omni completion utils +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +" For sort numbers in list +function! omni#common#utils#CompareNumber(i1, i2) + let num1 = eval(a:i1) + let num2 = eval(a:i2) + return num1 == num2 ? 0 : num1 > num2 ? 1 : -1 +endfunc + +" TagList function calling the vim taglist() with try catch +" The only throwed exception is 'TagList:UserInterrupt' +" We also force the noignorecase option to avoid linear search when calling +" taglist() +function! omni#common#utils#TagList(szTagQuery) + let result = [] + let bUserIgnoreCase = &ignorecase + " Forcing noignorecase search => binary search can be used in taglist() + " if tags in the tag file are sorted + if bUserIgnoreCase + set noignorecase + endif + try + let result = taglist(a:szTagQuery) + catch /^Vim:Interrupt$/ + " Restoring user's setting + if bUserIgnoreCase + set ignorecase + endif + throw 'TagList:UserInterrupt' + catch + "Note: it seems that ctags can generate corrupted files, in this case + "taglist() will fail to read the tagfile and an exception from + "has_add() is thrown + endtry + + " Restoring user's setting + if bUserIgnoreCase + set ignorecase + endif + return result +endfunc + +" Same as TagList but don't throw exception +function! omni#common#utils#TagListNoThrow(szTagQuery) + let result = [] + try + let result = omni#common#utils#TagList(a:szTagQuery) + catch + endtry + return result +endfunc + +" Get the word under the cursor +function! omni#common#utils#GetWordUnderCursor() + let szLine = getline('.') + let startPos = getpos('.')[2]-1 + let startPos = (startPos < 0)? 0 : startPos + if szLine[startPos] =~ '\w' + let startPos = searchpos('\<\w\+', 'cbn', line('.'))[1] - 1 + endif + + let startPos = (startPos < 0)? 0 : startPos + let szResult = matchstr(szLine, '\w\+', startPos) + return szResult +endfunc diff --git a/.vim/autoload/omni/cpp/complete.vim b/.vim/autoload/omni/cpp/complete.vim new file mode 100644 index 0000000..a7e4edc --- /dev/null +++ b/.vim/autoload/omni/cpp/complete.vim @@ -0,0 +1,569 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 27 sept. 2007 + +if v:version < 700 + echohl WarningMsg + echomsg "omni#cpp#complete.vim: Please install vim 7.0 or higher for omni-completion" + echohl None + finish +endif + +call omni#cpp#settings#Init() +let s:OmniCpp_ShowScopeInAbbr = g:OmniCpp_ShowScopeInAbbr +let s:OmniCpp_ShowPrototypeInAbbr = g:OmniCpp_ShowPrototypeInAbbr +let s:OmniCpp_ShowAccess = g:OmniCpp_ShowAccess +let s:szCurrentWorkingDir = getcwd() + +" Cache data +let s:CACHE_TAG_POPUP_ITEMS = {} +let s:CACHE_TAG_FILES = {} +let s:CACHE_TAG_ENV = '' +let s:CACHE_OVERLOADED_FUNCTIONS = {} + +" Has preview window? +let s:hasPreviewWindow = match(&completeopt, 'preview')>=0 +let s:hasPreviewWindowOld = s:hasPreviewWindow + +" Popup item list +let s:popupItemResultList = [] + +" May complete indicator +let s:bMayComplete = 0 + +" Init mappings +function! omni#cpp#complete#Init() + call omni#cpp#settings#Init() + set omnifunc=omni#cpp#complete#Main + inoremap omni#cpp#maycomplete#Complete() + inoremap . omni#cpp#maycomplete#Dot() + inoremap > omni#cpp#maycomplete#Arrow() + inoremap : omni#cpp#maycomplete#Scope() +endfunc + +" Find the start position of the completion +function! s:FindStartPositionOfCompletion() + " Locate the start of the item, including ".", "->" and "[...]". + let line = getline('.') + let start = col('.') - 1 + + let lastword = -1 + while start > 0 + if line[start - 1] =~ '\w' + let start -= 1 + elseif line[start - 1] =~ '\.' + " Searching for dot '.' + if lastword == -1 + let lastword = start + endif + let start -= 1 + elseif start > 1 && line[start - 2] == '-' && line[start - 1] == '>' + " Searching for '->' + if lastword == -1 + let lastword = start + endif + let start -= 2 + elseif start > 1 && line[start - 2] == ':' && line[start - 1] == ':' + " Searching for '::' for namespaces and class + if lastword == -1 + let lastword = start + endif + let start -= 2 + elseif line[start - 1] == ']' + " Skip over [...]. + let n = 0 + let start -= 1 + while start > 0 + let start -= 1 + if line[start] == '[' + if n == 0 + break + endif + let n -= 1 + elseif line[start] == ']' " nested [] + let n += 1 + endif + endwhile + else + break + endif + endwhile + if lastword==-1 + " For completion on the current scope + let lastword = start + endif + return lastword +endfunc + +" Returns if szKey1.szKey2 is in the cache +" @return +" - 0 = key not found +" - 1 = szKey1.szKey2 found +" - 2 = szKey1.[part of szKey2] found +function! s:IsCached(cache, szKey1, szKey2) + " Searching key in the result cache + let szResultKey = a:szKey1 . a:szKey2 + let result = [0, szResultKey] + if a:szKey2 != '' + let szKey = a:szKey2 + while len(szKey)>0 + if has_key(a:cache, a:szKey1 . szKey) + let result[1] = a:szKey1 . szKey + if szKey != a:szKey2 + let result[0] = 2 + else + let result[0] = 1 + endif + break + endif + let szKey = szKey[:-2] + endwhile + else + if has_key(a:cache, szResultKey) + let result[0] = 1 + endif + endif + return result +endfunc + +" Extend a tag item to a popup item +function! s:ExtendTagItemToPopupItem(tagItem, szTypeName) + let tagItem = a:tagItem + + " Add the access + let szItemMenu = '' + let accessChar = {'public': '+','protected': '#','private': '-'} + if g:OmniCpp_ShowAccess + if has_key(tagItem, 'access') && has_key(accessChar, tagItem.access) + let szItemMenu = szItemMenu.accessChar[tagItem.access] + else + let szItemMenu = szItemMenu." " + endif + endif + + " Formating optional menu string we extract the scope information + let szName = substitute(tagItem.name, '.*::', '', 'g') + let szItemWord = szName + let szAbbr = szName + + if !g:OmniCpp_ShowScopeInAbbr + let szScopeOfTag = omni#cpp#utils#ExtractScope(tagItem) + let szItemMenu = szItemMenu.' '.szScopeOfTag[2:] + let szItemMenu = substitute(szItemMenu, '\s\+$', '', 'g') + else + let szAbbr = tagItem.name + endif + if g:OmniCpp_ShowAccess + let szItemMenu = substitute(szItemMenu, '^\s\+$', '', 'g') + else + let szItemMenu = substitute(szItemMenu, '\(^\s\+\)\|\(\s\+$\)', '', 'g') + endif + + " Formating information for the preview window + if index(['f', 'p'], tagItem.kind[0])>=0 + let szItemWord .= '(' + if g:OmniCpp_ShowPrototypeInAbbr && has_key(tagItem, 'signature') + let szAbbr .= tagItem.signature + else + let szAbbr .= '(' + endif + endif + let szItemInfo = '' + if s:hasPreviewWindow + let szItemInfo = omni#cpp#utils#GetPreviewWindowStringFromTagItem(tagItem) + endif + + " If a function is a ctor we add a new key in the tagItem + if index(['f', 'p'], tagItem.kind[0])>=0 + if match(szName, '^\~') < 0 && a:szTypeName =~ '\C\<'.szName.'$' + " It's a ctor + let tagItem['ctor'] = 1 + elseif has_key(tagItem, 'access') && tagItem.access == 'friend' + " Friend function + let tagItem['friendfunc'] = 1 + endif + endif + + " Extending the tag item to a popup item + let tagItem['word'] = szItemWord + let tagItem['abbr'] = szAbbr + let tagItem['menu'] = szItemMenu + let tagItem['info'] = szItemInfo + let tagItem['dup'] = (s:hasPreviewWindow && index(['f', 'p', 'm'], tagItem.kind[0])>=0) + return tagItem +endfunc + +" Get tag popup item list +function! s:TagPopupList(szTypeName, szBase) + let result = [] + + " Searching key in the result cache + let cacheResult = s:IsCached(s:CACHE_TAG_POPUP_ITEMS, a:szTypeName, a:szBase) + + " Building the tag query, we don't forget dtors when a:szBase=='' + if a:szTypeName!='' + " Scope search + let szTagQuery = '^' . a:szTypeName . '::' . a:szBase . '\~\?\w\+$' + else + " Global search + let szTagQuery = '^' . a:szBase . '\w\+$' + endif + + " If the result is already in the cache we return it + if cacheResult[0] + let result = s:CACHE_TAG_POPUP_ITEMS[ cacheResult[1] ] + if cacheResult[0] == 2 + let result = filter(copy(result), 'v:val.name =~ szTagQuery' ) + endif + return result + endif + + try + " Getting tags + let result = omni#common#utils#TagList(szTagQuery) + + " We extend tag items to popup items + call map(result, 's:ExtendTagItemToPopupItem(v:val, a:szTypeName)') + + " We store the result in a cache + if cacheResult[1] != '' + let s:CACHE_TAG_POPUP_ITEMS[ cacheResult[1] ] = result + endif + catch /^TagList:UserInterrupt$/ + endtry + + return result +endfunc + +" Find complete matches for a completion on the global scope +function! s:SearchGlobalMembers(szBase) + if a:szBase != '' + let tagPopupList = s:TagPopupList('', a:szBase) + let tagPopupList = filter(copy(tagPopupList), g:omni#cpp#utils#szFilterGlobalScope) + call extend(s:popupItemResultList, tagPopupList) + endif +endfunc + +" Search class, struct, union members +" @param resolvedTagItem: a resolved tag item +" @param szBase: string base +" @return list of tag items extended to popup items +function! s:SearchMembers(resolvedTagItem, szBase) + let result = [] + if a:resolvedTagItem == {} + return result + endif + + " Get type info without the starting '::' + let szTagName = omni#cpp#utils#ExtractTypeInfoFromTag(a:resolvedTagItem)[2:] + + " Unnamed type case. A tag item representing an unnamed type is a variable + " ('v') a member ('m') or a typedef ('t') + if index(['v', 't', 'm'], a:resolvedTagItem.kind[0])>=0 && has_key(a:resolvedTagItem, 'typeref') + " We remove the 'struct:' or 'class:' etc... + let szTagName = substitute(a:resolvedTagItem.typeref, '^\w\+:', '', 'g') + endif + + return copy(s:TagPopupList(szTagName, a:szBase)) +endfunc + +" Return if the tag env has changed +function! s:HasTagEnvChanged() + if s:CACHE_TAG_ENV == &tags + return 0 + else + let s:CACHE_TAG_ENV = &tags + return 1 + endif +endfunc + +" Return if a tag file has changed in tagfiles() +function! s:HasATagFileOrTagEnvChanged() + if s:HasTagEnvChanged() + let s:CACHE_TAG_FILES = {} + return 1 + endif + + let result = 0 + for tagFile in tagfiles() + if tagFile == "" + continue + endif + + if has_key(s:CACHE_TAG_FILES, tagFile) + let currentFiletime = getftime(tagFile) + if currentFiletime > s:CACHE_TAG_FILES[tagFile] + " The file has changed, updating the cache + let s:CACHE_TAG_FILES[tagFile] = currentFiletime + let result = 1 + endif + else + " We store the time of the file + let s:CACHE_TAG_FILES[tagFile] = getftime(tagFile) + let result = 1 + endif + endfor + return result +endfunc +" Initialization +call s:HasATagFileOrTagEnvChanged() + +" Filter same function signatures of base classes +function! s:FilterOverloadedFunctions(tagPopupList) + let result = [] + for tagPopupItem in a:tagPopupList + if has_key(tagPopupItem, 'kind') && index(['f', 'p'], tagPopupItem.kind[0])>=0 && has_key(tagPopupItem, 'signature') + if !has_key(s:CACHE_OVERLOADED_FUNCTIONS, tagPopupItem.word . tagPopupItem.signature) + let s:CACHE_OVERLOADED_FUNCTIONS[tagPopupItem.word . tagPopupItem.signature] = 1 + call extend(result, [tagPopupItem]) + endif + else + call extend(result, [tagPopupItem]) + endif + endfor + return result +endfunc + +" Access filter +function! s:GetAccessFilter(szFilter, szAccessFilter) + let szFilter = a:szFilter + if g:OmniCpp_DisplayMode == 0 + if a:szAccessFilter == 'public' + " We only get public members + let szFilter .= "&& v:val.access == 'public'" + elseif a:szAccessFilter == 'protected' + " We get public and protected members + let szFilter .= "&& v:val.access != 'private'" + endif + endif + return szFilter +endfunc + +" Filter class members in the popup menu after a completion with -> or . +function! s:FilterClassMembers(tagPopupList, szAccessFilter) + let szFilter = "(!has_key(v:val, 'friendfunc') && !has_key(v:val, 'ctor') && has_key(v:val, 'kind') && index(['m', 'p', 'f'], v:val.kind[0])>=0 && has_key(v:val, 'access'))" + call filter(a:tagPopupList, s:GetAccessFilter(szFilter, a:szAccessFilter)) + call extend(s:popupItemResultList, s:FilterOverloadedFunctions(a:tagPopupList)) +endfunc + +" Filter class scope members in the popup menu after a completion with :: +" We only display attribute and functions members that +" have an access information. We also display nested +" class, struct, union, and enums, typedefs +function! s:FilterClassScopeMembers(tagPopupList, szAccessFilter) + let szFilter = "!has_key(v:val, 'friendfunc') && has_key(v:val, 'kind') && (index(['m', 'p', 'f'], v:val.kind[0])>=0 && has_key(v:val, 'access'))" + let szFilter = s:GetAccessFilter(szFilter, a:szAccessFilter) + let szFilter .= "|| index(['c','e','g','s','t','u'], v:val.kind[0])>=0" + call filter(a:tagPopupList, szFilter) + call extend(s:popupItemResultList, s:FilterOverloadedFunctions(a:tagPopupList)) +endfunc + +" Filter static class members in the popup menu +function! s:FilterStaticClassMembers(tagPopupList, szAccessFilter) + let szFilter = "!has_key(v:val, 'friendfunc') && has_key(v:val, 'kind') && (index(['m', 'p', 'f'], v:val.kind[0])>=0 && has_key(v:val, 'access') && match(v:val.cmd, '\\Cstatic')!=-1)" + let szFilter = s:GetAccessFilter(szFilter, a:szAccessFilter) + let szFilter = szFilter . "|| index(['c','e','g','n','s','t','u','v'], v:val.kind[0])>=0" + call filter(a:tagPopupList, szFilter) + call extend(s:popupItemResultList, s:FilterOverloadedFunctions(a:tagPopupList)) +endfunc + +" Filter scope members in the popup menu +function! s:FilterNamespaceScopeMembers(tagPopupList) + call extend(s:popupItemResultList, a:tagPopupList) +endfunc + +" Init data at the start of completion +function! s:InitComplete() + " Reset the popup item list + let s:popupItemResultList = [] + let s:CACHE_OVERLOADED_FUNCTIONS = {} + + " Reset includes cache when the current working directory has changed + let szCurrentWorkingDir = getcwd() + if s:szCurrentWorkingDir != szCurrentWorkingDir + let s:szCurrentWorkingDir = szCurrentWorkingDir + let g:omni#cpp#includes#CACHE_INCLUDES = {} + let g:omni#cpp#includes#CACHE_FILE_TIME = {} + endif + + " Has preview window ? + let s:hasPreviewWindow = match(&completeopt, 'preview')>=0 + + let bResetCache = 0 + + " Reset tag env or tag files dependent caches + if s:HasATagFileOrTagEnvChanged() + let bResetCache = 1 + endif + + if (s:OmniCpp_ShowScopeInAbbr != g:OmniCpp_ShowScopeInAbbr) + \|| (s:OmniCpp_ShowPrototypeInAbbr != g:OmniCpp_ShowPrototypeInAbbr) + \|| (s:OmniCpp_ShowAccess != g:OmniCpp_ShowAccess) + + let s:OmniCpp_ShowScopeInAbbr = g:OmniCpp_ShowScopeInAbbr + let s:OmniCpp_ShowPrototypeInAbbr = g:OmniCpp_ShowPrototypeInAbbr + let s:OmniCpp_ShowAccess = g:OmniCpp_ShowAccess + let bResetCache = 1 + endif + + if s:hasPreviewWindow != s:hasPreviewWindowOld + let s:hasPreviewWindowOld = s:hasPreviewWindow + let bResetCache = 1 + endif + + if bResetCache + let g:omni#cpp#namespaces#CacheResolve = {} + let s:CACHE_TAG_POPUP_ITEMS = {} + let g:omni#cpp#utils#CACHE_TAG_INHERITS = {} + call garbagecollect() + endif + + " Check for updates + for szIncludeName in keys(g:omni#cpp#includes#CACHE_INCLUDES) + let fTime = getftime(szIncludeName) + let bNeedUpdate = 0 + if has_key(g:omni#cpp#includes#CACHE_FILE_TIME, szIncludeName) + if fTime != g:omni#cpp#includes#CACHE_FILE_TIME[szIncludeName] + let bNeedUpdate = 1 + endif + else + let g:omni#cpp#includes#CACHE_FILE_TIME[szIncludeName] = fTime + let bNeedUpdate = 1 + endif + + if bNeedUpdate + " We have to update include list and namespace map of this file + call omni#cpp#includes#GetList(szIncludeName, 1) + call omni#cpp#namespaces#GetMapFromBuffer(szIncludeName, 1) + endif + endfor + + let s:bDoNotComplete = 0 +endfunc + + +" This function is used for the 'omnifunc' option. +function! omni#cpp#complete#Main(findstart, base) + if a:findstart + "call omni#common#debug#Start() + + call s:InitComplete() + + " Note: if s:bMayComplete==1 g:omni#cpp#items#data is build by MayComplete functions + if !s:bMayComplete + " If the cursor is in a comment we go out + if omni#cpp#utils#IsCursorInCommentOrString() + " Returning -1 is not enough we have to set a variable to let + " the second call of omni#cpp#complete knows that the + " cursor was in a comment + " Why is there a second call when the first call returns -1 ? + let s:bDoNotComplete = 1 + return -1 + endif + + " We get items here (whend a:findstart==1) because GetItemsToComplete() + " depends on the cursor position. + " When a:findstart==0 the cursor position is modified + let g:omni#cpp#items#data = omni#cpp#items#Get(omni#cpp#utils#TokenizeCurrentInstruction()) + endif + + " Get contexts stack + let s:contextStack = omni#cpp#namespaces#GetContexts() + + " Reinit of may complete indicator + let s:bMayComplete = 0 + return s:FindStartPositionOfCompletion() + endif + + " If the cursor is in a comment we return an empty result + if s:bDoNotComplete + let s:bDoNotComplete = 0 + return [] + endif + + if len(g:omni#cpp#items#data)==0 + " A) CURRENT_SCOPE_COMPLETION_MODE + + " 1) Displaying data of each context + let szAccessFilter = 'all' + for szCurrentContext in s:contextStack + if szCurrentContext == '::' + continue + endif + + let resolvedTagItem = omni#cpp#utils#GetResolvedTagItem(s:contextStack, omni#cpp#utils#CreateTypeInfo(szCurrentContext)) + if resolvedTagItem != {} + " We don't search base classes because bases classes are + " already in the context stack + let tagPopupList = s:SearchMembers(resolvedTagItem, a:base) + if index(['c','s'], resolvedTagItem.kind[0])>=0 + " It's a class or struct + call s:FilterClassScopeMembers(tagPopupList, szAccessFilter) + let szAccessFilter = 'protected' + else + " It's a namespace or union, we display all members + call s:FilterNamespaceScopeMembers(tagPopupList) + endif + endif + endfor + + " 2) Displaying global scope members + if g:OmniCpp_GlobalScopeSearch + call s:SearchGlobalMembers(a:base) + endif + else + let typeInfo = omni#cpp#items#ResolveItemsTypeInfo(s:contextStack, g:omni#cpp#items#data) + + if typeInfo != {} + if g:omni#cpp#items#data[-1].kind == 'itemScope' + " B) SCOPE_COMPLETION_MODE + if omni#cpp#utils#GetTypeInfoString(typeInfo)=='' + call s:SearchGlobalMembers(a:base) + else + for resolvedTagItem in omni#cpp#utils#GetResolvedTags(s:contextStack, typeInfo) + let tagPopupList = s:SearchMembers(resolvedTagItem, a:base) + if index(['c','s'], resolvedTagItem.kind[0])>=0 + let szTypeInfo = omni#cpp#utils#ExtractTypeInfoFromTag(resolvedTagItem) + if g:OmniCpp_DisplayMode==0 + " We want to complete a class or struct + " If this class is a base class so we display all class members + if index(s:contextStack, szTypeInfo)<0 + let szAccessFilter = 'public' + call s:FilterStaticClassMembers(tagPopupList, szAccessFilter) + else + let szAccessFilter = (s:contextStack[0] == szTypeInfo)? 'all' : 'protected' + call s:FilterClassScopeMembers(tagPopupList, szAccessFilter) + endif + else + if index(s:contextStack, szTypeInfo)<0 + let szAccessFilter = 'public' + else + let szAccessFilter = (s:contextStack[0] == szTypeInfo)? 'all' : 'protected' + endif + call s:FilterClassScopeMembers(tagPopupList, szAccessFilter) + endif + else + " We want to complete a namespace + call s:FilterNamespaceScopeMembers(tagPopupList) + endif + endfor + endif + else + " C) CLASS_MEMBERS_COMPLETION_MODE + for resolvedTagItem in omni#cpp#utils#GetResolvedTags(s:contextStack, typeInfo) + let szTypeInfo = omni#cpp#utils#ExtractTypeInfoFromTag(resolvedTagItem) + if index(s:contextStack, szTypeInfo)<0 + let szAccessFilter = 'public' + else + let szAccessFilter = (s:contextStack[0] == szTypeInfo)? 'all' : 'protected' + endif + call s:FilterClassMembers(s:SearchMembers(resolvedTagItem, a:base), szAccessFilter) + endfor + endif + endif + endif + + "call omni#common#debug#End() + + return s:popupItemResultList +endfunc diff --git a/.vim/autoload/omni/cpp/includes.vim b/.vim/autoload/omni/cpp/includes.vim new file mode 100644 index 0000000..10a89bc --- /dev/null +++ b/.vim/autoload/omni/cpp/includes.vim @@ -0,0 +1,126 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +let g:omni#cpp#includes#CACHE_INCLUDES = {} +let g:omni#cpp#includes#CACHE_FILE_TIME = {} + +let s:rePreprocIncludePart = '\C#\s*include\s*' +let s:reIncludeFilePart = '\(<\|"\)\(\f\|\s\)\+\(>\|"\)' +let s:rePreprocIncludeFile = s:rePreprocIncludePart . s:reIncludeFilePart + +" Get the include list of a file +function! omni#cpp#includes#GetList(...) + if a:0 > 0 + return s:GetIncludeListFromFile(a:1, (a:0 > 1)? a:2 : 0 ) + else + return s:GetIncludeListFromCurrentBuffer() + endif +endfunc + +" Get the include list from the current buffer +function! s:GetIncludeListFromCurrentBuffer() + let listIncludes = [] + let originalPos = getpos('.') + + call setpos('.', [0, 1, 1, 0]) + let curPos = [1,1] + let alreadyInclude = {} + while curPos != [0,0] + let curPos = searchpos('\C\(^'.s:rePreprocIncludeFile.'\)', 'W') + if curPos != [0,0] + let szLine = getline('.') + let startPos = curPos[1] + let endPos = matchend(szLine, s:reIncludeFilePart, startPos-1) + if endPos!=-1 + let szInclusion = szLine[startPos-1:endPos-1] + let szIncludeFile = substitute(szInclusion, '\('.s:rePreprocIncludePart.'\)\|[<>""]', '', 'g') + let szResolvedInclude = omni#cpp#utils#ResolveFilePath(szIncludeFile) + + " Protection over self inclusion + if szResolvedInclude != '' && szResolvedInclude != omni#cpp#utils#ResolveFilePath(getreg('%')) + let includePos = curPos + if !has_key(alreadyInclude, szResolvedInclude) + call extend(listIncludes, [{'pos' : includePos, 'include' : szResolvedInclude}]) + let alreadyInclude[szResolvedInclude] = 1 + endif + endif + endif + endif + endwhile + + call setpos('.', originalPos) + return listIncludes +endfunc + +" Get the include list from a file +function! s:GetIncludeListFromFile(szFilePath, bUpdate) + let listIncludes = [] + if a:szFilePath == '' + return listIncludes + endif + + if !a:bUpdate && has_key(g:omni#cpp#includes#CACHE_INCLUDES, a:szFilePath) + return copy(g:omni#cpp#includes#CACHE_INCLUDES[a:szFilePath]) + endif + + let g:omni#cpp#includes#CACHE_FILE_TIME[a:szFilePath] = getftime(a:szFilePath) + + let szFixedPath = escape(a:szFilePath, g:omni#cpp#utils#szEscapedCharacters) + execute 'silent! lvimgrep /\C\(^'.s:rePreprocIncludeFile.'\)/gj '.szFixedPath + + let listQuickFix = getloclist(0) + let alreadyInclude = {} + for qf in listQuickFix + let szLine = qf.text + let startPos = qf.col + let endPos = matchend(szLine, s:reIncludeFilePart, startPos-1) + if endPos!=-1 + let szInclusion = szLine[startPos-1:endPos-1] + let szIncludeFile = substitute(szInclusion, '\('.s:rePreprocIncludePart.'\)\|[<>""]', '', 'g') + let szResolvedInclude = omni#cpp#utils#ResolveFilePath(szIncludeFile) + + " Protection over self inclusion + if szResolvedInclude != '' && szResolvedInclude != a:szFilePath + let includePos = [qf.lnum, qf.col] + if !has_key(alreadyInclude, szResolvedInclude) + call extend(listIncludes, [{'pos' : includePos, 'include' : szResolvedInclude}]) + let alreadyInclude[szResolvedInclude] = 1 + endif + endif + endif + endfor + + let g:omni#cpp#includes#CACHE_INCLUDES[a:szFilePath] = listIncludes + + return copy(listIncludes) +endfunc + +" For debug purpose +function! omni#cpp#includes#Display() + let szPathBuffer = omni#cpp#utils#ResolveFilePath(getreg('%')) + call s:DisplayIncludeTree(szPathBuffer, 0) +endfunc + +" For debug purpose +function! s:DisplayIncludeTree(szFilePath, indent, ...) + let includeGuard = {} + if a:0 >0 + let includeGuard = a:1 + endif + let szFilePath = omni#cpp#utils#ResolveFilePath(a:szFilePath) + if has_key(includeGuard, szFilePath) + return + else + let includeGuard[szFilePath] = 1 + endif + + let szIndent = repeat(' ', a:indent) + echo szIndent . a:szFilePath + let incList = omni#cpp#includes#GetList(a:szFilePath) + for inc in incList + call s:DisplayIncludeTree(inc.include, a:indent+1, includeGuard) + endfor +endfunc + + diff --git a/.vim/autoload/omni/cpp/items.vim b/.vim/autoload/omni/cpp/items.vim new file mode 100644 index 0000000..b943ad4 --- /dev/null +++ b/.vim/autoload/omni/cpp/items.vim @@ -0,0 +1,660 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +" Build the item list of an instruction +" An item is an instruction between a -> or . or ->* or .* +" We can sort an item in different kinds: +" eg: ((MyClass1*)(pObject))->_memberOfClass1.get() ->show() +" | cast | | member | | method | | method | +" @return a list of item +" an item is a dictionnary where keys are: +" tokens = list of token +" kind = itemVariable|itemCast|itemCppCast|itemTemplate|itemFunction|itemUnknown|itemThis|itemScope +function! omni#cpp#items#Get(tokens, ...) + let bGetWordUnderCursor = (a:0>0)? a:1 : 0 + + let result = [] + let itemsDelimiters = ['->', '.', '->*', '.*'] + + let tokens = reverse(omni#cpp#utils#BuildParenthesisGroups(a:tokens)) + + " fsm states: + " 0 = initial state + " TODO: add description of fsm states + let state=(bGetWordUnderCursor)? 1 : 0 + let item = {'tokens' : [], 'kind' : 'itemUnknown'} + let parenGroup=-1 + for token in tokens + if state==0 + if index(itemsDelimiters, token.value)>=0 + let item = {'tokens' : [], 'kind' : 'itemUnknown'} + let state = 1 + elseif token.value=='::' + let state = 9 + let item.kind = 'itemScope' + " Maybe end of tokens + elseif token.kind =='cppOperatorPunctuator' + " If it's a cppOperatorPunctuator and the current token is not + " a itemsDelimiters or '::' we can exit + let state=-1 + break + endif + elseif state==1 + call insert(item.tokens, token) + if token.kind=='cppWord' + " It's an attribute member or a variable + let item.kind = 'itemVariable' + let state = 2 + " Maybe end of tokens + elseif token.value=='this' + let item.kind = 'itemThis' + let state = 2 + " Maybe end of tokens + elseif token.value==')' + let parenGroup = token.group + let state = 3 + elseif token.value==']' + let parenGroup = token.group + let state = 4 + elseif token.kind == 'cppDigit' + let state = -1 + break + endif + elseif state==2 + if index(itemsDelimiters, token.value)>=0 + call insert(result, item) + let item = {'tokens' : [], 'kind' : 'itemUnknown'} + let state = 1 + elseif token.value == '::' + call insert(item.tokens, token) + " We have to get namespace or classscope + let state = 8 + " Maybe end of tokens + else + call insert(result, item) + let state=-1 + break + endif + elseif state==3 + call insert(item.tokens, token) + if token.value=='(' && token.group == parenGroup + let state = 5 + " Maybe end of tokens + endif + elseif state==4 + call insert(item.tokens, token) + if token.value=='[' && token.group == parenGroup + let state = 1 + endif + elseif state==5 + if token.kind=='cppWord' + " It's a function or method + let item.kind = 'itemFunction' + call insert(item.tokens, token) + let state = 2 + " Maybe end of tokens + elseif token.value == '>' + " Maybe a cpp cast or template + let item.kind = 'itemTemplate' + call insert(item.tokens, token) + let parenGroup = token.group + let state = 6 + else + " Perhaps it's a C cast eg: ((void*)(pData)) or a variable eg:(*pData) + let item.kind = omni#cpp#utils#GetCastType(item.tokens) + let state=-1 + call insert(result, item) + break + endif + elseif state==6 + call insert(item.tokens, token) + if token.value == '<' && token.group == parenGroup + " Maybe a cpp cast or template + let state = 7 + endif + elseif state==7 + call insert(item.tokens, token) + if token.kind=='cppKeyword' + " It's a cpp cast + let item.kind = omni#cpp#utils#GetCastType(item.tokens) + let state=-1 + call insert(result, item) + break + else + " Template ? + let state=-1 + call insert(result, item) + break + endif + elseif state==8 + if token.kind=='cppWord' + call insert(item.tokens, token) + let state = 2 + " Maybe end of tokens + else + let state=-1 + call insert(result, item) + break + endif + elseif state==9 + if token.kind == 'cppWord' + call insert(item.tokens, token) + let state = 10 + " Maybe end of tokens + else + let state=-1 + call insert(result, item) + break + endif + elseif state==10 + if token.value == '::' + call insert(item.tokens, token) + let state = 9 + " Maybe end of tokens + else + let state=-1 + call insert(result, item) + break + endif + endif + endfor + + if index([2, 5, 8, 9, 10], state)>=0 + if state==5 + let item.kind = omni#cpp#utils#GetCastType(item.tokens) + endif + call insert(result, item) + endif + + return result +endfunc + +" Resolve type information of items +" @param namespaces: list of namespaces used in the file +" @param szCurrentClassScope: the current class scope, only used for the first +" item to detect if this item is a class member (attribute, method) +" @param items: list of item, can be an empty list @see GetItemsToComplete +function! omni#cpp#items#ResolveItemsTypeInfo(contextStack, items) + " Note: kind = itemVariable|cCast|cppCast|template|function|itemUnknown|this + " For the first item, if it's a variable we try to detect the type of the + " variable with the function searchdecl. If it fails, thanks to the + " current class scope, we try to detect if the variable is an attribute + " member. + " If the kind of the item is a function, we have to first check if the + " function is a method of the class, if it fails we try to get a match in + " the global namespace. After that we get the returned type of the + " function. + " It the kind is a C cast or C++ cast, there is no problem, it's the + " easiest case. We just extract the type of the cast. + + let szCurrentContext = '' + let typeInfo = {} + " Note: We search the decl only for the first item + let bSearchDecl = 1 + for item in a:items + let curItem = item + if index(['itemVariable', 'itemFunction'], curItem.kind)>=0 + " Note: a variable can be : MyNs::MyClass::_var or _var or (*pVar) + " or _var[0][0] + let szSymbol = s:GetSymbol(curItem.tokens) + + " If we have MyNamespace::myVar + " We add MyNamespace in the context stack set szSymbol to myVar + if match(szSymbol, '::\w\+$') >= 0 + let szCurrentContext = substitute(szSymbol, '::\w\+$', '', 'g') + let szSymbol = matchstr(szSymbol, '\w\+$') + endif + let tmpContextStack = a:contextStack + if szCurrentContext != '' + let tmpContextStack = [szCurrentContext] + a:contextStack + endif + + if curItem.kind == 'itemVariable' + let typeInfo = s:GetTypeInfoOfVariable(tmpContextStack, szSymbol, bSearchDecl) + else + let typeInfo = s:GetTypeInfoOfReturnedType(tmpContextStack, szSymbol) + endif + + elseif curItem.kind == 'itemThis' + if len(a:contextStack) + let typeInfo = omni#cpp#utils#CreateTypeInfo(substitute(a:contextStack[0], '^::', '', 'g')) + endif + elseif curItem.kind == 'itemCast' + let typeInfo = omni#cpp#utils#CreateTypeInfo(s:ResolveCCast(curItem.tokens)) + elseif curItem.kind == 'itemCppCast' + let typeInfo = omni#cpp#utils#CreateTypeInfo(s:ResolveCppCast(curItem.tokens)) + elseif curItem.kind == 'itemScope' + let typeInfo = omni#cpp#utils#CreateTypeInfo(substitute(s:TokensToString(curItem.tokens), '\s', '', 'g')) + endif + + if omni#cpp#utils#IsTypeInfoValid(typeInfo) + let szCurrentContext = omni#cpp#utils#GetTypeInfoString(typeInfo) + endif + let bSearchDecl = 0 + endfor + + return typeInfo +endfunc + +" Get symbol name +function! s:GetSymbol(tokens) + let szSymbol = '' + let state = 0 + for token in a:tokens + if state == 0 + if token.value == '::' + let szSymbol .= token.value + let state = 1 + elseif token.kind == 'cppWord' + let szSymbol .= token.value + let state = 2 + " Maybe end of token + endif + elseif state == 1 + if token.kind == 'cppWord' + let szSymbol .= token.value + let state = 2 + " Maybe end of token + else + " Error + break + endif + elseif state == 2 + if token.value == '::' + let szSymbol .= token.value + let state = 1 + else + break + endif + endif + endfor + return szSymbol +endfunc + +" Search a declaration. +" eg: std::map +" can be empty +" Note: The returned type info can be a typedef +" The typedef resolution is done later +" @return +" - a dictionnary where keys are +" - type: the type of value same as type() +" - value: the value +function! s:GetTypeInfoOfVariable(contextStack, szVariable, bSearchDecl) + let result = {} + + if a:bSearchDecl + " Search type of declaration + "let result = s:SearchTypeInfoOfDecl(a:szVariable) + let result = s:SearchDecl(a:szVariable) + endif + + if result=={} + let szFilter = "index(['m', 'v'], v:val.kind[0])>=0" + let tagItem = s:ResolveSymbol(a:contextStack, a:szVariable, szFilter) + if tagItem=={} + return result + endif + + let szCmdWithoutVariable = substitute(omni#cpp#utils#ExtractCmdFromTagItem(tagItem), '\C\<'.a:szVariable.'\>.*', '', 'g') + let tokens = omni#cpp#tokenizer#Tokenize(omni#cpp#utils#GetCodeFromLine(szCmdWithoutVariable)) + let result = omni#cpp#utils#CreateTypeInfo(omni#cpp#utils#ExtractTypeInfoFromTokens(tokens)) + " TODO: Namespace resolution for result + + if result != {} && result.value=='' + " result.value=='' + " eg: + " struct + " { + " }gVariable; + if has_key(tagItem, 'typeref') + " Maybe the variable is a global var of an + " unnamed class, struct or union. + " eg: + " 1) + " struct + " { + " }gVariable; + " In this case we need the tags (the patched version) + " Note: We can have a named type like this: + " 2) + " class A + " { + " }gVariable; + if s:IsUnnamedType(tagItem) + " It's an unnamed type we are in the case 1) + let result = omni#cpp#utils#CreateTypeInfo(tagItem) + else + " It's not an unnamed type we are in the case 2) + + " eg: tagItem.typeref = 'struct:MY_STRUCT::MY_SUBSTRUCT' + let szTypeRef = substitute(tagItem.typeref, '^\w\+:', '', '') + + " eg: szTypeRef = 'MY_STRUCT::MY_SUBSTRUCT' + let result = omni#cpp#utils#CreateTypeInfo(szTypeRef) + endif + endif + endif + endif + return result +endfunc + +" Get the type info string from the returned type of function +function! s:GetTypeInfoOfReturnedType(contextStack, szFunctionName) + let result = {} + + let szFilter = "index(['f', 'p'], v:val.kind[0])>=0" + let tagItem = s:ResolveSymbol(a:contextStack, a:szFunctionName, szFilter) + + if tagItem != {} + let szCmdWithoutVariable = substitute(omni#cpp#utils#ExtractCmdFromTagItem(tagItem), '\C\<'.a:szFunctionName.'\>.*', '', 'g') + let tokens = omni#cpp#tokenizer#Tokenize(omni#cpp#utils#GetCodeFromLine(szCmdWithoutVariable)) + let result = omni#cpp#utils#CreateTypeInfo(omni#cpp#utils#ExtractTypeInfoFromTokens(tokens)) + " TODO: Namespace resolution for result + return result + endif + return result +endfunc + +" Resolve a symbol, return a tagItem +" Gets the first symbol found in the context stack +function! s:ResolveSymbol(contextStack, szSymbol, szTagFilter) + let tagItem = {} + for szCurrentContext in a:contextStack + if szCurrentContext != '::' + let szTagQuery = substitute(szCurrentContext, '^::', '', 'g').'::'.a:szSymbol + else + let szTagQuery = a:szSymbol + endif + + let tagList = omni#common#utils#TagListNoThrow('^'.szTagQuery.'$') + call filter(tagList, a:szTagFilter) + if len(tagList) + let tagItem = tagList[0] + break + endif + endfor + return tagItem +endfunc + +" Return if the tag item represent an unnamed type +function! s:IsUnnamedType(tagItem) + let bResult = 0 + if has_key(a:tagItem, 'typeref') + " Note: Thanks for __anon ! + let bResult = match(a:tagItem.typeref, '\C\<__anon') >= 0 + endif + return bResult +endfunc + +" Search the declaration of a variable and return the type info +function! s:SearchTypeInfoOfDecl(szVariable) + let szReVariable = '\C\<'.a:szVariable.'\>' + + let originalPos = getpos('.') + let origPos = originalPos[1:2] + let curPos = origPos + let stopPos = origPos + + while curPos !=[0,0] + " We go to the start of the current scope + let curPos = searchpairpos('{', '', '}', 'bW', g:omni#cpp#utils#expIgnoreComments) + if curPos != [0,0] + let matchPos = curPos + " Now want to search our variable but we don't want to go in child + " scope + while matchPos != [0,0] + let matchPos = searchpos('{\|'.szReVariable, 'W', stopPos[0]) + if matchPos != [0,0] + " We ignore matches under comment + if omni#cpp#utils#IsCursorInCommentOrString() + continue + endif + + " Getting the current line + let szLine = getline('.') + if match(szLine, szReVariable)>=0 + " We found our variable + " Check if the current instruction is a decl instruction + let tokens = omni#cpp#utils#TokenizeCurrentInstruction() + let szTypeInfo = s:ExtractTypeInfoFromDecl(tokens) + if szTypeInfo != '' + call setpos('.', originalPos) + return omni#cpp#utils#CreateTypeInfo(szTypeInfo) + endif + else + " We found a child scope, we don't want to go in, thus + " we search for the end } of this child scope + let bracketEnd = searchpairpos('{', '', '}', 'nW', g:omni#cpp#utils#expIgnoreComments) + if bracketEnd == [0,0] + break + endif + + if bracketEnd[0] >= stopPos[0] + " The end of the scope is after our cursor we stop + " the search + break + else + " We move the cursor and continue to search our + " variable + call setpos('.', [0, bracketEnd[0], bracketEnd[1], 0]) + endif + endif + endif + endwhile + + " Backing to the start of the scope + call setpos('.', [0,curPos[0], curPos[1], 0]) + let stopPos = curPos + endif + endwhile + + let result = {} + if s:LocalSearchDecl(a:szVariable)==0 && !omni#cpp#utils#IsCursorInCommentOrString() + let tokens = omni#cpp#utils#TokenizeCurrentInstruction() + let szTypeInfo = s:ExtractTypeInfoFromDecl(tokens) + if szTypeInfo != '' + let result = omni#cpp#utils#CreateTypeInfo(szTypeInfo) + endif + endif + + call setpos('.', originalPos) + + return result +endfunc + +" Search a declaration +" @return +" - tokens of the current instruction if success +" - empty list if failure +function! s:SearchDecl(szVariable) + let result = {} + let originalPos = getpos('.') + let searchResult = s:LocalSearchDecl(a:szVariable) + if searchResult==0 + " searchdecl() may detect a decl if the variable is in a conditional + " instruction (if, elseif, while etc...) + " We have to check if the detected decl is really a decl instruction + let tokens = omni#cpp#utils#TokenizeCurrentInstruction() + + for token in tokens + " Simple test + if index(['if', 'elseif', 'while', 'for', 'switch'], token.value)>=0 + " Invalid declaration instruction + call setpos('.', originalPos) + return result + endif + endfor + + let szTypeInfo = s:ExtractTypeInfoFromDecl(tokens) + if szTypeInfo != '' + let result = omni#cpp#utils#CreateTypeInfo(szTypeInfo) + endif + endif + call setpos('.', originalPos) + return result +endfunc + +" Extract the type info string from an instruction. +" We use a small parser to extract the type +" We parse the code according to a C++ BNF from: http://www.nongnu.org/hcb/#basic.link +" @param tokens: token list of the current instruction +function! s:ExtractTypeInfoFromDecl(tokens) + return omni#cpp#utils#ExtractTypeInfoFromTokens(a:tokens) +endfunc + +" Convert tokens to string +function! s:TokensToString(tokens) + let result = '' + for token in a:tokens + let result = result . token.value . ' ' + endfor + return result[:-2] +endfunc + +" Resolve a cast. +" Resolve a C++ cast +" @param list of token. tokens must be a list that represents +" a cast expression (C++ cast) the function does not control +" if it's a cast or not +" eg: static_cast(something) +" @return type info string +function! s:ResolveCppCast(tokens) + return omni#cpp#utils#ExtractTypeInfoFromTokens(s:ResolveCast(a:tokens, '<', '>')) +endfunc + +" Resolve a cast. +" Resolve a C cast +" @param list of token. tokens must be a list that represents +" a cast expression (C cast) the function does not control +" if it's a cast or not +" eg: (MyClass*)something +" @return type info string +function! s:ResolveCCast(tokens) + return omni#cpp#utils#ExtractTypeInfoFromTokens(s:ResolveCast(a:tokens, '(', ')')) +endfunc + +" Resolve a cast. +" Resolve a C cast +" @param list of token. tokens must be a list that represents +" a cast expression (C cast) the function does not control +" if it's a cast or not +" eg: (MyClass*)something +" @return type tokens +function! s:ResolveCast(tokens, startChar, endChar) + let tokens = omni#cpp#utils#BuildParenthesisGroups(a:tokens) + + " We remove useless parenthesis eg: (((MyClass))) + let tokens = omni#cpp#utils#SimplifyParenthesis(tokens) + + let countItem=0 + let startIndex = -1 + let endIndex = -1 + let i = 0 + for token in tokens + if startIndex==-1 + if token.value==a:startChar + let countItem += 1 + let startIndex = i + endif + else + if token.value==a:startChar + let countItem += 1 + elseif token.value==a:endChar + let countItem -= 1 + endif + + if countItem==0 + let endIndex = i + break + endif + endif + let i+=1 + endfor + + return tokens[startIndex+1 : endIndex-1] +endfunc + +" Replacement for build-in function 'searchdecl' +" It does not require that the upper-level bracket is in the first column. +" Otherwise it should be equal to 'searchdecl(name, 0, 1)' +" @param name: name of variable to find declaration for +function! s:LocalSearchDecl(name) + + if g:OmniCpp_LocalSearchDecl == 0 + let bUserIgnoreCase = &ignorecase + + " Forcing the noignorecase option + " avoid bug when, for example, if we have a declaration like this : "A a;" + set noignorecase + + let result = searchdecl(a:name, 0, 1) + + " Restoring user's setting + let &ignorecase = bUserIgnoreCase + + return result + endif + + let lastpos = getpos('.') + let winview = winsaveview() + let lastfoldenable = &foldenable + let &foldenable = 0 + + " We add \C (noignorecase) to + " avoid bug when, for example, if we have a declaration like this : "A a;" + let varname = "\\C\\<" . a:name . "\\>" + + " Go to first blank line before begin of highest scope + normal 99[{ + let scopepos = getpos('.') + while (line('.') > 1) && (len(split(getline('.'))) > 0) + call cursor(line('.')-1, 0) + endwhile + + let declpos = [ 0, 0, 0, 0 ] + while search(varname, '', scopepos[1]) > 0 + " Check if we are a string or a comment + if omni#cpp#utils#IsCursorInCommentOrString() + continue + endif + + " Remember match + let declpos = getpos('.') + endwhile + if declpos[1] != 0 + " We found a match + call winrestview(winview) + call setpos('.', declpos) + let &foldenable = lastfoldenable + return 0 + endif + + while search(varname, '', lastpos[1]) > 0 + " Check if current scope is ending before variable + let old_cur = getpos('.') + normal ]} + let new_cur = getpos('.') + call setpos('.', old_cur) + if (new_cur[1] < lastpos[1]) || ((new_cur[1] == lastpos[1]) && (new_cur[2] < lastpos[2])) + continue + endif + + " Check if we are a string or a comment + if omni#cpp#utils#IsCursorInCommentOrString() + continue + endif + + " We found match + call winrestview(winview) + call setpos('.', old_cur) + let &foldenable = lastfoldenable + return 0 + endwhile + + " No match found. + call winrestview(winview) + let &foldenable = lastfoldenable + return 1 +endfunc diff --git a/.vim/autoload/omni/cpp/maycomplete.vim b/.vim/autoload/omni/cpp/maycomplete.vim new file mode 100644 index 0000000..610526b --- /dev/null +++ b/.vim/autoload/omni/cpp/maycomplete.vim @@ -0,0 +1,82 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +" Check if we can use omni completion in the current buffer +function! s:CanUseOmnicompletion() + " For C and C++ files and only if the omnifunc is omni#cpp#complete#Main + return (index(['c', 'cpp'], &filetype)>=0 && &omnifunc == 'omni#cpp#complete#Main' && !omni#cpp#utils#IsCursorInCommentOrString()) +endfunc + +" Return the mapping of omni completion +function! omni#cpp#maycomplete#Complete() + let szOmniMapping = "\\" + + " 0 = don't select first item + " 1 = select first item (inserting it to the text, default vim behaviour) + " 2 = select first item (without inserting it to the text) + if g:OmniCpp_SelectFirstItem == 0 + " We have to force the menuone option to avoid confusion when there is + " only one popup item + set completeopt-=menu + set completeopt+=menuone + let szOmniMapping .= "\" + elseif g:OmniCpp_SelectFirstItem == 2 + " We have to force the menuone option to avoid confusion when there is + " only one popup item + set completeopt-=menu + set completeopt+=menuone + let szOmniMapping .= "\" + let szOmniMapping .= "\=pumvisible() ? \"\\\" : \"\"\" + endif + return szOmniMapping +endfunc + +" May complete function for dot +function! omni#cpp#maycomplete#Dot() + if s:CanUseOmnicompletion() && g:OmniCpp_MayCompleteDot + let g:omni#cpp#items#data = omni#cpp#items#Get(omni#cpp#utils#TokenizeCurrentInstruction('.')) + if len(g:omni#cpp#items#data) + let s:bMayComplete = 1 + return '.' . omni#cpp#maycomplete#Complete() + endif + endif + return '.' +endfunc +" May complete function for arrow +function! omni#cpp#maycomplete#Arrow() + if s:CanUseOmnicompletion() && g:OmniCpp_MayCompleteArrow + let index = col('.') - 2 + if index >= 0 + let char = getline('.')[index] + if char == '-' + let g:omni#cpp#items#data = omni#cpp#items#Get(omni#cpp#utils#TokenizeCurrentInstruction('>')) + if len(g:omni#cpp#items#data) + let s:bMayComplete = 1 + return '>' . omni#cpp#maycomplete#Complete() + endif + endif + endif + endif + return '>' +endfunc + +" May complete function for double points +function! omni#cpp#maycomplete#Scope() + if s:CanUseOmnicompletion() && g:OmniCpp_MayCompleteScope + let index = col('.') - 2 + if index >= 0 + let char = getline('.')[index] + if char == ':' + let g:omni#cpp#items#data = omni#cpp#items#Get(omni#cpp#utils#TokenizeCurrentInstruction(':')) + if len(g:omni#cpp#items#data) + if len(g:omni#cpp#items#data[-1].tokens) && g:omni#cpp#items#data[-1].tokens[-1].value != '::' + let s:bMayComplete = 1 + return ':' . omni#cpp#maycomplete#Complete() + endif + endif + endif + endif + endif + return ':' +endfunc diff --git a/.vim/autoload/omni/cpp/namespaces.vim b/.vim/autoload/omni/cpp/namespaces.vim new file mode 100644 index 0000000..386b3f9 --- /dev/null +++ b/.vim/autoload/omni/cpp/namespaces.vim @@ -0,0 +1,838 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +let g:omni#cpp#namespaces#CacheResolve = {} +let g:omni#cpp#namespaces#CacheUsing = {} +" TODO: For the next release +"let g:omni#cpp#namespaces#CacheAlias = {} + +" Get the using namespace list from a line +function! s:GetNamespaceAliasListFromLine(szLine) + let result = {} + let tokens = omni#cpp#tokenizer#Tokenize(a:szLine) + let szAlias = '' + let szNamespace = '' + let state = 0 + for token in tokens + if state==0 + let szAlias = '' + let szNamespace = '' + if token.value == '/*' + let state = 1 + elseif token.value == '//' + " It's a comment + let state = -1 + break + elseif token.value == 'namespace' + let state = 2 + endif + elseif state==1 + if token.value == '*/' + let state=0 + endif + elseif state==2 + if token.kind == 'cppWord' + let szAlias .= token.value + let state = 3 + else + let state = -1 + break + endif + elseif state == 3 + if token.value == '=' + let state = 4 + else + let state = -1 + break + endif + elseif state == 4 + if token.value == '::' + let szNamespace .= token.value + let state = 5 + elseif token.kind == 'cppWord' + let szNamespace .= token.value + let state = 6 + " Maybe end of tokens + endif + elseif state==5 + if token.kind == 'cppWord' + let szNamespace .= token.value + let state = 6 + " Maybe end of tokens + else + " Error, we can't have 'namespace ALIAS = Something::' + let state = -1 + break + endif + elseif state==6 + if token.value == '::' + let szNamespace .= token.value + let state = 5 + else + call extend(result, {szAlias : szNamespace}) + let state = 0 + endif + endif + endfor + + if state == 6 + call extend(result, {szAlias : szNamespace}) + endif + + return result +endfunc + +" Get the using namespace list from a line +function! s:GetNamespaceListFromLine(szLine) + let result = [] + let tokens = omni#cpp#tokenizer#Tokenize(a:szLine) + let szNamespace = '' + let state = 0 + for token in tokens + if state==0 + let szNamespace = '' + if token.value == '/*' + let state = 1 + elseif token.value == '//' + " It's a comment + let state = -1 + break + elseif token.value == 'using' + let state = 2 + endif + elseif state==1 + if token.value == '*/' + let state=0 + endif + elseif state==2 + if token.value == 'namespace' + let state = 3 + else + " Error, 'using' must be followed by 'namespace' + let state = -1 + break + endif + elseif state==3 + if token.value == '::' + let szNamespace .= token.value + let state = 4 + elseif token.kind == 'cppWord' + let szNamespace .= token.value + let state = 5 + " Maybe end of tokens + endif + elseif state==4 + if token.kind == 'cppWord' + let szNamespace .= token.value + let state = 5 + " Maybe end of tokens + else + " Error, we can't have 'using namespace Something::' + let state = -1 + break + endif + elseif state==5 + if token.value == '::' + let szNamespace .= token.value + let state = 4 + else + call extend(result, [szNamespace]) + let state = 0 + endif + endif + endfor + + if state == 5 + call extend(result, [szNamespace]) + endif + + return result +endfunc + +" Get the namespace list from a namespace map +function! s:GetUsingNamespaceListFromMap(namespaceMap, ...) + let stopLine = 0 + if a:0>0 + let stopLine = a:1 + endif + + let result = [] + let keys = sort(keys(a:namespaceMap), 'omni#common#utils#CompareNumber') + for i in keys + if stopLine != 0 && i > stopLine + break + endif + call extend(result, a:namespaceMap[i]) + endfor + return result +endfunc + +" Get global using namespace list from the current buffer +function! omni#cpp#namespaces#GetListFromCurrentBuffer(...) + let namespaceMap = s:GetAllUsingNamespaceMapFromCurrentBuffer() + let result = [] + if namespaceMap != {} + let result = s:GetUsingNamespaceListFromMap(namespaceMap, (a:0 > 0)? a:1 : line('.')) + endif + return result +endfunc + +" Get global using namespace map from the current buffer and include files recursively +function! s:GetAllUsingNamespaceMapFromCurrentBuffer(...) + let includeGuard = (a:0>0)? a:1 : {} + + let szBufferName = getreg("%") + let szFilePath = omni#cpp#utils#ResolveFilePath(szBufferName) + let szFilePath = (szFilePath=='')? szBufferName : szFilePath + + let namespaceMap = {} + if has_key(includeGuard, szFilePath) + return namespaceMap + else + let includeGuard[szFilePath] = 1 + endif + + let namespaceMap = omni#cpp#namespaces#GetMapFromCurrentBuffer() + + if g:OmniCpp_NamespaceSearch != 2 + " We don't search included files if OmniCpp_NamespaceSearch != 2 + return namespaceMap + endif + + for inc in omni#cpp#includes#GetList() + let lnum = inc.pos[0] + let tmpMap = s:GetAllUsingNamespaceMapFromFile(inc.include, includeGuard) + if tmpMap != {} + if has_key(namespaceMap, lnum) + call extend(namespaceMap[lnum], s:GetUsingNamespaceListFromMap(tmpMap)) + else + let namespaceMap[lnum] = s:GetUsingNamespaceListFromMap(tmpMap) + endif + endif + endfor + + return namespaceMap +endfunc + +" Get global using namespace map from a file and include files recursively +function! s:GetAllUsingNamespaceMapFromFile(szFilePath, ...) + let includeGuard = {} + if a:0 >0 + let includeGuard = a:1 + endif + + let szFilePath = omni#cpp#utils#ResolveFilePath(a:szFilePath) + let szFilePath = (szFilePath=='')? a:szFilePath : szFilePath + + let namespaceMap = {} + if has_key(includeGuard, szFilePath) + return namespaceMap + else + let includeGuard[szFilePath] = 1 + endif + + " If g:OmniCpp_NamespaceSearch == 1 (search namespaces only in the current + " buffer) we don't use cache for the current buffer + let namespaceMap = omni#cpp#namespaces#GetMapFromBuffer(szFilePath, g:OmniCpp_NamespaceSearch==1) + + if g:OmniCpp_NamespaceSearch != 2 + " We don't search included files if OmniCpp_NamespaceSearch != 2 + return namespaceMap + endif + + for inc in omni#cpp#includes#GetList(szFilePath) + let lnum = inc.pos[0] + let tmpMap = s:GetAllUsingNamespaceMapFromFile(inc.include, includeGuard) + if tmpMap != {} + if has_key(namespaceMap, lnum) + call extend(namespaceMap[lnum], s:GetUsingNamespaceListFromMap(tmpMap)) + else + let namespaceMap[lnum] = s:GetUsingNamespaceListFromMap(tmpMap) + endif + endif + endfor + + return namespaceMap +endfunc + +" Get global using namespace map from a the current buffer +function! omni#cpp#namespaces#GetMapFromCurrentBuffer() + let namespaceMap = {} + let originalPos = getpos('.') + + call setpos('.', [0, 1, 1, 0]) + let curPos = [1,1] + while curPos != [0,0] + let curPos = searchpos('\C^using\s\+namespace', 'W') + if curPos != [0,0] + let szLine = getline('.') + let startPos = curPos[1] + let endPos = match(szLine, ';', startPos-1) + if endPos!=-1 + " We get the namespace list from the line + let namespaceMap[curPos[0]] = s:GetNamespaceListFromLine(szLine) + endif + endif + endwhile + + call setpos('.', originalPos) + return namespaceMap +endfunc + +" Get global using namespace map from a file +function! omni#cpp#namespaces#GetMapFromBuffer(szFilePath, ...) + let bUpdate = 0 + if a:0 > 0 + let bUpdate = a:1 + endif + + let szFilePath = omni#cpp#utils#ResolveFilePath(a:szFilePath) + let szFilePath = (szFilePath=='')? a:szFilePath : szFilePath + + if !bUpdate && has_key(g:omni#cpp#namespaces#CacheUsing, szFilePath) + return copy(g:omni#cpp#namespaces#CacheUsing[szFilePath]) + endif + + let namespaceMap = {} + " The file exists, we get the global namespaces in this file + let szFixedPath = escape(szFilePath, g:omni#cpp#utils#szEscapedCharacters) + execute 'silent! lvimgrep /\C^using\s\+namespace/gj '.szFixedPath + + " key = line number + " value = list of namespaces + let listQuickFix = getloclist(0) + for qf in listQuickFix + let szLine = qf.text + let startPos = qf.col + let endPos = match(szLine, ';', startPos-1) + if endPos!=-1 + " We get the namespace list from the line + let namespaceMap[qf.lnum] = s:GetNamespaceListFromLine(szLine) + endif + endfor + + if szFixedPath != '' + let g:omni#cpp#namespaces#CacheUsing[szFixedPath] = namespaceMap + endif + + return copy(namespaceMap) +endfunc + +" Get the stop position when searching for local variables +function! s:GetStopPositionForLocalSearch() + " Stop position when searching a local variable + let originalPos = getpos('.') + let origPos = originalPos[1:2] + let stopPosition = origPos + let curPos = origPos + while curPos !=[0,0] + let stopPosition = curPos + let curPos = searchpairpos('{', '', '}', 'bW', g:omni#cpp#utils#expIgnoreComments) + endwhile + call setpos('.', originalPos) + + return stopPosition +endfunc + +" Get namespaces alias used at the cursor postion in a vim buffer +" Note: The result depends on the current cursor position +" @return +" - Map of namespace alias +function! s:GetNamespaceAliasMap() + " We store the cursor position because searchpairpos() moves the cursor + let result = {} + let originalPos = getpos('.') + let origPos = originalPos[1:2] + + let stopPos = s:GetStopPositionForLocalSearch() + let stopLine = stopPos[0] + let curPos = origPos + let lastLine = 0 + let nextStopLine = origPos[0] + let szReAlias = '\Cnamespace\s\+\w\+\s\+=' + while curPos !=[0,0] + let curPos = searchpos('}\|\('. szReAlias .'\)', 'bW',stopLine) + if curPos!=[0,0] && curPos[0]!=lastLine + let lastLine = curPos[0] + + let szLine = getline('.') + if origPos[0] == curPos[0] + " We get the line until cursor position + let szLine = szLine[:origPos[1]] + endif + + let szLine = omni#cpp#utils#GetCodeFromLine(szLine) + if match(szLine, szReAlias)<0 + " We found a '}' + let curPos = searchpairpos('{', '', '}', 'bW', g:omni#cpp#utils#expIgnoreComments) + else + " We get the namespace alias from the line + call extend(result, s:GetNamespaceAliasListFromLine(szLine)) + let nextStopLine = curPos[0] + endif + endif + endwhile + + " Setting the cursor to the original position + call setpos('.', originalPos) + + call s:ResolveAliasKeys(result) + return result +endfunc + +" Resolve an alias +" eg: namespace IAmAnAlias1 = Ns1 +" eg: namespace IAmAnAlias2 = IAmAnAlias1::Ns2 +" => IAmAnAlias2 = Ns1::Ns2 +function! s:ResolveAliasKey(mapNamespaceAlias, szAlias) + let szResult = a:mapNamespaceAlias[a:szAlias] + " ::Ns1::Ns2::Ns3 => ['Ns1', 'Ns2', 'Ns3'] + let listNamespace = split(szResult, '::') + if len(listNamespace) + " szBeginPart = 'Ns1' + let szBeginPart = remove(listNamespace, 0) + + " Is 'Ns1' an alias ? + if has_key(a:mapNamespaceAlias, szBeginPart) && szBeginPart != a:szAlias + " Resolving alias 'Ns1' + " eg: Ns1 = NsResolved + let szResult = s:ResolveAliasKey(a:mapNamespaceAlias, szBeginPart) + " szEndPart = 'Ns2::Ns3' + let szEndPart = join(listNamespace, '::') + if szEndPart != '' + " Concatenation => szResult = 'NsResolved::Ns2::Ns3' + let szResult .= '::' . szEndPart + endif + endif + endif + return szResult +endfunc + +" Resolve all keys in the namespace alias map +function! s:ResolveAliasKeys(mapNamespaceAlias) + let mapNamespaceAlias = a:mapNamespaceAlias + call map(mapNamespaceAlias, 's:ResolveAliasKey(mapNamespaceAlias, v:key)') +endfunc + +" Resolve namespace alias +function! omni#cpp#namespaces#ResolveAlias(mapNamespaceAlias, szNamespace) + let szResult = a:szNamespace + " ::Ns1::Ns2::Ns3 => ['Ns1', 'Ns2', 'Ns3'] + let listNamespace = split(a:szNamespace, '::') + if len(listNamespace) + " szBeginPart = 'Ns1' + let szBeginPart = remove(listNamespace, 0) + + " Is 'Ns1' an alias ? + if has_key(a:mapNamespaceAlias, szBeginPart) + " Resolving alias 'Ns1' + " eg: Ns1 = NsResolved + let szResult = a:mapNamespaceAlias[szBeginPart] + " szEndPart = 'Ns2::Ns3' + let szEndPart = join(listNamespace, '::') + if szEndPart != '' + " Concatenation => szResult = 'NsResolved::Ns2::Ns3' + let szResult .= '::' . szEndPart + endif + + " If a:szNamespace starts with '::' we add '::' to the beginning + " of the result + if match(a:szNamespace, '^::')>=0 + let szResult = omni#cpp#utils#SimplifyScope('::' . szResult) + endif + endif + endif + return szResult +endfunc + +" Resolve namespace alias +function! s:ResolveAliasInNamespaceList(mapNamespaceAlias, listNamespaces) + call map(a:listNamespaces, 'omni#cpp#namespaces#ResolveAlias(a:mapNamespaceAlias, v:val)') +endfunc + +" Get namespaces used at the cursor postion in a vim buffer +" Note: The result depends on the current cursor position +" @return +" - List of namespace used in the reverse order +function! omni#cpp#namespaces#GetUsingNamespaces() + " We have to get local using namespace declarations + " We need the current cursor position and the position of the start of the + " current scope + + " We store the cursor position because searchpairpos() moves the cursor + let result = [] + let originalPos = getpos('.') + let origPos = originalPos[1:2] + + let stopPos = s:GetStopPositionForLocalSearch() + + let stopLine = stopPos[0] + let curPos = origPos + let lastLine = 0 + let nextStopLine = origPos[0] + while curPos !=[0,0] + let curPos = searchpos('\C}\|\(using\s\+namespace\)', 'bW',stopLine) + if curPos!=[0,0] && curPos[0]!=lastLine + let lastLine = curPos[0] + + let szLine = getline('.') + if origPos[0] == curPos[0] + " We get the line until cursor position + let szLine = szLine[:origPos[1]] + endif + + let szLine = omni#cpp#utils#GetCodeFromLine(szLine) + if match(szLine, '\Cusing\s\+namespace')<0 + " We found a '}' + let curPos = searchpairpos('{', '', '}', 'bW', g:omni#cpp#utils#expIgnoreComments) + else + " We get the namespace list from the line + let result = s:GetNamespaceListFromLine(szLine) + result + let nextStopLine = curPos[0] + endif + endif + endwhile + + " Setting the cursor to the original position + call setpos('.', originalPos) + + " 2) Now we can get all global using namespace declaration from the + " beginning of the file to nextStopLine + let result = omni#cpp#namespaces#GetListFromCurrentBuffer(nextStopLine) + result + + " Resolving alias in the namespace list + " TODO: For the next release + "let g:omni#cpp#namespaces#CacheAlias= s:GetNamespaceAliasMap() + "call s:ResolveAliasInNamespaceList(g:omni#cpp#namespaces#CacheAlias, result) + + return ['::'] + result +endfunc + +" Resolve a using namespace regarding the current context +" For each namespace used: +" - We get all possible contexts where the namespace +" can be define +" - We do a comparison test of each parent contexts with the current +" context list +" - If one and only one parent context is present in the +" current context list we add the namespace in the current +" context +" - If there is more than one of parent contexts in the +" current context the namespace is ambiguous +" @return +" - result item +" - kind = 0|1 +" - 0 = unresolved or error +" - 1 = resolved +" - value = resolved namespace +function! s:ResolveNamespace(namespace, mapCurrentContexts) + let result = {'kind':0, 'value': ''} + + " If the namespace is already resolved we add it in the list of + " current contexts + if match(a:namespace, '^::')>=0 + let result.kind = 1 + let result.value = a:namespace + return result + elseif match(a:namespace, '\w\+::\w\+')>=0 + let mapCurrentContextsTmp = copy(a:mapCurrentContexts) + let resolvedItem = {} + for nsTmp in split(a:namespace, '::') + let resolvedItem = s:ResolveNamespace(nsTmp, mapCurrentContextsTmp) + if resolvedItem.kind + " Note: We don't extend the map + let mapCurrentContextsTmp = {resolvedItem.value : 1} + else + break + endif + endfor + if resolvedItem!={} && resolvedItem.kind + let result.kind = 1 + let result.value = resolvedItem.value + endif + return result + endif + + " We get all possible parent contexts of this namespace + let listTagsOfNamespace = [] + if has_key(g:omni#cpp#namespaces#CacheResolve, a:namespace) + let listTagsOfNamespace = g:omni#cpp#namespaces#CacheResolve[a:namespace] + else + let listTagsOfNamespace = omni#common#utils#TagList('^'.a:namespace.'$') + let g:omni#cpp#namespaces#CacheResolve[a:namespace] = listTagsOfNamespace + endif + + if len(listTagsOfNamespace)==0 + return result + endif + call filter(listTagsOfNamespace, 'v:val.kind[0]=="n"') + + " We extract parent context from tags + " We use a map to avoid multiple entries + let mapContext = {} + for tagItem in listTagsOfNamespace + let szParentContext = omni#cpp#utils#ExtractScope(tagItem) + let mapContext[szParentContext] = 1 + endfor + let listParentContext = keys(mapContext) + + " Now for each parent context we test if the context is in the current + " contexts list + let listResolvedNamespace = [] + for szParentContext in listParentContext + if has_key(a:mapCurrentContexts, szParentContext) + call extend(listResolvedNamespace, [omni#cpp#utils#SimplifyScope(szParentContext.'::'.a:namespace)]) + endif + endfor + + " Now we know if the namespace is ambiguous or not + let len = len(listResolvedNamespace) + if len==1 + " Namespace resolved + let result.kind = 1 + let result.value = listResolvedNamespace[0] + elseif len > 1 + " Ambiguous namespace, possible matches are in listResolvedNamespace + else + " Other cases + endif + return result +endfunc + +" Resolve namespaces +"@return +" - List of resolved namespaces +function! omni#cpp#namespaces#ResolveAll(namespacesUsed) + + " We add the default context '::' + let contextOrder = 0 + let mapCurrentContexts = {} + + " For each namespace used: + " - We get all possible contexts where the namespace + " can be define + " - We do a comparison test of each parent contexts with the current + " context list + " - If one and only one parent context is present in the + " current context list we add the namespace in the current + " context + " - If there is more than one of parent contexts in the + " current context the namespace is ambiguous + for ns in a:namespacesUsed + let resolvedItem = s:ResolveNamespace(ns, mapCurrentContexts) + if resolvedItem.kind + let contextOrder+=1 + let mapCurrentContexts[resolvedItem.value] = contextOrder + endif + endfor + + " Build the list of current contexts from the map, we have to keep the + " order + let mapReorder = {} + for key in keys(mapCurrentContexts) + let mapReorder[ mapCurrentContexts[key] ] = key + endfor + let result = [] + for key in sort(keys(mapReorder)) + call extend(result, [mapReorder[key]]) + endfor + return result +endfunc + +" Build the context stack +function! s:BuildContextStack(namespaces, szCurrentScope) + let result = copy(a:namespaces) + if a:szCurrentScope != '::' + let tagItem = omni#cpp#utils#GetResolvedTagItem(a:namespaces, omni#cpp#utils#CreateTypeInfo(a:szCurrentScope)) + if has_key(tagItem, 'inherits') + let listBaseClass = omni#cpp#utils#GetClassInheritanceList(a:namespaces, omni#cpp#utils#CreateTypeInfo(a:szCurrentScope)) + let result = listBaseClass + result + elseif has_key(tagItem, 'kind') && index(['c', 's', 'u', 'n'], tagItem.kind[0])>=0 + call insert(result, omni#cpp#utils#ExtractTypeInfoFromTag(tagItem)) + endif + endif + return result +endfunc + +" Returns the class scope at the current position of the cursor +" @return a string that represents the class scope +" eg: ::NameSpace1::Class1 +" The returned string always starts with '::' +" Note: In term of performance it's the weak point of the script +function! s:GetClassScopeAtCursor() + " We store the cursor position because searchpairpos() moves the cursor + let originalPos = getpos('.') + let endPos = originalPos[1:2] + let listCode = [] + let result = {'namespaces': [], 'scope': ''} + + while endPos!=[0,0] + let endPos = searchpairpos('{', '', '}', 'bW', g:omni#cpp#utils#expIgnoreComments) + let szReStartPos = '[;{}]\|\%^' + let startPos = searchpairpos(szReStartPos, '', '{', 'bWn', g:omni#cpp#utils#expIgnoreComments) + + " If the file starts with a comment so the startPos can be [0,0] + " we change it to [1,1] + if startPos==[0,0] + let startPos = [1,1] + endif + + " Get lines backward from cursor position to last ; or { or } + " or when we are at the beginning of the file. + " We store lines in listCode + if endPos!=[0,0] + " We remove the last character which is a '{' + " We also remove starting { or } or ; if exits + let szCodeWithoutComments = substitute(omni#cpp#utils#GetCode(startPos, endPos)[:-2], '^[;{}]', '', 'g') + call insert(listCode, {'startLine' : startPos[0], 'code' : szCodeWithoutComments}) + endif + endwhile + " Setting the cursor to the original position + call setpos('.', originalPos) + + let listClassScope = [] + let bResolved = 0 + let startLine = 0 + " Now we can check in the list of code if there is a function + for code in listCode + " We get the name of the namespace, class, struct or union + " and we store it in listClassScope + let tokens = omni#cpp#tokenizer#Tokenize(code.code) + let bContinue=0 + let bAddNamespace = 0 + let state=0 + for token in tokens + if state==0 + if index(['namespace', 'class', 'struct', 'union'], token.value)>=0 + if token.value == 'namespace' + let bAddNamespace = 1 + endif + let state= 1 + " Maybe end of tokens + endif + elseif state==1 + if token.kind == 'cppWord' + " eg: namespace MyNs { class MyCl {}; } + " => listClassScope = [MyNs, MyCl] + call extend( listClassScope , [token.value] ) + + " Add the namespace in result + if bAddNamespace + call extend(result.namespaces, [token.value]) + let bAddNamespace = 0 + endif + + let bContinue=1 + break + endif + endif + endfor + if bContinue==1 + continue + endif + + " Simple test to check if we have a chance to find a + " class method + let aPos = matchend(code.code, '::\s*\~*\s*\w\+\s*(') + if aPos ==-1 + continue + endif + + let startLine = code.startLine + let listTmp = [] + " eg: 'void MyNamespace::MyClass::foo(' + " => tokens = ['MyClass', '::', 'MyNamespace', 'void'] + let tokens = reverse(omni#cpp#tokenizer#Tokenize(code.code[:aPos-1])[:-4]) + let state = 0 + " Reading tokens backward + for token in tokens + if state==0 + if token.kind=='cppWord' + call insert(listTmp, token.value) + let state=1 + endif + elseif state==1 + if token.value=='::' + let state=2 + else + break + endif + elseif state==2 + if token.kind=='cppWord' + call insert(listTmp, token.value) + let state=1 + else + break + endif + endif + endfor + + if len(listTmp) + if len(listClassScope) + let bResolved = 1 + " Merging class scopes + " eg: current class scope = 'MyNs::MyCl1' + " method class scope = 'MyCl1::MyCl2' + " If we add the method class scope to current class scope + " we'll have MyNs::MyCl1::MyCl1::MyCl2 => it's wrong + " we want MyNs::MyCl1::MyCl2 + let index = 0 + for methodClassScope in listTmp + if methodClassScope==listClassScope[-1] + let listTmp = listTmp[index+1:] + break + else + let index+=1 + endif + endfor + endif + call extend(listClassScope, listTmp) + break + endif + endfor + + let szClassScope = '::' + if len(listClassScope) + if bResolved + let szClassScope .= join(listClassScope, '::') + else + let szClassScope = join(listClassScope, '::') + + " The class scope is not resolved, we have to check using + " namespace declarations and search the class scope in each + " namespace + if startLine != 0 + let namespaces = ['::'] + omni#cpp#namespaces#GetListFromCurrentBuffer(startLine) + let namespaces = omni#cpp#namespaces#ResolveAll(namespaces) + let tagItem = omni#cpp#utils#GetResolvedTagItem(namespaces, omni#cpp#utils#CreateTypeInfo(szClassScope)) + if tagItem != {} + let szClassScope = omni#cpp#utils#ExtractTypeInfoFromTag(tagItem) + endif + endif + endif + endif + + let result.scope = szClassScope + return result +endfunc + +" Get all contexts at the cursor position +function! omni#cpp#namespaces#GetContexts() + " Get the current class scope at the cursor, the result depends on the current cursor position + let scopeItem = s:GetClassScopeAtCursor() + let listUsingNamespace = copy(g:OmniCpp_DefaultNamespaces) + call extend(listUsingNamespace, scopeItem.namespaces) + if g:OmniCpp_NamespaceSearch && &filetype != 'c' + " Get namespaces used in the file until the cursor position + let listUsingNamespace = omni#cpp#namespaces#GetUsingNamespaces() + listUsingNamespace + " Resolving namespaces, removing ambiguous namespaces + let namespaces = omni#cpp#namespaces#ResolveAll(listUsingNamespace) + else + let namespaces = ['::'] + listUsingNamespace + endif + call reverse(namespaces) + + " Building context stack from namespaces and the current class scope + return s:BuildContextStack(namespaces, scopeItem.scope) +endfunc diff --git a/.vim/autoload/omni/cpp/settings.vim b/.vim/autoload/omni/cpp/settings.vim new file mode 100644 index 0000000..6683d3a --- /dev/null +++ b/.vim/autoload/omni/cpp/settings.vim @@ -0,0 +1,96 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +function! omni#cpp#settings#Init() + " Global scope search on/off + " 0 = disabled + " 1 = enabled + if !exists('g:OmniCpp_GlobalScopeSearch') + let g:OmniCpp_GlobalScopeSearch = 1 + endif + + " Sets the namespace search method + " 0 = disabled + " 1 = search namespaces in the current file + " 2 = search namespaces in the current file and included files + if !exists('g:OmniCpp_NamespaceSearch') + let g:OmniCpp_NamespaceSearch = 1 + endif + + " Set the class scope completion mode + " 0 = auto + " 1 = show all members (static, public, protected and private) + if !exists('g:OmniCpp_DisplayMode') + let g:OmniCpp_DisplayMode = 0 + endif + + " Set if the scope is displayed in the abbr column of the popup + " 0 = no + " 1 = yes + if !exists('g:OmniCpp_ShowScopeInAbbr') + let g:OmniCpp_ShowScopeInAbbr = 0 + endif + + " Set if the function prototype is displayed in the abbr column of the popup + " 0 = no + " 1 = yes + if !exists('g:OmniCpp_ShowPrototypeInAbbr') + let g:OmniCpp_ShowPrototypeInAbbr = 0 + endif + + " Set if the access (+,#,-) is displayed + " 0 = no + " 1 = yes + if !exists('g:OmniCpp_ShowAccess') + let g:OmniCpp_ShowAccess = 1 + endif + + " Set the list of default namespaces + " eg: ['std'] + if !exists('g:OmniCpp_DefaultNamespaces') + let g:OmniCpp_DefaultNamespaces = [] + endif + + " Set MayComplete to '.' + " 0 = disabled + " 1 = enabled + " default = 1 + if !exists('g:OmniCpp_MayCompleteDot') + let g:OmniCpp_MayCompleteDot = 1 + endif + + " Set MayComplete to '->' + " 0 = disabled + " 1 = enabled + " default = 1 + if !exists('g:OmniCpp_MayCompleteArrow') + let g:OmniCpp_MayCompleteArrow = 1 + endif + + " Set MayComplete to dot + " 0 = disabled + " 1 = enabled + " default = 0 + if !exists('g:OmniCpp_MayCompleteScope') + let g:OmniCpp_MayCompleteScope = 0 + endif + + " When completeopt does not contain longest option, this setting + " controls the behaviour of the popup menu selection when starting the completion + " 0 = don't select first item + " 1 = select first item (inserting it to the text) + " 2 = select first item (without inserting it to the text) + " default = 0 + if !exists('g:OmniCpp_SelectFirstItem') + let g:OmniCpp_SelectFirstItem= 0 + endif + + " Use local search function for variable definitions + " 0 = use standard vim search function + " 1 = use local search function + " default = 0 + if !exists('g:OmniCpp_LocalSearchDecl') + let g:OmniCpp_LocalSearchDecl= 0 + endif +endfunc diff --git a/.vim/autoload/omni/cpp/tokenizer.vim b/.vim/autoload/omni/cpp/tokenizer.vim new file mode 100644 index 0000000..16e0be2 --- /dev/null +++ b/.vim/autoload/omni/cpp/tokenizer.vim @@ -0,0 +1,93 @@ +" Description: Omni completion tokenizer +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 +" TODO: Generic behaviour for Tokenize() + +" From the C++ BNF +let s:cppKeyword = ['asm', 'auto', 'bool', 'break', 'case', 'catch', 'char', 'class', 'const', 'const_cast', 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'operator', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast', 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not', 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'] + +let s:reCppKeyword = '\C\<'.join(s:cppKeyword, '\>\|\<').'\>' + +" The order of items in this list is very important because we use this list to build a regular +" expression (see below) for tokenization +let s:cppOperatorPunctuator = ['->*', '->', '--', '-=', '-', '!=', '!', '##', '#', '%:%:', '%=', '%>', '%:', '%', '&&', '&=', '&', '(', ')', '*=', '*', ',', '...', '.*', '.', '/=', '/', '::', ':>', ':', ';', '?', '[', ']', '^=', '^', '{', '||', '|=', '|', '}', '~', '++', '+=', '+', '<<=', '<%', '<:', '<<', '<=', '<', '==', '=', '>>=', '>>', '>=', '>'] + +" We build the regexp for the tokenizer +let s:reCComment = '\/\*\|\*\/' +let s:reCppComment = '\/\/' +let s:reComment = s:reCComment.'\|'.s:reCppComment +let s:reCppOperatorOrPunctuator = escape(join(s:cppOperatorPunctuator, '\|'), '*./^~[]') + + +" Tokenize a c++ code +" a token is dictionary where keys are: +" - kind = cppKeyword|cppWord|cppOperatorPunctuator|unknown|cComment|cppComment|cppDigit +" - value = 'something' +" Note: a cppWord is any word that is not a cpp keyword +function! omni#cpp#tokenizer#Tokenize(szCode) + let result = [] + + " The regexp to find a token, a token is a keyword, word or + " c++ operator or punctuator. To work properly we have to put + " spaces and tabs to our regexp. + let reTokenSearch = '\(\w\+\)\|\s\+\|'.s:reComment.'\|'.s:reCppOperatorOrPunctuator + " eg: 'using namespace std;' + " ^ ^ + " start=0 end=5 + let startPos = 0 + let endPos = matchend(a:szCode, reTokenSearch) + let len = endPos-startPos + while endPos!=-1 + " eg: 'using namespace std;' + " ^ ^ + " start=0 end=5 + " token = 'using' + " We also remove space and tabs + let token = substitute(strpart(a:szCode, startPos, len), '\s', '', 'g') + + " eg: 'using namespace std;' + " ^ ^ + " start=5 end=15 + let startPos = endPos + let endPos = matchend(a:szCode, reTokenSearch, startPos) + let len = endPos-startPos + + " It the token is empty we continue + if token=='' + continue + endif + + " Building the token + let resultToken = {'kind' : 'unknown', 'value' : token} + + " Classify the token + if token =~ '^\d\+' + " It's a digit + let resultToken.kind = 'cppDigit' + elseif token=~'^\w\+$' + " It's a word + let resultToken.kind = 'cppWord' + + " But maybe it's a c++ keyword + if match(token, s:reCppKeyword)>=0 + let resultToken.kind = 'cppKeyword' + endif + else + if match(token, s:reComment)>=0 + if index(['/*','*/'],token)>=0 + let resultToken.kind = 'cComment' + else + let resultToken.kind = 'cppComment' + endif + else + " It's an operator + let resultToken.kind = 'cppOperatorPunctuator' + endif + endif + + " We have our token, let's add it to the result list + call extend(result, [resultToken]) + endwhile + + return result +endfunc diff --git a/.vim/autoload/omni/cpp/utils.vim b/.vim/autoload/omni/cpp/utils.vim new file mode 100644 index 0000000..5d74d34 --- /dev/null +++ b/.vim/autoload/omni/cpp/utils.vim @@ -0,0 +1,587 @@ +" Description: Omni completion script for cpp files +" Maintainer: Vissale NEANG +" Last Change: 26 sept. 2007 + +let g:omni#cpp#utils#CACHE_TAG_INHERITS = {} +let g:omni#cpp#utils#szFilterGlobalScope = "(!has_key(v:val, 'class') && !has_key(v:val, 'struct') && !has_key(v:val, 'union') && !has_key(v:val, 'namespace')" +let g:omni#cpp#utils#szFilterGlobalScope .= "&& (!has_key(v:val, 'enum') || (has_key(v:val, 'enum') && v:val.enum =~ '^\\w\\+$')))" + +" Expression used to ignore comments +" Note: this expression drop drastically the performance +"let omni#cpp#utils#expIgnoreComments = 'match(synIDattr(synID(line("."), col("."), 1), "name"), '\CcComment')!=-1' +" This one is faster but not really good for C comments +let omni#cpp#utils#reIgnoreComment = escape('\/\/\|\/\*\|\*\/', '*/\') +let omni#cpp#utils#expIgnoreComments = 'getline(".") =~ g:omni#cpp#utils#reIgnoreComment' + +" Characters to escape in a filename for vimgrep +"TODO: Find more characters to escape +let omni#cpp#utils#szEscapedCharacters = ' %#' + +" Resolve the path of the file +" TODO: absolute file path +function! omni#cpp#utils#ResolveFilePath(szFile) + let result = '' + let listPath = split(globpath(&path, a:szFile), "\n") + if len(listPath) + let result = listPath[0] + endif + return simplify(result) +endfunc + +" Get code without comments and with empty strings +" szSingleLine must not have carriage return +function! omni#cpp#utils#GetCodeFromLine(szSingleLine) + " We set all strings to empty strings, it's safer for + " the next of the process + let szResult = substitute(a:szSingleLine, '".*"', '""', 'g') + + " Removing c++ comments, we can use the pattern ".*" because + " we are modifying a line + let szResult = substitute(szResult, '\/\/.*', '', 'g') + + " Now we have the entire code in one line and we can remove C comments + return s:RemoveCComments(szResult) +endfunc + +" Remove C comments on a line +function! s:RemoveCComments(szLine) + let result = a:szLine + + " We have to match the first '/*' and first '*/' + let startCmt = match(result, '\/\*') + let endCmt = match(result, '\*\/') + while startCmt!=-1 && endCmt!=-1 && startCmt0 + let result = result[ : startCmt-1 ] . result[ endCmt+2 : ] + else + " Case where '/*' is at the start of the line + let result = result[ endCmt+2 : ] + endif + let startCmt = match(result, '\/\*') + let endCmt = match(result, '\*\/') + endwhile + return result +endfunc + +" Get a c++ code from current buffer from [lineStart, colStart] to +" [lineEnd, colEnd] without c++ and c comments, without end of line +" and with empty strings if any +" @return a string +function! omni#cpp#utils#GetCode(posStart, posEnd) + let posStart = a:posStart + let posEnd = a:posEnd + if a:posStart[0]>a:posEnd[0] + let posStart = a:posEnd + let posEnd = a:posStart + elseif a:posStart[0]==a:posEnd[0] && a:posStart[1]>a:posEnd[1] + let posStart = a:posEnd + let posEnd = a:posStart + endif + + " Getting the lines + let lines = getline(posStart[0], posEnd[0]) + let lenLines = len(lines) + + " Formatting the result + let result = '' + if lenLines==1 + let sStart = posStart[1]-1 + let sEnd = posEnd[1]-1 + let line = lines[0] + let lenLastLine = strlen(line) + let sEnd = (sEnd>lenLastLine)?lenLastLine : sEnd + if sStart >= 0 + let result = omni#cpp#utils#GetCodeFromLine(line[ sStart : sEnd ]) + endif + elseif lenLines>1 + let sStart = posStart[1]-1 + let sEnd = posEnd[1]-1 + let lenLastLine = strlen(lines[-1]) + let sEnd = (sEnd>lenLastLine)?lenLastLine : sEnd + if sStart >= 0 + let lines[0] = lines[0][ sStart : ] + let lines[-1] = lines[-1][ : sEnd ] + for aLine in lines + let result = result . omni#cpp#utils#GetCodeFromLine(aLine)." " + endfor + let result = result[:-2] + endif + endif + + " Now we have the entire code in one line and we can remove C comments + return s:RemoveCComments(result) +endfunc + +" Extract the scope (context) of a tag item +" eg: ::MyNamespace +" @return a string of the scope. a scope from tag always starts with '::' +function! omni#cpp#utils#ExtractScope(tagItem) + let listKindScope = ['class', 'struct', 'union', 'namespace', 'enum'] + let szResult = '::' + for scope in listKindScope + if has_key(a:tagItem, scope) + let szResult = szResult . a:tagItem[scope] + break + endif + endfor + return szResult +endfunc + +" Simplify scope string, remove consecutive '::' if any +function! omni#cpp#utils#SimplifyScope(szScope) + let szResult = substitute(a:szScope, '\(::\)\+', '::', 'g') + if szResult=='::' + return szResult + else + return substitute(szResult, '::$', '', 'g') + endif +endfunc + +" Check if the cursor is in comment +function! omni#cpp#utils#IsCursorInCommentOrString() + return match(synIDattr(synID(line("."), col(".")-1, 1), "name"), '\C\=0 +endfunc + +" Tokenize the current instruction until the cursor position. +" @return list of tokens +function! omni#cpp#utils#TokenizeCurrentInstruction(...) + let szAppendText = '' + if a:0>0 + let szAppendText = a:1 + endif + + let startPos = searchpos('[;{}]\|\%^', 'bWn') + let curPos = getpos('.')[1:2] + " We don't want the character under the cursor + let column = curPos[1]-1 + let curPos[1] = (column<1)?1:column + return omni#cpp#tokenizer#Tokenize(omni#cpp#utils#GetCode(startPos, curPos)[1:] . szAppendText) +endfunc + +" Tokenize the current instruction until the word under the cursor. +" @return list of tokens +function! omni#cpp#utils#TokenizeCurrentInstructionUntilWord() + let startPos = searchpos('[;{}]\|\%^', 'bWn') + + " Saving the current cursor pos + let originalPos = getpos('.') + + " We go at the end of the word + execute 'normal gee' + let curPos = getpos('.')[1:2] + + " Restoring the original cursor pos + call setpos('.', originalPos) + + let szCode = omni#cpp#utils#GetCode(startPos, curPos)[1:] + return omni#cpp#tokenizer#Tokenize(szCode) +endfunc + +" Build parenthesis groups +" add a new key 'group' in the token +" where value is the group number of the parenthesis +" eg: (void*)(MyClass*) +" group1 group0 +" if a parenthesis is unresolved the group id is -1 +" @return a copy of a:tokens with parenthesis group +function! omni#cpp#utils#BuildParenthesisGroups(tokens) + let tokens = copy(a:tokens) + let kinds = {'(': '()', ')' : '()', '[' : '[]', ']' : '[]', '<' : '<>', '>' : '<>', '{': '{}', '}': '{}'} + let unresolved = {'()' : [], '[]': [], '<>' : [], '{}' : []} + let groupId = 0 + + " Note: we build paren group in a backward way + " because we can often have parenthesis unbalanced + " instruction + " eg: doSomething(_member.get()-> + for token in reverse(tokens) + if index([')', ']', '>', '}'], token.value)>=0 + let token['group'] = groupId + call extend(unresolved[kinds[token.value]], [token]) + let groupId+=1 + elseif index(['(', '[', '<', '{'], token.value)>=0 + if len(unresolved[kinds[token.value]]) + let tokenResolved = remove(unresolved[kinds[token.value]], -1) + let token['group'] = tokenResolved.group + else + let token['group'] = -1 + endif + endif + endfor + + return reverse(tokens) +endfunc + +" Determine if tokens represent a C cast +" @return +" - itemCast +" - itemCppCast +" - itemVariable +" - itemThis +function! omni#cpp#utils#GetCastType(tokens) + " Note: a:tokens is not modified + let tokens = omni#cpp#utils#SimplifyParenthesis(omni#cpp#utils#BuildParenthesisGroups(a:tokens)) + + if tokens[0].value == '(' + return 'itemCast' + elseif index(['static_cast', 'dynamic_cast', 'reinterpret_cast', 'const_cast'], tokens[0].value)>=0 + return 'itemCppCast' + else + for token in tokens + if token.value=='this' + return 'itemThis' + endif + endfor + return 'itemVariable' + endif +endfunc + +" Remove useless parenthesis +function! omni#cpp#utils#SimplifyParenthesis(tokens) + "Note: a:tokens is not modified + let tokens = a:tokens + " We remove useless parenthesis eg: (((MyClass))) + if len(tokens)>2 + while tokens[0].value=='(' && tokens[-1].value==')' && tokens[0].group==tokens[-1].group + let tokens = tokens[1:-2] + endwhile + endif + return tokens +endfunc + +" Function create a type info +function! omni#cpp#utils#CreateTypeInfo(param) + let type = type(a:param) + return {'type': type, 'value':a:param} +endfunc + +" Extract type info from a tag item +" eg: ::MyNamespace::MyClass +function! omni#cpp#utils#ExtractTypeInfoFromTag(tagItem) + let szTypeInfo = omni#cpp#utils#ExtractScope(a:tagItem) . '::' . substitute(a:tagItem.name, '.*::', '', 'g') + return omni#cpp#utils#SimplifyScope(szTypeInfo) +endfunc + +" Build a class inheritance list +function! omni#cpp#utils#GetClassInheritanceList(namespaces, typeInfo) + let result = [] + for tagItem in omni#cpp#utils#GetResolvedTags(a:namespaces, a:typeInfo) + call extend(result, [omni#cpp#utils#ExtractTypeInfoFromTag(tagItem)]) + endfor + return result +endfunc + +" Get class inheritance list where items in the list are tag items. +" TODO: Verify inheritance order +function! omni#cpp#utils#GetResolvedTags(namespaces, typeInfo) + let result = [] + let tagItem = omni#cpp#utils#GetResolvedTagItem(a:namespaces, a:typeInfo) + if tagItem!={} + let szTypeInfo = omni#cpp#utils#ExtractTypeInfoFromTag(tagItem) + if has_key(g:omni#cpp#utils#CACHE_TAG_INHERITS, szTypeInfo) + let result = g:omni#cpp#utils#CACHE_TAG_INHERITS[szTypeInfo] + else + call extend(result, [tagItem]) + if has_key(tagItem, 'inherits') + for baseClassTypeInfo in split(tagItem.inherits, ',') + let namespaces = [omni#cpp#utils#ExtractScope(tagItem), '::'] + call extend(result, omni#cpp#utils#GetResolvedTags(namespaces, omni#cpp#utils#CreateTypeInfo(baseClassTypeInfo))) + endfor + endif + let g:omni#cpp#utils#CACHE_TAG_INHERITS[szTypeInfo] = result + endif + endif + return result +endfunc + +" Get a tag item after a scope resolution and typedef resolution +function! omni#cpp#utils#GetResolvedTagItem(namespaces, typeInfo) + let typeInfo = {} + if type(a:typeInfo) == 1 + let typeInfo = omni#cpp#utils#CreateTypeInfo(a:typeInfo) + else + let typeInfo = a:typeInfo + endif + + let result = {} + if !omni#cpp#utils#IsTypeInfoValid(typeInfo) + return result + endif + + " Unnamed type case eg: '1::2' + if typeInfo.type == 4 + " Here there is no typedef or namespace to resolve, the tagInfo.value is a tag item + " representing a variable ('v') a member ('m') or a typedef ('t') and the typename is + " always in global scope + return typeInfo.value + endif + + " Named type case eg: 'MyNamespace::MyClass' + let szTypeInfo = omni#cpp#utils#GetTypeInfoString(typeInfo) + + " Resolving namespace alias + " TODO: For the next release + "let szTypeInfo = omni#cpp#namespaces#ResolveAlias(g:omni#cpp#namespaces#CacheAlias, szTypeInfo) + + if szTypeInfo=='::' + return result + endif + + " We can only get members of class, struct, union and namespace + let szTagFilter = "index(['c', 's', 'u', 'n', 't'], v:val.kind[0])>=0" + let szTagQuery = szTypeInfo + + if s:IsTypeInfoResolved(szTypeInfo) + " The type info is already resolved, we remove the starting '::' + let szTagQuery = substitute(szTypeInfo, '^::', '', 'g') + if len(split(szTagQuery, '::'))==1 + " eg: ::MyClass + " Here we have to get tags that have no parent scope + " That's why we change the szTagFilter + let szTagFilter .= '&& ' . g:omni#cpp#utils#szFilterGlobalScope + let tagList = omni#common#utils#TagListNoThrow('^'.szTagQuery.'$') + call filter(tagList, szTagFilter) + if len(tagList) + let result = tagList[0] + endif + else + " eg: ::MyNamespace::MyClass + let tagList = omni#common#utils#TagListNoThrow('^'.szTagQuery.'$') + call filter(tagList, szTagFilter) + + if len(tagList) + let result = tagList[0] + endif + endif + else + " The type is not resolved + let tagList = omni#common#utils#TagListNoThrow('^'.szTagQuery.'$') + call filter(tagList, szTagFilter) + + if len(tagList) + " Resolving scope (namespace, nested class etc...) + let szScopeOfTypeInfo = s:ExtractScopeFromTypeInfo(szTypeInfo) + if s:IsTypeInfoResolved(szTypeInfo) + let result = s:GetTagOfSameScope(tagList, szScopeOfTypeInfo) + else + " For each namespace of the namespace list we try to get a tag + " that can be in the same scope + if g:OmniCpp_NamespaceSearch && &filetype != 'c' + for scope in a:namespaces + let szTmpScope = omni#cpp#utils#SimplifyScope(scope.'::'.szScopeOfTypeInfo) + let result = s:GetTagOfSameScope(tagList, szTmpScope) + if result!={} + break + endif + endfor + else + let szTmpScope = omni#cpp#utils#SimplifyScope('::'.szScopeOfTypeInfo) + let result = s:GetTagOfSameScope(tagList, szTmpScope) + endif + endif + endif + endif + + if result!={} + " We have our tagItem but maybe it's a typedef or an unnamed type + if result.kind[0]=='t' + " Here we can have a typedef to another typedef, a class, struct, union etc + " but we can also have a typedef to an unnamed type, in that + " case the result contains a 'typeref' key + let namespaces = [omni#cpp#utils#ExtractScope(result), '::'] + if has_key(result, 'typeref') + let result = omni#cpp#utils#GetResolvedTagItem(namespaces, omni#cpp#utils#CreateTypeInfo(result)) + else + let szCmd = omni#cpp#utils#ExtractCmdFromTagItem(result) + let szCode = substitute(omni#cpp#utils#GetCodeFromLine(szCmd), '\C\<'.result.name.'\>.*', '', 'g') + let szTypeInfo = omni#cpp#utils#ExtractTypeInfoFromTokens(omni#cpp#tokenizer#Tokenize(szCode)) + let result = omni#cpp#utils#GetResolvedTagItem(namespaces, omni#cpp#utils#CreateTypeInfo(szTypeInfo)) + " TODO: Namespace resolution for result + endif + endif + endif + + return result +endfunc + +" Returns if the type info is valid +" @return +" - 1 if valid +" - 0 otherwise +function! omni#cpp#utils#IsTypeInfoValid(typeInfo) + if a:typeInfo=={} + return 0 + else + if a:typeInfo.type == 1 && a:typeInfo.value=='' + " String case + return 0 + elseif a:typeInfo.type == 4 && a:typeInfo.value=={} + " Dictionary case + return 0 + endif + endif + return 1 +endfunc + +" Get the string of the type info +function! omni#cpp#utils#GetTypeInfoString(typeInfo) + if a:typeInfo.type == 1 + return a:typeInfo.value + else + return substitute(a:typeInfo.value.typeref, '^\w\+:', '', 'g') + endif +endfunc + +" A resolved type info starts with '::' +" @return +" - 1 if type info starts with '::' +" - 0 otherwise +function! s:IsTypeInfoResolved(szTypeInfo) + return match(a:szTypeInfo, '^::')!=-1 +endfunc + +" A returned type info's scope may not have the global namespace '::' +" eg: '::NameSpace1::NameSpace2::MyClass' => '::NameSpace1::NameSpace2' +" 'NameSpace1::NameSpace2::MyClass' => 'NameSpace1::NameSpace2' +function! s:ExtractScopeFromTypeInfo(szTypeInfo) + let szScope = substitute(a:szTypeInfo, '\w\+$', '', 'g') + if szScope =='::' + return szScope + else + return substitute(szScope, '::$', '', 'g') + endif +endfunc + +" @return +" - the tag with the same scope +" - {} otherwise +function! s:GetTagOfSameScope(listTags, szScopeToMatch) + for tagItem in a:listTags + let szScopeOfTag = omni#cpp#utils#ExtractScope(tagItem) + if szScopeOfTag == a:szScopeToMatch + return tagItem + endif + endfor + return {} +endfunc + +" Extract the cmd of a tag item without regexp +function! omni#cpp#utils#ExtractCmdFromTagItem(tagItem) + let line = a:tagItem.cmd + let re = '\(\/\^\)\|\(\$\/\)' + if match(line, re)!=-1 + let line = substitute(line, re, '', 'g') + return line + else + " TODO: the cmd is a line number + return '' + endif +endfunc + +" Extract type from tokens. +" eg: examples of tokens format +" 'const MyClass&' +" 'const map < int, int >&' +" 'MyNs::MyClass' +" '::MyClass**' +" 'MyClass a, *b = NULL, c[1] = {}; +" 'hello(MyClass a, MyClass* b' +" @return the type info string eg: ::std::map +" can be empty +function! omni#cpp#utils#ExtractTypeInfoFromTokens(tokens) + let szResult = '' + let state = 0 + + let tokens = omni#cpp#utils#BuildParenthesisGroups(a:tokens) + + " If there is an unbalanced parenthesis we are in a parameter list + let bParameterList = 0 + for token in tokens + if token.value == '(' && token.group==-1 + let bParameterList = 1 + break + endif + endfor + + if bParameterList + let tokens = reverse(tokens) + let state = 0 + let parenGroup = -1 + for token in tokens + if state==0 + if token.value=='>' + let parenGroup = token.group + let state=1 + elseif token.kind == 'cppWord' + let szResult = token.value.szResult + let state=2 + elseif index(['*', '&'], token.value)<0 + break + endif + elseif state==1 + if token.value=='<' && token.group==parenGroup + let state=0 + endif + elseif state==2 + if token.value=='::' + let szResult = token.value.szResult + let state=3 + else + break + endif + elseif state==3 + if token.kind == 'cppWord' + let szResult = token.value.szResult + let state=2 + else + break + endif + endif + endfor + return szResult + endif + + for token in tokens + if state==0 + if token.value == '::' + let szResult .= token.value + let state = 1 + elseif token.kind == 'cppWord' + let szResult .= token.value + let state = 2 + " Maybe end of token + endif + elseif state==1 + if token.kind == 'cppWord' + let szResult .= token.value + let state = 2 + " Maybe end of token + else + break + endif + elseif state==2 + if token.value == '::' + let szResult .= token.value + let state = 1 + else + break + endif + endif + endfor + return szResult +endfunc + +" Get the preview window string +function! omni#cpp#utils#GetPreviewWindowStringFromTagItem(tagItem) + let szResult = '' + + let szResult .= 'name: '.a:tagItem.name."\n" + for tagKey in keys(a:tagItem) + if index(['name', 'static'], tagKey)>=0 + continue + endif + let szResult .= tagKey.': '.a:tagItem[tagKey]."\n" + endfor + + return substitute(szResult, "\n$", '', 'g') +endfunc diff --git a/.vim/doc/NERD_tree.txt b/.vim/doc/NERD_tree.txt new file mode 100644 index 0000000..4b6e38f --- /dev/null +++ b/.vim/doc/NERD_tree.txt @@ -0,0 +1,980 @@ +*NERD_tree.txt* A tree explorer plugin that owns your momma! + + + + + + ________ ________ _ ____________ ____ __________ ____________~ + /_ __/ / / / ____/ / | / / ____/ __ \/ __ \ /_ __/ __ \/ ____/ ____/~ + / / / /_/ / __/ / |/ / __/ / /_/ / / / / / / / /_/ / __/ / __/ ~ + / / / __ / /___ / /| / /___/ _, _/ /_/ / / / / _, _/ /___/ /___ ~ + /_/ /_/ /_/_____/ /_/ |_/_____/_/ |_/_____/ /_/ /_/ |_/_____/_____/ ~ + + + Reference Manual~ + + + + +============================================================================== +CONTENTS *NERDTree-contents* + + 1.Intro...................................|NERDTree| + 2.Functionality provided..................|NERDTreeFunctionality| + 2.1 Commands..........................|NERDTreeCommands| + 2.2 NERD tree mappings................|NERDTreeMappings| + 2.3 The filesystem menu...............|NERDTreeFilesysMenu| + 3.Options.................................|NERDTreeOptions| + 3.1 Option summary....................|NERDTreeOptionSummary| + 3.2 Option details....................|NERDTreeOptionDetails| + 4.Public functions........................|NERDTreePublicFunctions| + 5.TODO list...............................|NERDTreeTodo| + 6.The Author..............................|NERDTreeAuthor| + 7.Changelog...............................|NERDTreeChangelog| + 8.Credits.................................|NERDTreeCredits| + +============================================================================== +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 so you can alter the tree dynamically. + +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 + * 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 + * ... + * Most NERD tree navigation can also be done with the mouse + * Dynamic customisation of tree content + * 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 + * A textual filesystem menu is provided which allows you to + create/delete/rename file and directory nodes + * 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 + +============================================================================== +2. Functionality provided *NERDTreeFunctionality* + +------------------------------------------------------------------------------ +2.1. Commands *NERDTreeCommands* + +:NERDTree [start-directory] *:NERDTree* + Opens a fresh NERD tree in [start-directory] or the current + directory if [start-directory] isn't specified. + For example: > + :NERDTree /home/marty/vim7/src +< will open a NERD tree in /home/marty/vim7/src. + +:NERDTreeToggle [start-directory] *: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. + +------------------------------------------------------------------------------ +2.2. NERD tree Mappings *NERDTreeMappings* + +Default Description~ help-tag~ +Key~ + +o.......Open selected file, or expand selected dir...............|NERDTree-o| +go......Open selected file, but leave cursor in the NERDTree.....|NERDTree-go| +t.......Open selected node in a new tab..........................|NERDTree-t| +T.......Same as 't' but keep the focus on the current tab........|NERDTree-T| +...Open selected file in a split window.....................|NERDTree-tab| +g..Same as , but leave the cursor on the NERDTree......|NERDTree-gtab| +!.......Execute the current file.................................|NERDTree-!| +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.......Open a netrw for the current dir.........................|NERDTree-e| + +double-click.......same as the |NERDTree-o| map. +middle-click.......same as |NERDTree-tab| for files, same as + |NERDTree-e| for dirs. + +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| +...Jump down to the next sibling of the current directory...|NERDTree-c-j| +...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 filesystem menu..............................|NERDTree-m| +cd......Change the CWD to the dir of the selected node...........|NERDTree-cd| + +H.......Toggle whether hidden files displayed....................|NERDTree-H| +f.......Toggle whether the file filters are used.................|NERDTree-f| +F.......Toggle whether files are displayed.......................|NERDTree-F| + +q.......Close the NERDTree window................................|NERDTree-q| +?.......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. + +------------------------------------------------------------------------------ + *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 netrw is +opened 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-tab* +Default key: +Map option: NERDTreeMapOpenSplit +Applies to: files. + +Opens the selected file in a new split window and puts the cursor in the new +window. + +------------------------------------------------------------------------------ + *NERDTree-gtab* +Default key: g +Map option: None +Applies to: files. + +The same as |NERDTree-tab| except that the cursor is not moved. + +The key combo for this mapping is always "g" + NERDTreeMapOpenSplit (see +|NERDTree-tab|). + +------------------------------------------------------------------------------ + *NERDTree-!* +Default key: ! +Map option: NERDTreeMapExecute +Applies to: files. + +Executes the selected file, prompting for arguments first. + +------------------------------------------------------------------------------ + *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 it is not opened. 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. + +Opens a netrw on the selected directory, or the selected file's directory. + +------------------------------------------------------------------------------ + *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: +Map option: NERDTreeMapJumpNextSibling +Applies to: files and directories. + +If a dir node is selected, jump to the next sibling of that node. +If a file node is selected, jump to the next sibling of that nodes parent. + +------------------------------------------------------------------------------ + *NERDTree-c-k* +Default key: +Map option: NERDTreeMapJumpPrevSibling +Applies to: files and directories. + +If a dir node is selected, jump to the previous sibling of that node. +If a file node is selected, jump to the previous sibling of that nodes parent. + +------------------------------------------------------------------------------ + *NERDTree-C* +Default key: C +Map option: NERDTreeMapChdir +Applies to: directories. + +Made the selected directory node the new tree root. + +------------------------------------------------------------------------------ + *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: NERDTreeMapFilesystemMenu +Applies to: files and directories. + +Display the filesystem menu. See |NERDTreeFilesysMenu| for details. + +------------------------------------------------------------------------------ + *NERDTree-H* +Default key: H +Map option: NERDTreeMapToggleHidden +Applies to: no restrictions. + +Toggles whether hidden files are displayed. Hidden files are any +file/directory that starts with a "." + +------------------------------------------------------------------------------ + *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-q* +Default key: q +Map option: NERDTreeMapQuit +Applies to: no restrictions. + +Closes the NERDtree window. + +------------------------------------------------------------------------------ + *NERDTree-?* +Default key: ? +Map option: NERDTreeMapHelp +Applies to: no restrictions. + +Toggles whether the quickhelp is displayed. + +------------------------------------------------------------------------------ +2.3. The filesystem menu *NERDTreeFilesysMenu* + +The purpose of the filesystem menu is to allow you to perform basic filesystem +operations quickly from the NERD tree rather than the console. + +The filesystem menu can be accessed with 'm' mapping and has four supported +operations: > + 1. Adding nodes. + 2. Move nodes. + 3. Deleting nodes. + 3. Copying nodes. +< +1. Adding nodes: +To add a node move the cursor onto (or anywhere inside) the directory you wish +to create the new node inside. Select the 'add node' option from the +filesystem menu and type a filename. If the filename you type ends with a '/' +character then a directory will be created. Once the operation is completed, +the cursor is placed on the new node. + +2. Move nodes: +To move/rename a node, put the cursor on it and select the 'move' option from +the filesystem menu. Enter the new location for the node and it will be +moved. If the old file is open in a buffer, you will be asked if you wish to +delete that buffer. Once the operation is complete the cursor will be placed +on the renamed node. + +3. Deleting nodes: +To delete a node put the cursor on it and select the 'delete' option from the +filesystem menu. After confirmation the node will be deleted. If a file is +deleted but still exists as a buffer you will be given the option to delete +that buffer. + +4. Copying nodes: +To copy a node put the cursor on it and select the 'copy' option from the +filesystem menu. Enter the new location and you're done. Note: copying is +currently only supported for *nix operating systems. If someone knows a +one line copying command for windows that doesnt require user confirmation +then id be grateful if you'd email me. + +============================================================================== +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. + +|NERDTreeIgnore| Tells the NERD tree which files to ignore. + +|NERDTreeMouseMode| Tells the NERD tree how to handle mouse + clicks. + +|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. + +|NERDTreeSortOrder| Tell the NERD tree how to sort the nodes in + the tree. + +|NERDTreeSplitVertical| Tells the script whether the NERD tree should + be created by splitting the window vertically + or horizontally. + +|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: 1. + +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. + +Note to windows users: it is highly recommended that you have this option set +to either 1 or 2 or else the script wont function properly if you attempt to +open a NERD tree on a different drive to the one vim is currently in. + +Authors note: at work i have this option set to 1 because i have a giant ctags +file in the root dir of my project. This way i can initialise the NERD tree +with the root dir of my project and always have ctags available to me --- no +matter where i go with the NERD tree. + +------------------------------------------------------------------------------ + *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. + +------------------------------------------------------------------------------ + *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. + +------------------------------------------------------------------------------ + *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'. + +------------------------------------------------------------------------------ + *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 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 with the |NERDTree-H| mapping. +Use one of the follow lines to set this option: > + let NERDTreeShowHidden=0 + let NERDTreeShowHidden=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. Every 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. + +------------------------------------------------------------------------------ + *NERDTreeSplitVertical* +Values: 0 or 1. +Default: 1. + +This option, along with |NERDTreeWinPos|, is used to determine where the NERD +tree window appears. + +If it is set to 1 then the NERD tree window will appear on either the left or +right side of the screen (depending on the |NERDTreeWinPos| option). + +If it set to 0 then the NERD tree window will appear at the top of the screen. + +------------------------------------------------------------------------------ + *NERDTreeWinPos* +Values: 0 or 1. +Default: 1. + +This option works in conjunction with the |NERDTreeSplitVertical| option to +determine where NERD tree window is placed on the screen. + +If the option is set to 1 then the NERD tree will appear on the left or top of +the screen (depending on the value of |NERDTreeSplitVertical|). If set to 0, +the window will appear on the right or bottom of the screen. + +This option is makes it possible to use two different explorer type +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. + +============================================================================== + *NERDTreePublicFunctions* +5. Public functions ~ + +The script provides 2 public functions for your hacking pleasure. Their +signatures are: > + function! NERDTreeGetCurrentNode() + function! NERDTreeGetCurrentPath() +< +The first returns the node object that the cursor is currently on, while the +second returns the corresponding path object. + +This is probably a good time to mention that the script implements prototype +style OO. To see the functions that each class provides you can read look at +the code. + +Use the node objects to manipulate the structure of the tree. Use the path +objects to access the data the tree represents and to make changes to the +filesystem. + +============================================================================== +5. TODO list *NERDTreeTodo* + +Window manager integration? + +============================================================================== +6. The Author *NERDTreeAuthor* + +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 has an odd +love/hate relationship with computers (but monsters hate everything by nature +you know...) which can be awkward for him since he is a pro computer nerd for +a living. + +He can be reached at martin_grenfell at msn.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 ;) + +============================================================================== +7. Changelog *NERDTreeChangelog* + +2.7.1 + - Changed the keys for the filesystem menu to be mnemonic rather than + arbitrary integers + - Documented the copying functionality in the filesystem menu + +2.7.0 + - Bug fix: Now when you have the tree on the right and you open it with + multiple windows stacked, it will take up the full height of the vim + window. + - Now line numbers always turned off in the tree by default + - Implemented copying of nodes (via the filesystem menu) for *nix/macosx + - took the help doc out of the script and repackaged the whole thing as a + zip + +2.6.2 + - Now when you try to open a file node into a window that is modified, the + window is not split if the &hidden option is set. Thanks to Niels Aan + de Brugh for this suggestion. + +2.6.1 + - Fixed a major bug with the mapping. Thanks to Zhang Weiwu for + emailing me. + +2.6.0 + - Extended the behaviour of . Now if the cursor is on a file node + and you use the cursor will jump to its PARENTS next/previous + sibling. Go :help NERDTree-c-j and :help NERDTree-c-k for info. + - Extended the behaviour of the J/K mappings. Now if the cursor is on the + last child of a node and you push J/K it will jump down to the last child + of the next/prev of its parents siblings that is open and has children. + Go :help NERDTree-J and :help NERDTree-K for info. + - The goal of these changes is to make tree navigation faster. + - Reorganised the help page a bit. + - Removed the E mapping. + - bugfixes + +2.5.0 + - Added an option to enforce case sensitivity when sorting tree nodes. + Read :help NERDTreeCaseSensitiveSort for details. (thanks to Michael + Madsen for emailing me about this). Case sensitivity defaults to off. + - Made the script echo a "please wait" style message when opening large + directories. Thanks to AOYAMA Shotaro for this suggestion. + - Added 2 public functions that can be used to retrieve the treenode and + path that the cursor is on. Read :help NERDTreePublicFunctions for + details (thanks again to AOYAMA Shotaro for the idea :). + - added 2 new mappings for file nodes: "g" and "go". These are the + same as the "" and "o" maps except that the cursor stays in the + NERDTree. Note: these maps are slaved to the o and mappings, so if + eg you remap "" to "i" then the "g" map will also be changed + to "gi". + - Renamed many of the help tags to be simpler. + - Simplified the ascii "graphics" for the filesystem menu + - Fixed bugs. + - Probably created bugs. + - Refactoring. + +2.4.0 + - Added the P mapping to jump to the tree root. + - Added window centering functionality that can be triggered when doing + using any of the tree nav mappings. Essentially, if the cursor comes + within a certain distance of the top/bottom of the window then a zz is + done in the window. Two related options were added: NERDTreeAutoCenter + to turn this functionality on/off, and NERDTreeAutoCenterThreshold to + control how close the cursor has to be to the window edge to trigger the + centering. + +2.3.0 + - Tree navigation changes: + - Added J and K mappings to jump to last/first child of the current dir. + Options to customise these mappings have also been added. + - Remapped the jump to next/prev sibling commands to be and by + default. + These changes should hopefully make tree navigation mappings easier to + remember and use as the j and k keys are simply reused 3 times (twice + with modifier keys). + + - Made it so that, when any of the tree filters are toggled, the cursor + stays with the selected node (or goes to its parent/grandparent/... if + that node is no longer visible) + - Fixed an error in the doc for the mouse mode option. + - Made the quickhelp correctly display the current single/double click + mappings for opening nodes as specified by the NERDTreeMouseMode option. + - Fixed a bug where the script was spazzing after prompting you to delete + a modified buffer when using the filesystem menu. + - Refactoring +2.2.3 + - Refactored the :echo output from the script. + - Fixed some minor typos in the doc. + - Made some minor changes to the output of the 'Tree filtering mappings' + part of the quickhelp + +2.2.2 + - More bugfixes... doh. + +2.2.1 + - Bug fix that was causing an exception when closing the nerd tree. Thanks + to Tim carey-smith and Yu Jun for pointing this out. + +2.2.0 + - Now 'cursorline' is set in the NERD tree buffer by default. See :help + NERDTreeHighlightCursorline for how to disable it. + +2.1.2 + - Stopped the script from clobbering the 1,2,3 .. 9 registers. + - Made it "silent!"ly delete buffers when renaming/deleting file nodes. + - Minor correction to the doc + - Fixed a bug when refreshing that was occurring when the node you + refreshed had been deleted externally. + - Fixed a bug that was occurring when you open a file that is already open + and modified. + +2.1.1 + - Added a bit more info about the buffers you are prompted to delete when + renaming/deleting nodes from the filesystem menu that are already loaded + into buffers. + - Refactoring and bugfixes + +2.1.0 + - Finally removed the blank line that always appears at the top of the + NERDTree buffer + - Added NERDTreeMouseMode option. If set to 1, then a double click is + required to activate all nodes, if set to 2 then a single click will + activate directory nodes, if set to 3 then a single click will activate + all nodes. + - Now if you delete a file node and have it open in a buffer you are given + the option to delete that buffer as well. Similarly if you rename a file + you are given the option to delete any buffers containing the old file + (if any exist) + - When you rename or create a node, the cursor is now put on the new node, + this makes it easy immediately edit the new file. + - Fixed a bug with the ! mapping that was occurring on windows with paths + containing spaces. + - Made all the mappings customisable. See |NERD_tree-mappings| for + details. A side effect is that a lot of the "double mappings" have + disappeared. E.g 'o' is now the key that is used to activate a node, + is no longer mapped to the same. + - Made the script echo warnings in some places rather than standard echos + - Insane amounts of refactoring all over the place. + +2.0.0 + - Added two new NERDChristmasTree decorations. First person to spot them + and email me gets a free copy of the NERDTree. + - Made it so that when you jump around the tree (with the p, s and S + mappings) it is counted as a jump by vim. This means if you, eg, push + 'p' one too many times then you can go `` or ctrl-o. + - Added a new option called NERDTreeSortOrder which takes an array of + regexs and is used to determine the order that the treenodes are listed + in. Go :help NERDTreeSortOrder for details. + - Removed the NERDTreeSortDirs option because it is consumed by + NERDTreeSortOrder + - Added the 'i' mapping which is the same as but requires less + effort to reach. + - Added the ! mapping which is used to execute file in the tree (after it + prompts you for arguments etc) + + +============================================================================== +8. Credits *NERDTreeCredits* + +Thanks to Tim Carey-Smith for testing/using the NERD tree from the first +pre-beta version, for his many suggestions and for his constant stream of bug +complaints. + +Thanks to Vigil for trying it out before the first release :) and suggesting +that mappings to open files in new tabs should be implemented. + +Thanks to Nick Brettell for testing, fixing my spelling and suggesting i put a + .. (up a directory) +line in the gui. + +Thanks to Thomas Scott Urban - the author of the vtreeexplorer plugin - whose +gui code i borrowed from. + +Thanks to Terrance Cohen for pointing out a bug where the script was changing +vims CWD all over the show. + +Thanks to Yegappan Lakshmanan (author of Taglist and other orgasmically +wonderful plugins) for telling me how to fix a bug that was causing vim to go +into visual mode everytime you double clicked a node :) + +Thanks to Jason Mills for sending me a fix that allows windows paths to use +forward slashes as well as backward. + +Thanks to Michael Geddes (frogonwheels on #vim at freenode) for giving me some +tips about syntax highlighting when i was doing highlighting for the +quickhelp. + +Thanks to Yu Jun for emailing me about a bug that was occurring when closing +the tree. + +Thanks to Michael Madsen for emailing me about making case sensitivity +optional when sorting nodes. + +Thanks to AOYAMA Shotaro for suggesting that i echo a "please wait" message +when opening large directories. + +Thanks to Michael Madsen for requesting the NERDTreeCaseSensitiveSort option. + +Thanks to AOYAMA Shotaro for suggesting that a "please wait" style message be +echoed when opening large directories. Also, thanks for the suggestion of +having public functions in the script to access the internal data :D + +Thanks to Zhang Weiwu for emailing me about a bug with the the mapping +in 2.6.0 + +Thanks to Niels Aan de Brugh for the suggestion that the script now split the +window if you try to open a file in a window containing a modified buffer when +the &hidden option is set. diff --git a/.vim/doc/omnicppcomplete.txt b/.vim/doc/omnicppcomplete.txt new file mode 100644 index 0000000..a2a65f1 --- /dev/null +++ b/.vim/doc/omnicppcomplete.txt @@ -0,0 +1,1078 @@ +*omnicppcomplete.txt* Plugin for C/C++ omnicompletion +*omnicppcomplete* + +Author: Vissale NEANG (fromtonrouge AT gmail DOT com) +Last Change: 26 sept. 2007 + +OmniCppComplete version 0.41 + +For Vim version 7.0 and above + +============================================================================== + +1. Overview |omnicpp-overview| +2. Downloads |omnicpp-download| +3. Installation |omnicpp-installation| +4. Options |omnicpp-options| +5. Features |omnicpp-features| +6. Limitations |omnicpp-limitations| +7. FAQ & TIPS |omnicpp-faq| +8. History |omnicpp-history| +9. Thanks |omnicpp-thanks| + +============================================================================== +1. Overview~ + *omnicpp-overview* +The purpose of this script is to provide an 'omnifunc' function for C and C++ +language. In a C++ file, while in insert mode, you can use CTRL-X CTRL-O to: + + * Complete namespaces, classes, structs and unions + * Complete attribute members and return type of functions + * Complete the "this" pointer + * Complete an object after a cast (C and C++ cast) + * Complete typedefs and anonymous types + +You can set a "may complete" behaviour to start a completion automatically +after a '.', '->' or '::'. Please see |omnicpp-may-complete| for more details. + +The script needs an |Exuberant_ctags| database to work properly. + +============================================================================== +2. Downloads~ + *omnicpp-download* +You can download the latest release of the script from this url : + + http://www.vim.org/scripts/script.php?script_id=1520 + +You can download |Exuberant_ctags| from : + + http://ctags.sourceforge.net + +============================================================================== +3. Installation~ + *omnicpp-installation* +3.1. Script installation~ + +Unzip the downloaded file in your personal |vimfiles| directory (~/.vim under +unix or %HOMEPATH%\vimfiles under windows). The 'omnifunc' will be +automatically set for C and C++ files. + +You also have to enable plugins by adding these two lines in your|.vimrc|file: > + + set nocp + filetype plugin on +< +Please see |cp| and |filetype-plugin-on| sections for more details. + +3.1.1. Files~ + +After installation you should find these files : + + after\ftplugin\cpp.vim + after\ftplugin\c.vim + + autoload\omni\common\debug.vim + \utils.vim + + autoload\omni\cpp\complete.vim + \includes.vim + \items.vim + \maycomplete.vim + \namespaces.vim + \settings.vim + \tokenizer.vim + \utils.vim + + doc\omnicppcomplete.txt + +3.2. Building the Exuberant Ctags database~ + +To extract C/C++ symbols information, the script needs an |Exuberant_ctags| +database. + +You have to build your database with at least the following options: + --c++-kinds=+p : Adds prototypes in the database for C/C++ files. + --fields=+iaS : Adds inheritance (i), access (a) and function + signatures (S) information. + --extra=+q : Adds context to the tag name. Note: Without this + option, the script cannot get class members. + +Thus to build recursively a ctags database from the current directory, the +command looks like this: +> + ctags -R --c++-kinds=+p --fields=+iaS --extra=+q . +< +You can add a map in your |.vimrc| file, eg: > + + map :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q . +< +Or you can add these options in your ctags config file (~/.ctags under unix or +%HOMEPATH%\ctags.cnf under windows) and execute the command : > + + :!ctags -R . +< +If your project contains files of other languages you may add the following +options: + --languages=c++ : Builds only the tags for C++ files. + +If your project contains macros you may also use the -I option. + +Please read the ctags help or ctags man page for more details. + +3.3. Setting the 'tags' option~ + +The default value of the option 'tags' is "./tags,tags" ("./tags,./TAGS,tags,TAGS" +when |+emacs_tags| is enabled), if you build your tag database with the cmd above, +you normally don't have to change this setting (The cmd used above generates a +file with the name "tags"). In this case your current working directory must be +the directory where the tags file reside. + +Note: When |+emacs_tags| is enabled, the script may display members twice, it's + recommended to set tags to "./tags,tags' or "./TAGS,TAGS". + +If your tags file is not named "tags" you have to add it in the 'tags' +option eg: > + + set tags+=/usr/tagsdir/mytagfile +< +You can ensure that the 'tags' option is set properly by executing the following +command: > + + :tselect MyClass +< +Where MyClass is a class of your project. This command should display all +possible tags for the type MyClass. + +3.4. Simple test~ + +Now you can do a simple test. Edit a C++ file and write the simplest case : > + + MyClass myObject; + myObject. +< +You should see class members of MyClass. + +============================================================================== +4. Options~ + *omnicpp-options* + +You can change completion behaviour by setting script options in your |.vimrc| +configuration file. + +4.1. Global scope search toggle~ + *OmniCpp_GlobalScopeSearch* + +You can enable/disable the global scope search by setting the +OmniCpp_GlobalScopeSearch option. + +Possible values are : + 0 = disabled + 1 = enabled + [default=1] > + + let OmniCpp_GlobalScopeSearch = 1 +< +4.2. Namespace search method~ + *OmniCpp_NamespaceSearch* + +You can change the 'using namespace' search behaviour by setting the +OmniCpp_NamespaceSearch option. + +Possible values are : + 0 = namespaces disabled + 1 = search namespaces in the current buffer + 2 = search namespaces in the current buffer and in included files + [default=1] > + + let OmniCpp_NamespaceSearch = 1 +< +When OmniCpp_NamespaceSearch is 2, "using namespace" declarations are parsed +in the current buffer and also in included files. To find included files, the +script use the vim env 'path', so you have to set it properly. + +Note: included files are searched with lvimgrep, thus the location list of the +current window is changed. + +Note: When the 'filetype' is "c", namespace search is always disabled even if +OmniCpp_NamespaceSearch != 0 + +4.3. Class scope completion mode~ + *OmniCpp_DisplayMode* + +When you are completing a class scope (eg: MyClass::), depending on +the current scope, you may see sometimes static, public, protected or private +members and sometimes you may see all members. By default the choice is done +automatically by the script but you can override it with the +OmniCpp_DisplayMode option. + +Note: This option can be use when you have friend classes in your project (the +script does not support friend classes). + +Possible values are : + 0 = auto + 1 = always show all members + [default=0] > + + let OmniCpp_DisplayMode = 0 +< +4.4. Show scope in abbreviation~ + *OmniCpp_ShowScopeInAbbr* + +By default, in the |omnicpp-popup| menu, you will see the scope of a match in +the last column. You can remove this column and add the scope at the beginning +of match abbreviation. +eg: + +OmniCpp_ShowScopeInAbbr = 0 + +-------------------------------------+ + |method1( f + MyNamespace::MyClass| + |_member1 m + MyNamespace::MyClass| + |_member2 m # MyNamespace::MyClass| + |_member3 m - MyNamespace::MyClass| + +-------------------------------------+ + +OmniCpp_ShowScopeInAbbr = 1 + +-------------------------------------+ + |MyNamespace::MyClass::method1( f + | + |MyNamespace::MyClass::_member1 m + | + |MyNamespace::MyClass::_member2 m # | + |MyNamespace::MyClass::_member3 m - | + +-------------------------------------+ + +Possible values are : + 0 = don't show scope in abbreviation + 1 = show scope in abbreviation and remove the last column + [default=0] > + + let OmniCpp_ShowScopeInAbbr = 0 +< +4.5. Show prototype in abbreviation~ + *OmniCpp_ShowPrototypeInAbbr* + +This option allows to display the prototype of a function in the abbreviation +part of the popup menu. + +Possible values are: + 0 = don't display prototype in abbreviation + 1 = display prototype in abbreviation + [default=0] > + + let OmniCpp_ShowPrototypeInAbbr = 0 +< +4.6. Show access~ + *OmniCpp_ShowAccess* + +This option allows to show/hide the access information ('+', '#', '-') in the +popup menu. + +Possible values are: + 0 = hide access + 1 = show access + [default=1] > + + let OmniCpp_ShowAccess = 1 + +4.7. Default using namespace list~ + *OmniCpp_DefaultNamespaces* + +When |OmniCpp_NamespaceSearch| is not 0, the script will parse using namespace +declarations in the current buffer and maybe in included files. +You can specify manually a default namespace list if you want with the +OmniCpp_DefaultNamespaces option. Each item in the list is a namespace name. +eg: If you have + + let OmniCpp_DefaultNamespaces = ["std", "MyNamespace"] + + It will be the same as inserting this declarations at the top of the + current buffer : + + using namespace std; + using namespace MyNamespace; + +This option can be use if you don't want to parse using namespace declarations +in included files and want to add namespaces that are always used in your +project. + +Possible values are : + List of String + [default=[]] > + + let OmniCpp_DefaultNamespaces = [] +< +4.8. May complete behaviour~ + *omnicpp-may-complete* + +This feature allows you to run automatically a completion after a '.', '->' +or '::'. By default, the "may complete" feature is set automatically for '.' +and '->'. The reason to not set this feature for the scope operator '::' is +sometimes you don't want to complete a namespace that contains many members. + +To enable/disable the "may complete" behaviour for dot, arrow and scope +operator, you can change the option OmniCpp_MayCompleteDot, +OmniCpp_MayCompleteArrow and OmniCpp_MayCompleteScope respectively. + + *OmniCpp_MayCompleteDot* +Possible values are : + 0 = May complete disabled for dot + 1 = May complete enabled for dot + [default=1] > + + let OmniCpp_MayCompleteDot = 1 +< + *OmniCpp_MayCompleteArrow* +Possible values are : + 0 = May complete disabled for arrow + 1 = May complete enabled for arrow + [default=1] > + + let OmniCpp_MayCompleteArrow = 1 +< + *OmniCpp_MayCompleteScope* +Possible values are : + 0 = May complete disabled for scope + 1 = May complete enabled for scope + [default=0] > + + let OmniCpp_MayCompleteScope = 0 +< + +Note: You can obviously continue to use + +4.9. Select/Don't select first popup item~ + *OmniCpp_SelectFirstItem* + +Note: This option is only used when 'completeopt' does not contain "longest". + +When 'completeopt' does not contain "longest", Vim automatically select the +first entry of the popup menu. You can change this behaviour with the +OmniCpp_SelectFirstItem option. + +Possible values are: + 0 = don't select first popup item + 1 = select first popup item (inserting it to the text) + 2 = select first popup item (without inserting it to the text) + [default=0] > + + let OmniCpp_SelectFirstItem = 0 + +4.10 Use local search function for variable definitions~ + *OmniCpp_LocalSearchDecl* + +The internal search function for variable definitions of vim requires that the +enclosing braces of the function are located in the first column. You can +change this behaviour with the OmniCpp_LocalSearchDecl option. The local +version works irrespective the position of braces. + +Possible values are: + 0 = use standard vim search function + 1 = use local search function + [default=0] > + +============================================================================== +5. Features~ + *omnicpp-features* +5.1. Popup menu~ + *omnicpp-popup* +Popup menu format: + +-------------------------------------+ + |method1( f + MyNamespace::MyClass| + |_member1 m + MyNamespace::MyClass| + |_member2 m # MyNamespace::MyClass| + |_member3 m - MyNamespace::MyClass| + +-------------------------------------+ + ^ ^ ^ ^ + (1) (2)(3) (4) + +(1) name of the symbol, when a match ends with '(' it's a function. + +(2) kind of the symbol, possible kinds are : + * c = classes + * d = macro definitions + * e = enumerators (values inside an enumeration) + * f = function definitions + * g = enumeration names + * m = class, struct, and union members + * n = namespaces + * p = function prototypes + * s = structure names + * t = typedefs + * u = union names + * v = variable definitions + +(3) access, possible values are : + * + = public + * # = protected + * - = private +Note: enumerators have no access information + +(4) scope where the symbol is defined. +Note: If the scope is empty it's a global symbol +Note: anonymous scope may end with __anon[number] +eg: If you have an anonymous enum in MyNamespace::MyClass : > + + namespace MyNamespace + { + class MyClass + { + private: + + enum + { + E_ENUM0, + E_ENUM1, + E_ENUM2 + }; + }; + } +< + +You should see : + + +----------------------------------------------+ + |E_ENUM0 e MyNamespace::MyClass::__anon1| + |E_ENUM1 e MyNamespace::MyClass::__anon1| + |E_ENUM2 e MyNamespace::MyClass::__anon1| + +----------------------------------------------+ + ^ + __anon[number] + +5.2. Global scope completion~ + +The global scope completion allows you to complete global symbols for the base +you are currently typing. The base can start with '::' or not. +Note: Global scope completion only works with a non empty base, if you run a +completion just after a '::' the completion will fail. The reason is that if +there is no base to complete the script will try to display all the tags in +the database. For small project it could be not a problem but for others you +may wait 5 minutes or more for a result. + +eg1 : > + + pthread_cr => pthread_create +< +Where pthread_create is a global function. +eg2: > + ::globa => ::global_func( + +----------------+ + |global_func( f| + |global_var1 v| + |global_var2 v| + +----------------+ +< +Where global_var1, global_var2 and global_func are global symbols +eg3: > + :: => [NO MATCH] +< +No match because a global completion from an empty base is not allowed. + +5.3. Namespace scope completion~ + +You can complete namespace members after a 'MyNamespace::'. Contrary to global +scope completion you can run a completion from an empty base. +Possible members are: + * Namespaces + * Classes + * Structs + * Unions + * Enums + * Functions + * Variables + * Typedefs + +eg: > + MyNamespace:: + +--------------------------------+ + |E_ENUM0 e MyNamespace| + |E_ENUM1 e MyNamespace| + |E_ENUM2 e MyNamespace| + |MyClass c MyNamespace| + |MyEnum g MyNamespace| + |MyStruct s MyNamespace| + |MyUnion u MyNamespace| + |SubNamespace n MyNamespace| + |doSomething( f MyNamespace| + |myVar v MyNamespace| + |something_t t MyNamespace| + +--------------------------------+ + +5.4. Class scope completion~ + +You can complete class members after a 'MyClass::'. Contrary to global scope +completion you can run a completion from an empty base. +By default, there is two behaviours for class scope completion. + + a) Completion of a base class of the current class scope + + When you are completing a base class of the current class scope, you + will see all members of this class in the popup menu. + eg: > + + class A + { + public: + enum + { + E_ENUM0, + E_ENUM1, + E_ENUM2, + }; + + void func1(); + static int _staticMember; + + private: + int _member; + }; + + class B : public A + { + public: + void doSomething(); + }; + + + void MyClassB::doSomething() + { + MyClassA:: + +---------------------------+ + |E_ENUM0 e MyClassA| + |E_ENUM1 e MyClassA| + |E_ENUM2 e MyClassA| + |func1( f + MyClassA| + |_member m - MyClassA| + |_staticMember m + MyClassA| + +---------------------------+ + } +< + + b) Completion of a non base class of the current class scope + + When you are completing a class that is not a base class of the + current class you will see only enumerators and static members. + eg: > + + class C + { + public: + void doSomething(); + }; + + void MyClassC::doSomething() + { + MyClassA:: + +---------------------------+ + |E_ENUM0 e MyClassA| + |E_ENUM1 e MyClassA| + |E_ENUM2 e MyClassA| + |_staticMember m + MyClassA| + +---------------------------+ + } +< +You can override the default behaviour by setting the +|OmniCpp_DisplayMode| option. + +5.5. Current scope completion~ + +When you start a completion from an empty instruction you are in "Current +scope completion" mode. You will see possible members of each context in +the context stack. +eg: > + void MyClass::doSomething() + { + using namespace MyNamespace; + using namespace SubNamespace; + + // You will see members of each context in the context stack + // 1) MyClass members + // 2) MyNamespace::SubNamespace members + // 3) MyNamespace members + + + +------------------------------------------+ + |_member1 m + MyClass | + |_member2 m # MyClass | + |func1( f MyNamespace::SubNamespace| + |var v MyNamespace::SubNamespace| + |func1( f MyNamespace | + |var v MyNamespace | + +------------------------------------------+ + } +< + +5.6. Class, Struct and Union members completion~ + +You can complete members of class, struct and union instances after a '->' or +'.'. +eg: > + MyClass myObject; + myObject. + +-----------------------+ + |_member1 m + MyClass | + |_member2 m # MyClass | + +-----------------------+ +< + +5.7. Attribute members and returned type completion~ + +You can complete a class member or a return type of a function. +eg: > + MyClass myObject; + + // Completion of the member _member1 + myObject._member1-> + +------------------------+ + |get( m + AnotherClass1| + +------------------------+ + + // Completion of the return type of the function get() + myObject._member1->get()-> + +--------------------------+ + |_member1 m + AnotherClass2| + |_member2 m # AnotherClass2| + |_member3 m - AnotherClass2| + +--------------------------+ + +5.8. Anonymous type completion~ + +Note: To use this feature you need at least|Exuberant_ctags| version 5.6 + +You can complete an anonymous type like this : > + struct + { + int a; + int b; + int c; + }globalVar; + + void func() + { + globalVar. + +---------------+ + |a m + __anon1| + |b m + __anon1| + |c m + __anon1| + +---------------+ + } +< +Where globalVar is a global variable of an anonymous type + +5.9. Typedef completion~ + +You can complete a typedef. The typedef is resolved recursively, thus typedef +of typedef of... may not be a problem. + +You can also complete a typedef of an anonymous type, eg : > + typedef struct + { + int a; + int b; + int c; + }something_t; + + something_t globalVar; + + void func() + { + globalVar. + +---------------+ + |a m + __anon1| + |b m + __anon1| + |c m + __anon1| + +---------------+ + } +< +Where globalVar is a global variable of typedef of an anonymous type. + +5.10. Completion of the "this" pointer~ + +You can complete the "this" pointer. +eg: > + this-> + +-----------------------+ + |_member1 m + MyClass | + |_member2 m # MyClass | + +-----------------------+ + + (*this). + +-----------------------+ + |_member1 m + MyClass | + |_member2 m # MyClass | + +-----------------------+ +< + +5.11. Completion after a cast~ + +You can complete an object after a C or C++ cast. +eg: > + // C cast style + ((AnotherStruct*)pStruct)-> + + // C++ cast style + static_cast(pStruct)-> +< + +5.12. Preview window~ + +If the 'completeopt' option contains the setting "preview" (this is the +default value), you will see a preview window during the completion. +This window shows useful information like function signature, filename where +the symbol is define etc... + +The preview window contains tag information, the list below is non exhaustive. + + * name : name of the tag + * cmd : regexp or line number that helps to find the tag + * signature : signature for prototypes and functions + * kind : kind of the tag (eg: namespace, class etc...) + * access : access information (eg: public, protected, private) + * inherits : list of base classes + * filename : filename where the tag is define + +5.13. Code tokenization~ + +When you start a completion, the current instruction is tokenized ignoring +spaces, tabs, carriage returns and comments. Thus you can complete a symbol +even if the current instruction is on multiple lines, has comments between +words etc... : +eg: this case is unrealistic but it's just for illustration > + + myObject [ 0 ]/* Why is there a comment here ?*/ + ->_member + -> +< + +============================================================================== +6. Limitations~ + *omnicpp-limitations* +Some C++ features are not supported by the script, some implemented features +may not work properly in some conditions. They are multiple reasons like a +lack of information in the database, performance issues and so on... + +6.1. Attribute members and returned type completion~ + +To work properly, the completion of attribute members and returned type of +functions depends on how you write your code in the class declaration. +Because the tags database does not contain information like return type or +type of a member, the script use the cmd information of the tag to determine +the type of an attribute member or the return type of a function. + +Thus, because the cmd is a regular expression (or line number for #define) if +you write your code like this : > + + class MyClass + { + public: + + MyOtherClass + _member; + }; +< +The type of _member will not be recognized, because the cmd will be +/^ _member;$/ and does not contain the type MyOtherClass. +The correct case should be : > + + class MyClass + { + public: + + MyOtherClass _member; + }; +< +It's the same problem for return type of function : > + + class MyClass + { + public: + + MyOtherClass + getOtherClass(); + }; +< +Here the cmd will be /^ getOtherClass();$/ and the script won't find the +return type. +The correct case should be : > + class MyClass + { + public: + + MyOtherClass getOtherClass(); + }; +< + +6.2. Static members~ + +It's the same problem as above, tags database does not contain information +about static members. The only fast way to get this information is to use the +cmd. + +6.3. Typedef~ + +It's the same problem as above, tags database does not contain information +about the type of a typedef. The script use the cmd information to resolve the +typedef. + +6.4. Restricted inheritance access~ + +Tags database contains inheritance information but unfortunately inheritance +access are not available. We could use the cmd but we often find code +indentation like this : > + + class A : + public B, + protected C, + private D + { + }; +< +Here the cmd will be /^class A :$/, we can't extract inheritance access. + +6.5. Using namespace parsing~ + +When you start a completion, using namespace declarations are parsed from the +cursor position to the first scope to detect local using namespace +declarations. After that, global using namespace declarations are parsed in the +file and included files. + +There is a limitation for global using namespace detection, for performance +issues only using namespace that starts a line will be detected. + +6.6. Friend classes~ + +Tags database does not contain information about friend classes. The script +does not support friend classes. + +6.7. Templates~ + +At the moment, |Exuberant_ctags| does not provide additional information for +templates. That's why the script does not handle templates. + +============================================================================== +7. FAQ & TIPS~ + *omnicpp-faq* + +* How to complete STL objects ? + If you have some troubles to generate a good ctags database for STL you + can try this solution : + + 1) Download SGI's STL from SGI's site + (http://www.sgi.com/tech/stl/download.html) + 2) Replace all __STL_BEGIN_NAMESPACE by "namespace std {" and + __STL_END_NAMESPACE by "}" from header and source files. (with Vim, + or with tar and sed or another tool) + 3) Run ctags and put the generated tags file in a directory eg: + ~/MyTags/stl.tags + 4) set tags+=~/MyTags/stl.tags + + The main problem is that you can't tell to ctags that + __STL_BEGIN_NAMESPACE = "namespace std {" even with the option -I. + That's why you need the step 2). + + Here is another solution if you have STL sources using _GLIBCXX_STD macro + (Tip by Nicola Bonelli) : > + + let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"] +< +* How to close automatically the preview window after a completion ? + (Tip by Kamil Renczewski) + + You can add to your |vimrc| the following lines : > + + autocmd CursorMovedI * if pumvisible() == 0|pclose|endif + autocmd InsertLeave * if pumvisible() == 0|pclose|endif +< +============================================================================== +8. History~ + *omnicpp-history* +Version O.41 + - It's recommended to update ctags to version 5.7 or higher + - The plugin is now activated for C files + - New value for OmniCpp_SelectFirstItem when the option is equal to + 2 the first item is selected without inserting it to + the text (patch from Marek Olszewski) + - Bug when completing union members fixed with ctags 5.7 + (reported by Willem-Jan de Hoog) + - New option OmniCpp_LocalSearchDecl (patch from Roland Kuck) + - Bug when tags=something,,somethingelse (reported by Tobias Pflug) + - Bug with nested structure (reported by Mikhail Daen) + - Bug where the script fails to detect the type of a variable when + the ignorecase option is on (reported by Alexey Vakhov) + - Error message when trying to use completion on a not yet saved + Vim buffer (reported by Neil Bird) + - Error message when trying to use completion on an file opened from + a tselect command (reported by Henrique Andrade) + +Version 0.4 + - The script is renamed to OmniCppComplete according to the library + script directory structure. + - OmniCpp_ClassScopeCompletionMethod renamed to OmniCpp_DisplayMode + - Fixed a bug where the quickfix list is modified after a completion. + - OmniCpp_ShowPrototypeInAbbr option added. It allows to show the + function signature in the abbreviation. + - OmniCpp_ShowAccess option added. It allows to hide the access + information in the popup menu. + - The tags database format must be a ctags 5.6 database if you want to + complete anonymous types. + - Fixed current scope detection not working properly in destructors. + - Don't show protected and private members according to the current scope. + - Overloaded functions are now filtered properly. + - New cache system using less memory. + - The class scope of a method is now resolved properly with "using + namespace" declarations. + - OmniCpp_SelectFirstItem option added. It allows to not select the first + item in the popup menu when 'completeopt' does not contain "longest". + - Fixed the bug where a "random" item in the popup menu is selected + by default when 'completeopt' does not contain "longest" option. + - The script is now split in library scripts. + - Cache added for 'using namespace' search in included files + - Default value for OmniCpp_NamespaceSearch is now 1 (search only in the + current buffer). + - Namespace search automatically disabled for C files even if + OmniCpp_NamespaceSearch != 0. + - To avoid linear search in tags files, the ignorecase option is now + disabled when getting tags datas (the user setting is restored after). + - Fixed a bug where friend functions may crash the script and also crash vim. + +Version 0.32 + - Optimizations in search members methods. + - 'May complete' behaviour is now set to default for dot '.' and arrow + '->' (mappings are set in after/ftplugin/cpp.vim) + - Fixed the option CppOmni_ShowScopeInAbbr not detected after the first + completion. + - Exceptions catched from taglist() when a tag file is corrupted. + - Fixed a bug where enumerators in global scope didn't appear in the + popup menu. + +Version 0.31 + WARNING: For this release and future releases you have to build your tags + database with this cmd : + "ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ." + Please read installation instructions in the documentation for details + + - May complete added, please see installation notes for details. + - Fixed a bug where the completion works while in a comment or in a string. + +Version 0.3 + WARNING: For this release and future releases you have to build your tags + database with this cmd : + "ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ." + Please read installation instructions in the documentation for details + + - Documentation added. + - Fixed a bug where typedefs were not correctly resolved in namespaces + in some cases. + - Fixed a bug where the type can not be detected when we have a decl + like this: class A {}globalVar; + - Fixed a bug in type detection where searchdecl() (gd) find + incorrect declaration instruction. + - Global scope completion now only works with non-empty base. + - Using namespace list is now parsed in the current buffer and in + included files. + - Fixed a bug where the completion fails in some cases when the user + sets the ignorecase to on + - Preview window information added + - Some improvements in type detection, the type can be properly detected + with a declaration like this: + 'Class1 *class1A = NULL, **class1B = NULL, class1C[9], class1D[1] = {};' + - Fixed a bug where parent scopes were not displayed in the popup menu + in the current scope completion mode. + - Fixed a bug where an error message was displayed when the last + instruction was not finished. + - Fixed a bug where the completion fails if a punctuator or operator was + immediately after the cursor. + - The script can now detect parent contexts at the cursor position + thanks to 'using namespace' declarations. + It can also detect ambiguous namespaces. They are not included in + the context list. + - Fixed a bug where the current scope is not properly detected when + a file starts with a comment + - Fixed a bug where the type is not detected when we have myObject[0] + - Removed the system() call in SearchMembers(), no more calls to the + ctags binary. The user have to build correctly his database with the cmd: + "ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ." + - File time cache removed, the user have to rebuild his data base after a + modification. + +Version 0.22 + - Completion of unnamed type (eg: You can complete g_Var defined like + this 'struct {int a; int b;}g_Var;'). It also works for a typedef of + an unnamed type (eg: 'typedef struct {int a; int b;}t_mytype; t_mytype + g_Var;'). + - Tag file's time cache added, if a tag file has changed the global + scope result cache is cleared. + - Fixed a bug where the tokenization process enter in an infinite loop + when a file starts with '/*'. + +Version 0.21 + - Improvements on the global scope completion. + The user can now see the progression of the search and complete + matches are stored in a cache for optimization. The cache is cleared + when the tag env is modified. + - Within a class scope when the user complete an empty word, the popup + menu displays the members of the class then members of the global + scope. + - Fixed a bug where a current scope completion failed after a punctuator + or operator (eg: after a '=' or '!='). + +Version 0.2 + - Improvements in type detection (eg: when a variable is declared in a + parameter list, a catch clause, etc...) + - Code tokenization => ignoring spaces, tabs, carriage returns and comments + You can complete a code even if the instruction has bad + indentation, spaces or carriage returns between words + - Completion of class members added + - Detection of the current scope at the cursor position. + If you run a completion from en empty line, members of the current + scope are displayed. It works on the global namespace and the current + class scope (but there is not the combination of the 2 for the moment) + - Basic completion on the global namespace (very slow) + - Completion of returned type added + - this pointer completion added + - Completion after a cast added (C and C++ cast) + - Fixed a bug where the matches of the complete menu are not filtered + according to what the user typed + - Change the output of the popup menu. The type of the member + (function, member, enum etc...) is now display as a single letter. + The access information is display like this : '+' for a public member + '#' for a protected member and '-' for a private member. + The last information is the class, namespace or enum where the member is define. + +Version 0.12: + - Complete check added to the search process, you can now cancel + the search during a complete search. + +Version 0.1: + - First release + +============================================================================== +9. Thanks~ + *omnicpp-thanks* + * For advices, bug report, documentation, help, ideas : + Alexey Vakhov (bug report) + Arthur Axel "fREW" Schmidt (documentation) + Dennis Lubert (bug report) + Henrique Andrade (bug report) + Kamil Renczewski (tips) + Marek Olszewski (patch) + Markus Trenkwalder (bug report) + Martin Stubenschrott (bug report) + Mikhail Daen (bug report) + Neil Bird (bug report) + Nicola Bonelli (tips) + Robert Webb (bug report) + Roland Kuck (patch) + Tobias Pflug (bug report) + Willem-Jan de Hoog (bug report) + Yegappan Lakshmanan (advices) + + + * Darren Hiebert for Exuberant Ctags + + * All Vim devs for Vim + + * Bram Moolenaar for Vim + + * You for using this script :) + +============================================================================== + + vim:tw=78:fo=tcq2:isk=!-~,^*,^\|,^\":ts=8:ft=help:norl: diff --git a/.vim/doc/project.txt b/.vim/doc/project.txt new file mode 100644 index 0000000..8f85c23 --- /dev/null +++ b/.vim/doc/project.txt @@ -0,0 +1,710 @@ +*project.txt* Plugin for managing multiple projects with multiple sources + For Vim version 6.x and Vim version 7.x. + Last Change: Fri 13 Oct 2006 10:20:13 AM EDT + + + By Aric Blumer + aricvim email-at-sign charter.net + + *project* *project-plugin* + Contents: + + Commands...................|project-invoking| + Inheritance.............|project-inheritance| + Mappings...................|project-mappings| + Adding Mappings.....|project-adding-mappings| + Settings...................|project-settings| + Example File................|project-example| + Tips...........................|project-tips| + + +You can use this plugin's basic functionality to set up a list of +frequently-accessed files for easy navigation. The list of files will be +displayed in a window on the left side of the Vim window, and you can press + or double-click on filenames in the list to open the files. I find +this easier to use than having to navigate a directory hierarchy with the +|file-explorer|. + +You can also instruct the Plugin to change to a directory and to run Vim +scripts when you select a file. These scripts can, for example, modify the +environment to include compilers in $PATH. This makes it very easy to use +quickfix with multiple projects that use different environments. + +Other features include: + o Loading/Unloading all the files in a Project (\l, \L, \w, and \W) + o Grepping all the files in a Project (\g and \G) + o Running a user-specified script on a file (can be used to launch an + external program on the file) (\1 through \9) + o Running a user-specified script on all the files in a Project + (\f1-\f9 and \F1-\F9) + o High degree of user-configurability + o Also works with |netrw| using the XXXX://... notation where XXXX is + ftp, rcp, scp, or http. + +All of this is specified within a simple text file and a few global variables +in your vimrc file. + +You must set 'nocompatible' in your |vimrc| file to use this plugin. You can +stop the plugin from being loaded by setting the "loaded_project" variable: > + :let loaded_project = 1 + + +============================================================================== +COMMANDS *project-invoking* + +You can use the plugin by placing it in your plugin directory (e.g., +~/.vim/plugin). See |add-global-plugin|. When you start vim the next time, you +then enter the command > + :Project +or > + :Project {file} + +If you do not specify the filename, $HOME/.vimprojects is used. + +To have Vim come up with the Project Window enabled automatically (say, from a +GUI launcher), run Vim like this: [g]vim +Project + +Note that you can invoke :Project on only one file at a time. If you wish to +change the Project File, do a :bwipe in the Project Buffer, then re-invoke the +Plugin as described above. + +Several Projects can be kept and displayed in the same file, each in a fold +delimited by { and } (see |fold.txt|). There can be any number of nested +folds to provide you with a Project hierarchy. Any line without a { or a } in +the file is considered to be a filename. Blank lines are ignored, and any +text after a # is ignored. + +Because the plugin uses standard Vim folds, you can use any of the +|fold-commands|. You can double-click on the first line of a fold to open and +close it. You can select a file to open by putting the cursor on its name and +pressing or by double-clicking on it. The plugin will create a new +window to the right or use the |CTRL-W_p| equivalent if it exists. + + *project-syntax* +Each Project Entry has this form: + +project_entry ::= + ={projpath} [{options}] { + [ filename ] + [ project_entry ] + } + +{options} is one or more of the following (on the same line): + CD={path} + in={filename} + out={filename} + filter="{pat}" + flags={flag} + +Note that a project_entry can reside within a project_entry. This allows you +to set up a hierarchy within your Project. + +The will be displayed in the foldtext and cannot contain "=". +There can be no space character directly on either side of the =. + +The {projpath} is the path in which the files listed in the Project's fold +will be found, and it may contain environment variables. If the path is a +relative path, then the plugin constructs the whole path from the Project's +parent, grandparent, etc., all the way up the hierarchy. An outermost +project_entry must have an absolute path. See the |project-inheritance| +example below. {projpath} may contain spaces, but they must be escaped like +normal Vim escapes. Here are two examples of the same directory: +> + Example=/my/directory/with\ spaces { + } + Example="/my/directory/with spaces" { + } + +I recommend this for Windows®: > + + Example="c:\My Documents" { + } + +But Vim is smart enough to do this, too: > + + Example=c:\My\ Documents { + } + +CD= provides the directory that Vim will change to when you select a file in +that fold (using |:cd|). This allows you, for example, to enter |:make| to use +the local Makefile. A CD=. means that Vim will make {projpath} or its +inherited equivalent the current working directory. When CD is omitted, the +directory is not changed. There can be no space on either side of the =. The +value of CD can also be a relative path from a parent's CD. See the +|project-inheritance| example below. This directive is ignored for |netrw| +projects. Spaces are allowed in the path as for {projpath}. + +in= and out= provide the means to run arbitrary Vim scripts whenever you enter +or leave a file's buffer (see the |BufEnter| and |BufLeave| autocommand +events). The idea is to have a Vim script that sets up or tears down the +environment for the Project like this: + +in.vim: > + let $PROJECT_HOME='~/my_project' + " Put the compiler in $PATH + if $PATH !~ '/path/to/my/compiler' + let $PATH=$PATH.':/path/to/my/compiler' + endif + +out.vim: > + " Remove compiler from $PATH + if $PATH =~ '/path/to/my/compiler' + let $PATH=substitute($PATH, ':/path/to/my/compiler', '', 'g') + endif + +Then you can use :make with the proper environment depending on what file you +are currently editing. If the path to the script is relative, then it is +relative from {projpath}. These directives are inherited by Subprojects +unless the Subproject specifies its own. For use with |netrw| projects, the +paths specified for in= and out= must be absolute and local. + +filter= specifies a |glob()| file pattern. It is used to regenerate the list +of files in a Project fold when using the \r (r) map in the +Project Window. The filter value must be in quotes because it can contain +multiple file patterns. If filter is omitted, then the * pattern is used. +There can be no space on either side of the =. A Subproject will inherit the +filter of its parent unless it specifies its own filter. + +flags= provides the means to enable/disable features for a particular fold. +The general mnemonic scheme is for lower case to turn something off and upper +case to turn something on. {flag} can contain any of the following +characters: + + flag Description ~ + + l Turn off recursion for this fold for \L. Subfolds are also + blocked from the recursion. + + r Turn off refresh. When present, do not refresh this fold when + \r or \R is used. This does not affect subfold recursion. + + S Turn on sorting for refresh and create. + + s Turn off sorting for refresh and create. + + T Turn on top gravity. Forces folds to the top of the current + fold when refreshing. It has the same affect as the 'T' flag + in g:proj_flags, but controls the feature on a per-fold basis. + + t Turn off top gravity. Forces folds to the bottom of the + current fold when refreshing. + + w Turn off recursion for this fold for \W. Subfolds are also + blocked from the recursion. + + +Flags are not inherited by Subprojects. + +Any text outside a fold is ignored. + + +============================================================================== +INHERITANCE *project-inheritance* + +It's best to show inheritance by comparing these two Project Files: +> + Parent=~/my_project CD=. filter="Make* *.mk" flags=r { + Child1=c_code { + } + Child2=include CD=. filter="*.h" { + } + } + +Child1's path is "~/my_project/c_code" because ~/my_project is inherited. It +also inherits the CD from Parent. Since Parent has CD=., the Parent's cwd is +"~/my_project". Child1 therefore inherits a CD of "~/my_project". Finally, +Child1 inherits the filter from Parent. The flags are not inherited. + +Child2 only inherits the "~/my_project" from Parent. + +Thus, the example above is exactly equivalent to this: +> + Parent=~/my_project CD=. filter="Make* *.mk" flags=r { + Child1=~/my_project/c_code CD=~/my_project filter="Make* *.mk" { + } + Child2=~/my_project/include CD=~/my_project/include filter="*.h" { + } + } + +(For a real Project, Child1 would not want to inherit its parent's filter, but +this example shows the concept.) You can always enter \i to display what the +cursor's project inherits. + + +============================================================================== +MAPPINGS *project-mappings* + +Map Action ~ + +\r Refreshes the Project fold that the cursor is in by placing in the + fold all the files that match the filter. The Project is refreshed + using an indent of one space for every foldlevel in the hierarchy. + + You may place a "# pragma keep" (without the quotes) at the end of a + line, and the file entry on that line will not be removed when you + refresh. This is useful, for example, when you have . as an entry so + you can easily browse the directory. + + Note that this mapping is actually r, and the default of + || is \. + + This does not work for Projects using |netrw|. + +\R Executes \r recursively in the current fold and all folds below. + This does not work for Projects using |netrw|. + +\c Creates a Project fold entry. It asks for the description, the path + to the files, the CD parameter, and the filename |glob()| pattern. + From this information, it will create the Project Entry below the + cursor. + + This does not work for Projects using |netrw|. + +\C Creates a Project fold entry like \c, but recursively includes all the + subdirectories. + + + Select a file to open in the |CTRL-W_p| window or in a new window. If + the cursor is on a fold, open or close it. + + +\s + Same as but horizontally split the target window. + s is provided for those terminals that don't recognize + . + +\S + Load all files in a project by doing horizontal splits. + + +\o + Same as but ensure that the opened file is the only other + window. o is provided for those terminals that don't + recognize . + + +\v + Same as but only display the file--the cursor stays in the + Project Window. + +<2-LeftMouse> + (Double-click) If on a closed fold, open it. If on an open fold + boundary, close it. If on a filename, open the file in the |CTRL-W_p| + window or in a new window. + + + Same as . + + + Same as . + + + Increase the width of the Project Window by g:proj_window_increment or + toggle between a width of + g:proj_window_width + g:proj_window_increment + and + g:proj_window_width. + + Whether you toggle or monotonically increase the width is determined + by the 't' flag of the g:proj_flags variable (see |project-flags|). + + Note that a Right Mouse click will not automatically place the cursor + in the Project Window if it is in a different window. The window will + go back to the g:proj_window_width width when you leave the window. + + Same as + + +\ + Move the text or fold under the cursor up one row. This may not work + in a terminal because the terminal is unaware of this key combination. + is provided for those terminals that don't recognize + . + + + +\ + Move the text or fold under the cursor down one row. This may not work + in a terminal because the terminal is unaware of this key combination. + is provided for those terminals that don't + recognize . + +\i Show in the status line the completely resolved and inherited + parameters for the fold the cursor is in. This is intended for + debugging your relative path and inherited parameters for manually + entered Projects. + +\I Show in the status line the completely resolved filename. Uses the + Project_GetFname(line('.')) function. + +\1 - \9 + Run the command specified in g:proj_run{x} where {x} is the number + of the key. See the documentation of g:proj_run1 below. + +\f1-\f9 + Run the command specified in g:proj_run_fold{x} where {x} is the + number of the key. The command is run on the files at the current + Project level. See the |project-settings| below. + +\F1-\F9 + Run the command specified in g:proj_run_fold{x} where {x} is the + number of the key. The command is run on the files at the current + Project level and all Subprojects. See the |project-settings| below. + +\0 Display the commands that are defined for \1 through \9. + +\f0 Display the commands that are defined for \f1 through \f9 and \F1 + through \F0. Same as \F0. + +\l Load all the files in the current Project level into Vim. While files + are being loaded, you may press any key to stop. + +\L Load all the files in the current Project and all Subprojects into + Vim. Use this mapping with caution--I wouldn't suggest using \L to + load a Project with thousands of files. (BTW, my Project file has more + than 5,300 files in it!) While files are being loaded, you may press + any key to stop. + +\w Wipe all the files in the current Project level from Vim. (If files + are modified, they will be saved first.) While files are being wiped, + you may press any key to stop. + +\W Wipe all the files in the current Project and all Subprojects from + Vim. (If files are modified, they will be saved first.) While files + are being wiped, you may press any key to stop. + +\g Grep all the files in the current Project level. + +\G Grep all the files in the current Project level and all Subprojects. + +\e Set up the Environment for the Project File as though you had selected + it with . This allows you to do a \e and a :make without + having to open any files in the project. + +\E Explore (using |file-explorer|) the directory of the project the + cursor is in. Does not work with netrw. + + When the 'g' flag is present in g:proj_flags (see |project-flags|) + this key toggles the Project Window open and closed. You may remap + this toggle function by putting the following in your vimrc and + replacing P with whatever key combination you wish: + + nmap P ToggleProject + +Note that the Project Plugin remaps :help because the Help Window and the +Project Window get into a fight over placement. The mapping avoids the +problem. + +============================================================================== +ADDING MAPPINGS *project-adding-mappings* + +You can add your own mappings or change the mappings of the plugin by placing +them in the file $HOME/.vimproject_mappings. This file, if it exists, will be +sourced when the plugin in loaded. Here is an example that will count the +number of entries in a project when you press \K (Kount, C is taken :-): > + + function! s:Wc() + let b:loadcount=0 + function! SpawnExec(infoline, fname, lineno, data) + let b:loadcount = b:loadcount + 1 + if getchar(0) != 0 | let b:stop_everything=1 | endif + endfunction + call Project_ForEach(1, line('.'), "*SpawnExec", 0, '') + delfunction SpawnExec + echon b:loadcount." Files\r" + unlet b:loadcount + if exists("b:stop_everything") + unlet b:stop_everything + echon "Aborted.\r" + endif + endfunction + + nnoremap K :call Wc() + +Here's another example of how I integrated the use of perforce with the plugin +in my $HOME/.vimproject_mappings: +> + function! s:DoP4(cmd) + let name=Project_GetFname(line('.')) + let dir=substitute(name, '\(.*\)/.*', '\1', 'g') + exec 'cd '.dir + exec "!".a:cmd.' '.Project_GetFname(line('.')) + cd - + endfunction + + nmap \pa :call DoP4("p4add") + nmap \pe :call DoP4("p4edit") +< +(Note that I CD to the directory the file is in so I can pick of the $P4CONFIG +file. See the perforce documentation.) + +This creates the mappings \pe to check out the file for edit and \pa to add +the file to the depot. + +Here is another example where I remap the mapping to use an external +program to launch a special kind of file (in this case, it launches ee to view +a jpg file). It is a bit contrived, but it works. +> + let s:sid = substitute(maparg('', 'n'), '.*\(.\{-}\)_.*', '\1', '') + function! s:LaunchOrWhat() + let fname=Project_GetFname(line('.')) + if fname =~ '\.jpg$' + exec 'silent! !ee "'.fname.'"&' + else + call {s:sid}_DoFoldOrOpenEntry('', 'e') + endif + endfunction + nnoremap \|:call LaunchOrWhat() +< +If the file ends in .jpg, the external program is launched, otherwise the +original mapping of is run. + +============================================================================== +SETTINGS *project-settings* + +You can set these variables in your vimrc file before the plugin is loaded to +change its default behavior + +g:proj_window_width + The width of the Project Window that the plugin attempts to maintain. + Default: 24 + + The Project Plugin is not always successful in keeping the window + where I want it with the size specified here, but it does a decent + job. + +g:proj_window_increment + The increment by which to increase the width of the Project Window + when pressing or clicking the . Default: 100 + (See |project-mappings|.) + + *project-flags* +g:proj_flags + Default: "imst" + Various flags to control the behavior of the Project Plugin. This + variable can contain any of the following character flags. + + flag Description ~ + + b When present, use the |browse()| when selecting directories + for \c and \C. This is off by default for Windows, because + the windows browser does not allow you to select directories. + + c When present, the Project Window will automatically close when + you select a file. + + F Float the Project Window. That is, turn off automatic + resizing and placement. This allows placement between other + windows that wish to share similar placement at the side of + the screen. It is also particularly helpful for external + window managers. + + g When present, the mapping for will be created to toggle + the Project Window open and closed. + + i When present, display the filename and the current working + directory in the command line when a file is selected for + opening. + + l When present, the Project Plugin will use the |:lcd| command + rather than |:cd| to change directories when you select a file + to open. This flag is really obsolete and not of much use + because of L below. + + L Similar to l, but install a BufEnter/Leave |:autocommand| to + ensure that the current working directory is changed to the + one specified in the fold CD specification whenever that + buffer is active. (|:lcd| only changes the CWD for a window, + not a buffer.) + + m Turn on mapping of the |CTRL-W_o| and |CTRL-W_CTRL_O| normal + mode commands to make the current buffer the only visible + buffer, but keep the Project Window visible, too. + + n When present, numbers will be turned on for the project + window. + + s When present, the Project Plugin will use syntax highlighting + in the Project Window. + + S Turn on sorting for refresh and create. + + t When present, toggle the size of the window rather than just + increase the size when pressing or right-clicking. + See the entry for in |project-mappings|. + + T When present, put Subproject folds at the top of the fold when + refreshing. + + v When present, use :vimgrep rather than :grep when using \G. + +g:proj_run1 ... g:proj_run9 + Contains a Vim command to execute on the file. See the + mappings of \1 to \9 above. + + %f is replaced with the full path and filename + %F is replaced with the full path and filename with spaces + quoted + %n is replaced with the filename alone + %N is replaced with the filename alone with spaces quoted + %h is replaced with the home directory + %H is replaced with the home directory with spaces quoted + %r is replaced with the directory relative to the CD path + %R is replaced with the directory relative to the CD path + with spaces quoted + %d is replaced with the CD directory. + %D is replaced with the CD directory.with spaces quoted + %% is replaced with a single % that is not used in + expansion. + + (Deprecated: %s is also replaced with the full path and + filename for backward compatibility.) + + For example, gvim will be launched on the file under the + cursor when you enter \3 if the following is in your vimrc + file: > + let g:proj_run3='silent !gvim %f' +< Here are a few other examples: > + let g:proj_run1='!p4 edit %f' + let g:proj_run2='!p4 add %f' + let g:proj_run4="echo 'Viewing %f'|sil !xterm -e less %f &" +< + On Windows systems you will want to put the %f, %h, and %d in + single quotes to avoid \ escaping. + +g:proj_run_fold1 ... g:proj_run_fold9 + Contains a Vim command to execute on the files in a fold. See + the mappings of \f1 to \f9 and \F1 to \F9 above. + + %f is the filename, %h is replaced with the project home + directory, and %d is replaced with the CD directory. Multiple + filenames can be handled in two ways: + + The first (default) way is to have %f replaced with all the + absolute filenames, and the command is run once. The second + is to have the command run for each of the non-absolute + filenames (%f is replaced with one filename at a time). To + select the second behavior, put an '*' character at the + beginning of the g:proj_run_fold{x} variable. (The '*' is + stripped before the command is run.) + + For example, note the difference between the following: > + let g:proj_run_fold3="*echo '%h/%f'" + let g:proj_run_fold4="echo '%f'" +< + Note that on Windows systems, you will want the %f, %h, and %c + within single quotes, or the \ in the paths will cause + problems. The alternative is to put them in |escape()|. + + +============================================================================== +PROJECT EXAMPLE FILE *project-example* + +Here is an example ~/.vimprojects file: > + + 1 My Project=~/c/project CD=. in=in.vim out=out.vim flags=r { + 2 Makefile + 3 in.vim + 4 out.vim + 5 GUI Files=. filter="gui*.c gui*.h" { + 6 gui_window.c + 7 gui_dialog.c + 8 gui_list.c + 9 gui.h # Header file + 10 } + 11 Database Files=. filter="data*.c data*.h" { + 12 data_read.c + 13 data_write.c + 14 data.h + 15 } + 16 OS-Specific Files { + 17 Win32=. filter="os_win32*.c os_win32*.h" { + 18 os_win32_gui.c + 19 os_win32_io.c + 20 } + 21 Unix=. filter="os_unix*.c os_unix*.h" { + 22 os_unix_gui.c + 23 os_unix_io.c + 24 } + 25 } + 26 } + +(Don't type in the line numbers, of course.) + + +============================================================================== +TIPS ON USING PROJECT PLUGIN *project-tips* + +1. You can create a Project Entry by entering this: > + + Label=~/wherever CD=. filter="*.c *.h" { + } +< + Then you can put the cursor in the fold and press \r. The script will fill + in the files (C files in this case) from this directory for you. This is + equivalent to \c without any dialogs. + +2. You can edit the Project File at any time to add, remove, or reorder files + in the Project list. + +3. If the Project Window ever gets closed, you can just enter > + :Project +< to bring it back again. (You don't need to give it the filename; the + plugin remembers.) + + If you have the 'm' flag set in g:proj_flags, then you get the Project + Window to show up again by pressing |CTRL-W_o|. This, of course, will + close any other windows that may be open that the cursor is not in. + +4. Adding files to a Project is very easy. To add, for example, the 'more.c' + file to the Project, just insert the filename in the Project Entry then + hit on it. + +5. When |quickfix| loads files, it is not equivalent to pressing on + a filename, so the directory will not be changed and the scripts will not + be run. (If I could make this otherwise, I would.) The solution is to use + the \L key to load all of the files in the Project before running + quickfix. + +6. If the Project window gets a bit cluttered with folds partially + open/closed, you can press |zM| to close everything and tidy it up. + +7. For advanced users, I am exporting the function Project_GetAllFnames() + which returns all the filenames within a fold and optionally all its + Subprojects. Also, I export Project_ForEach() for running a function for + each filename in the project. See the code for examples on how to use + these. Finally, I export Project_GetFname(line_number) so that you can + write your own mappings and get the filename for it. + +8. Some people have asked how to do a global mapping to take the cursor to + the Project window. One of my goals for the plugin is for it to be as + self-contained as possible, so I'm not going to add it by default. But you + can put this in your vimrc: +> + nmap P :Project + +< +9. You can put the . entry in a project, and it will launch the + |file-explorer| plugin on the directory. To avoid removal when you + refresh, make the entry look like this: +> + . # pragma keep +< +============================================================================== +THANKS + + The following people have sent me patches to help with the Project + Plugin development: + + Tomas Zellerin + Lawrence Kesteloot + Dave Eggum + A Harrison + Thomas Link + Richard Bair + Eric Arnold + Peter Jones + Eric Van Dewoestine + + + vim:ts=8 sw=8 noexpandtab tw=78 ft=help: diff --git a/.vim/doc/taglist.txt b/.vim/doc/taglist.txt new file mode 100644 index 0000000..6a62b39 --- /dev/null +++ b/.vim/doc/taglist.txt @@ -0,0 +1,1501 @@ +*taglist.txt* Plugin for browsing source code + +Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com) +For Vim version 6.0 and above +Last change: 2007 May 24 + +1. Overview |taglist-intro| +2. Taglist on the internet |taglist-internet| +3. Requirements |taglist-requirements| +4. Installation |taglist-install| +5. Usage |taglist-using| +6. Options |taglist-options| +7. Commands |taglist-commands| +8. Global functions |taglist-functions| +9. Extending |taglist-extend| +10. FAQ |taglist-faq| +11. License |taglist-license| +12. Todo |taglist-todo| + +============================================================================== + *taglist-intro* +1. Overview~ + +The "Tag List" plugin is a source code browser plugin for Vim. This plugin +allows you to efficiently browse through source code files for different +programming languages. The "Tag List" plugin provides the following features: + + * Displays the tags (functions, classes, structures, variables, etc.) + defined in a file in a vertically or horizontally split Vim window. + * In GUI Vim, optionally displays the tags in the Tags drop-down menu and + in the popup menu. + * Automatically updates the taglist window as you switch between + files/buffers. As you open new files, the tags defined in the new files + are added to the existing file list and the tags defined in all the + files are displayed grouped by the filename. + * When a tag name is selected from the taglist window, positions the + cursor at the definition of the tag in the source file. + * Automatically highlights the current tag name. + * Groups the tags by their type and displays them in a foldable tree. + * Can display the prototype and scope of a tag. + * Can optionally display the tag prototype instead of the tag name in the + taglist window. + * The tag list can be sorted either by name or by chronological order. + * Supports the following language files: Assembly, ASP, Awk, Beta, C, + C++, C#, Cobol, Eiffel, Erlang, Fortran, HTML, Java, Javascript, Lisp, + Lua, Make, Pascal, Perl, PHP, Python, Rexx, Ruby, Scheme, Shell, Slang, + SML, Sql, TCL, Verilog, Vim and Yacc. + * Can be easily extended to support new languages. Support for + existing languages can be modified easily. + * Provides functions to display the current tag name in the Vim status + line or the window title bar. + * The list of tags and files in the taglist can be saved and + restored across Vim sessions. + * Provides commands to get the name and prototype of the current tag. + * Runs in both console/terminal and GUI versions of Vim. + * Works with the winmanager plugin. Using the winmanager plugin, you + can use Vim plugins like the file explorer, buffer explorer and the + taglist plugin at the same time like an IDE. + * Can be used in both Unix and MS-Windows systems. + +============================================================================== + *taglist-internet* +2. Taglist on the internet~ + +The home page of the taglist plugin is at: +> + http://vim-taglist.sourceforge.net/ +< +You can subscribe to the taglist mailing list to post your questions or +suggestions for improvement or to send bug reports. Visit the following page +for subscribing to the mailing list: +> + http://groups.yahoo.com/group/taglist +< +============================================================================== + *taglist-requirements* +3. Requirements~ + +The taglist plugin requires the following: + + * Vim version 6.0 and above + * Exuberant ctags 5.0 and above + +The taglist plugin will work on all the platforms where the exuberant ctags +utility and Vim are supported (this includes MS-Windows and Unix based +systems). + +The taglist plugin relies on the exuberant ctags utility to dynamically +generate the tag listing. The exuberant ctags utility must be installed in +your system to use this plugin. The exuberant ctags utility is shipped with +most of the Linux distributions. You can download the exuberant ctags utility +from +> + http://ctags.sourceforge.net +< +The taglist plugin doesn't use or create a tags file and there is no need to +create a tags file to use this plugin. The taglist plugin will not work with +the GNU ctags or the Unix ctags utility. + +This plugin relies on the Vim "filetype" detection mechanism to determine the +type of the current file. You have to turn on the Vim filetype detection by +adding the following line to your .vimrc file: +> + filetype on +< +The taglist plugin will not work if you run Vim in the restricted mode (using +the -Z command-line argument). + +The taglist plugin uses the Vim system() function to invoke the exuberant +ctags utility. If Vim is compiled without the system() function then you +cannot use the taglist plugin. Some of the Linux distributions (Suse) compile +Vim without the system() function for security reasons. + +============================================================================== + *taglist-install* +4. Installation~ + +1. Download the taglist.zip file and unzip the files to the $HOME/.vim or the + $HOME/vimfiles or the $VIM/vimfiles directory. After this step, you should + have the following two files (the directory structure should be preserved): + + plugin/taglist.vim - main taglist plugin file + doc/taglist.txt - documentation (help) file + + Refer to the |add-plugin|and |'runtimepath'| Vim help pages for more + details about installing Vim plugins. +2. Change to the $HOME/.vim/doc or $HOME/vimfiles/doc or $VIM/vimfiles/doc + directory, start Vim and run the ":helptags ." command to process the + taglist help file. Without this step, you cannot jump to the taglist help + topics. +3. If the exuberant ctags utility is not present in one of the directories in + the PATH environment variable, then set the 'Tlist_Ctags_Cmd' variable to + point to the location of the exuberant ctags utility (not to the directory) + in the .vimrc file. +4. If you are running a terminal/console version of Vim and the terminal + doesn't support changing the window width then set the + 'Tlist_Inc_Winwidth' variable to 0 in the .vimrc file. +5. Restart Vim. +6. You can now use the ":TlistToggle" command to open/close the taglist + window. You can use the ":help taglist" command to get more information + about using the taglist plugin. + +To uninstall the taglist plugin, remove the plugin/taglist.vim and +doc/taglist.txt files from the $HOME/.vim or $HOME/vimfiles directory. + +============================================================================== + *taglist-using* +5. Usage~ + +The taglist plugin can be used in several different ways. + +1. You can keep the taglist window open during the entire editing session. On + opening the taglist window, the tags defined in all the files in the Vim + buffer list will be displayed in the taglist window. As you edit files, the + tags defined in them will be added to the taglist window. You can select a + tag from the taglist window and jump to it. The current tag will be + highlighted in the taglist window. You can close the taglist window when + you no longer need the window. +2. You can configure the taglist plugin to process the tags defined in all the + edited files always. In this configuration, even if the taglist window is + closed and the taglist menu is not displayed, the taglist plugin will + processes the tags defined in newly edited files. You can then open the + taglist window only when you need to select a tag and then automatically + close the taglist window after selecting the tag. +3. You can configure the taglist plugin to display only the tags defined in + the current file in the taglist window. By default, the taglist plugin + displays the tags defined in all the files in the Vim buffer list. As you + switch between files, the taglist window will be refreshed to display only + the tags defined in the current file. +4. In GUI Vim, you can use the Tags pull-down and popup menu created by the + taglist plugin to display the tags defined in the current file and select a + tag to jump to it. You can use the menu without opening the taglist window. + By default, the Tags menu is disabled. +5. You can configure the taglist plugin to display the name of the current tag + in the Vim window status line or in the Vim window title bar. For this to + work without the taglist window or menu, you need to configure the taglist + plugin to process the tags defined in a file always. +6. You can save the tags defined in multiple files to a taglist session file + and load it when needed. You can also configure the taglist plugin to not + update the taglist window when editing new files. You can then manually add + files to the taglist window. + +Opening the taglist window~ +You can open the taglist window using the ":TlistOpen" or the ":TlistToggle" +commands. The ":TlistOpen" command opens the taglist window and jumps to it. +The ":TlistToggle" command opens or closes (toggle) the taglist window and the +cursor remains in the current window. If the 'Tlist_GainFocus_On_ToggleOpen' +variable is set to 1, then the ":TlistToggle" command opens the taglist window +and moves the cursor to the taglist window. + +You can map a key to invoke these commands. For example, the following command +creates a normal mode mapping for the key to toggle the taglist window. +> + nnoremap :TlistToggle +< +Add the above mapping to your ~/.vimrc or $HOME/_vimrc file. + +To automatically open the taglist window on Vim startup, set the +'Tlist_Auto_Open' variable to 1. + +You can also open the taglist window on startup using the following command +line: +> + $ vim +TlistOpen +< +Closing the taglist window~ +You can close the taglist window from the taglist window by pressing 'q' or +using the Vim ":q" command. You can also use any of the Vim window commands to +close the taglist window. Invoking the ":TlistToggle" command when the taglist +window is opened, closes the taglist window. You can also use the +":TlistClose" command to close the taglist window. + +To automatically close the taglist window when a tag or file is selected, you +can set the 'Tlist_Close_On_Select' variable to 1. To exit Vim when only the +taglist window is present, set the 'Tlist_Exit_OnlyWindow' variable to 1. + +Jumping to a tag or a file~ +You can select a tag in the taglist window either by pressing the key +or by double clicking the tag name using the mouse. To jump to a tag on a +single mouse click set the 'Tlist_Use_SingleClick' variable to 1. + +If the selected file is already opened in a window, then the cursor is moved +to that window. If the file is not currently opened in a window then the file +is opened in the window used by the taglist plugin to show the previously +selected file. If there are no usable windows, then the file is opened in a +new window. The file is not opened in special windows like the quickfix +window, preview window and windows containing buffer with the 'buftype' option +set. + +To jump to the tag in a new window, press the 'o' key. To open the file in the +previous window (Ctrl-W_p) use the 'P' key. You can press the 'p' key to jump +to the tag but still keep the cursor in the taglist window (preview). + +To open the selected file in a tab, use the 't' key. If the file is already +present in a tab then the cursor is moved to that tab otherwise the file is +opened in a new tab. To jump to a tag in a new tab press Ctrl-t. The taglist +window is automatically opened in the newly created tab. + +Instead of jumping to a tag, you can open a file by pressing the key +or by double clicking the file name using the mouse. + +In the taglist window, you can use the [[ or key to jump to the +beginning of the previous file. You can use the ]] or key to jump to the +beginning of the next file. When you reach the first or last file, the search +wraps around and the jumps to the next/previous file. + +Highlighting the current tag~ +The taglist plugin automatically highlights the name of the current tag in the +taglist window. The Vim |CursorHold| autocmd event is used for this. If the +current tag name is not visible in the taglist window, then the taglist window +contents are scrolled to make that tag name visible. You can also use the +":TlistHighlightTag" command to force the highlighting of the current tag. + +The tag name is highlighted if no activity is performed for |'updatetime'| +milliseconds. The default value for this Vim option is 4 seconds. To avoid +unexpected problems, you should not set the |'updatetime'| option to a very +low value. + +To disable the automatic highlighting of the current tag name in the taglist +window, set the 'Tlist_Auto_Highlight_Tag' variable to zero. + +When entering a Vim buffer/window, the taglist plugin automatically highlights +the current tag in that buffer/window. If you like to disable the automatic +highlighting of the current tag when entering a buffer, set the +'Tlist_Highlight_Tag_On_BufEnter' variable to zero. + +Adding files to the taglist~ +When the taglist window is opened, all the files in the Vim buffer list are +processed and the supported files are added to the taglist. When you edit a +file in Vim, the taglist plugin automatically processes this file and adds it +to the taglist. If you close the taglist window, the tag information in the +taglist is retained. + +To process files even when the taglist window is not open, set the +'Tlist_Process_File_Always' variable to 1. + +You can manually add multiple files to the taglist without opening them using +the ":TlistAddFiles" and the ":TlistAddFilesRecursive" commands. + +For example, to add all the C files in the /my/project/dir directory to the +taglist, you can use the following command: +> + :TlistAddFiles /my/project/dir/*.c +< +Note that when adding several files with a large number of tags or a large +number of files, it will take several seconds to several minutes for the +taglist plugin to process all the files. You should not interrupt the taglist +plugin by pressing . + +You can recursively add multiple files from a directory tree using the +":TlistAddFilesRecursive" command: +> + :TlistAddFilesRecursive /my/project/dir *.c +< +This command takes two arguments. The first argument specifies the directory +from which to recursively add the files. The second optional argument +specifies the wildcard matching pattern for selecting the files to add. The +default pattern is * and all the files are added. + +Displaying tags for only one file~ +The taglist window displays the tags for all the files in the Vim buffer list +and all the manually added files. To display the tags for only the current +active buffer, set the 'Tlist_Show_One_File' variable to 1. + +Removing files from the taglist~ +You can remove a file from the taglist window, by pressing the 'd' key when the +cursor is on one of the tags listed for the file in the taglist window. The +removed file will no longer be displayed in the taglist window in the current +Vim session. To again display the tags for the file, open the file in a Vim +window and then use the ":TlistUpdate" command or use ":TlistAddFiles" command +to add the file to the taglist. + +When a buffer is removed from the Vim buffer list using the ":bdelete" or the +":bwipeout" command, the taglist is updated to remove the stored information +for this buffer. + +Updating the tags displayed for a file~ +The taglist plugin keeps track of the modification time of a file. When the +modification time changes (the file is modified), the taglist plugin +automatically updates the tags listed for that file. The modification time of +a file is checked when you enter a window containing that file or when you +load that file. + +You can also update or refresh the tags displayed for a file by pressing the +"u" key in the taglist window. If an existing file is modified, after the file +is saved, the taglist plugin automatically updates the tags displayed for the +file. + +You can also use the ":TlistUpdate" command to update the tags for the current +buffer after you made some changes to it. You should save the modified buffer +before you update the taglist window. Otherwise the listed tags will not +include the new tags created in the buffer. + +If you have deleted the tags displayed for a file in the taglist window using +the 'd' key, you can again display the tags for that file using the +":TlistUpdate" command. + +Controlling the taglist updates~ +To disable the automatic processing of new files or modified files, you can +set the 'Tlist_Auto_Update' variable to zero. When this variable is set to +zero, the taglist is updated only when you use the ":TlistUpdate" command or +the ":TlistAddFiles" or the ":TlistAddFilesRecursive" commands. You can use +this option to control which files are added to the taglist. + +You can use the ":TlistLock" command to lock the taglist contents. After this +command is executed, new files are not automatically added to the taglist. +When the taglist is locked, you can use the ":TlistUpdate" command to add the +current file or the ":TlistAddFiles" or ":TlistAddFilesRecursive" commands to +add new files to the taglist. To unlock the taglist, use the ":TlistUnlock" +command. + +Displaying the tag prototype~ +To display the prototype of the tag under the cursor in the taglist window, +press the space bar. If you place the cursor on a tag name in the taglist +window, then the tag prototype is displayed at the Vim status line after +|'updatetime'| milliseconds. The default value for the |'updatetime'| Vim +option is 4 seconds. + +You can get the name and prototype of a tag without opening the taglist window +and the taglist menu using the ":TlistShowTag" and the ":TlistShowPrototype" +commands. These commands will work only if the current file is already present +in the taglist. To use these commands without opening the taglist window, set +the 'Tlist_Process_File_Always' variable to 1. + +You can use the ":TlistShowTag" command to display the name of the tag at or +before the specified line number in the specified file. If the file name and +line number are not supplied, then this command will display the name of the +current tag. For example, +> + :TlistShowTag + :TlistShowTag myfile.java 100 +< +You can use the ":TlistShowPrototype" command to display the prototype of the +tag at or before the specified line number in the specified file. If the file +name and the line number are not supplied, then this command will display the +prototype of the current tag. For example, +> + :TlistShowPrototype + :TlistShowPrototype myfile.c 50 +< +In the taglist window, when the mouse is moved over a tag name, the tag +prototype is displayed in a balloon. This works only in GUI versions where +balloon evaluation is supported. + +Taglist window contents~ +The taglist window contains the tags defined in various files in the taglist +grouped by the filename and by the tag type (variable, function, class, etc.). +For tags with scope information (like class members, structures inside +structures, etc.), the scope information is displayed in square brackets "[]" +after the tag name. + +The contents of the taglist buffer/window are managed by the taglist plugin. +The |'filetype'| for the taglist buffer is set to 'taglist'. The Vim +|'modifiable'| option is turned off for the taglist buffer. You should not +manually edit the taglist buffer, by setting the |'modifiable'| flag. If you +manually edit the taglist buffer contents, then the taglist plugin will be out +of sync with the taglist buffer contents and the plugin will no longer work +correctly. To redisplay the taglist buffer contents again, close the taglist +window and reopen it. + +Opening and closing the tag and file tree~ +In the taglist window, the tag names are displayed as a foldable tree using +the Vim folding support. You can collapse the tree using the '-' key or using +the Vim |zc| fold command. You can open the tree using the '+' key or using +the Vim |zo| fold command. You can open all the folds using the '*' key or +using the Vim |zR| fold command. You can also use the mouse to open/close the +folds. You can close all the folds using the '=' key. You should not manually +create or delete the folds in the taglist window. + +To automatically close the fold for the inactive files/buffers and open only +the fold for the current buffer in the taglist window, set the +'Tlist_File_Fold_Auto_Close' variable to 1. + +Sorting the tags for a file~ +The tags displayed in the taglist window can be sorted either by their name or +by their chronological order. The default sorting method is by the order in +which the tags appear in a file. You can change the default sort method by +setting the 'Tlist_Sort_Type' variable to either "name" or "order". You can +sort the tags by their name by pressing the "s" key in the taglist window. You +can again sort the tags by their chronological order using the "s" key. Each +file in the taglist window can be sorted using different order. + +Zooming in and out of the taglist window~ +You can press the 'x' key in the taglist window to maximize the taglist +window width/height. The window will be maximized to the maximum possible +width/height without closing the other existing windows. You can again press +'x' to restore the taglist window to the default width/height. + + *taglist-session* +Taglist Session~ +A taglist session refers to the group of files and their tags stored in the +taglist in a Vim session. + +You can save and restore a taglist session (and all the displayed tags) using +the ":TlistSessionSave" and ":TlistSessionLoad" commands. + +To save the information about the tags and files in the taglist to a file, use +the ":TlistSessionSave" command and specify the filename: +> + :TlistSessionSave +< +To load a saved taglist session, use the ":TlistSessionLoad" command: > + + :TlistSessionLoad +< +When you load a taglist session file, the tags stored in the file will be +added to the tags already stored in the taglist. + +The taglist session feature can be used to save the tags for large files or a +group of frequently used files (like a project). By using the taglist session +file, you can minimize the amount to time it takes to load/refresh the taglist +for multiple files. + +You can create more than one taglist session file for multiple groups of +files. + +Displaying the tag name in the Vim status line or the window title bar~ +You can use the Tlist_Get_Tagname_By_Line() function provided by the taglist +plugin to display the current tag name in the Vim status line or the window +title bar. Similarly, you can use the Tlist_Get_Tag_Prototype_By_Line() +function to display the current tag prototype in the Vim status line or the +window title bar. + +For example, the following command can be used to display the current tag name +in the status line: +> + :set statusline=%<%f%=%([%{Tlist_Get_Tagname_By_Line()}]%) +< +The following command can be used to display the current tag name in the +window title bar: +> + :set title titlestring=%<%f\ %([%{Tlist_Get_Tagname_By_Line()}]%) +< +Note that the current tag name can be displayed only after the file is +processed by the taglist plugin. For this, you have to either set the +'Tlist_Process_File_Always' variable to 1 or open the taglist window or use +the taglist menu. For more information about configuring the Vim status line, +refer to the documentation for the Vim |'statusline'| option. + +Changing the taglist window highlighting~ +The following Vim highlight groups are defined and used to highlight the +various entities in the taglist window: + + TagListTagName - Used for tag names + TagListTagScope - Used for tag scope + TagListTitle - Used for tag titles + TagListComment - Used for comments + TagListFileName - Used for filenames + +By default, these highlight groups are linked to the standard Vim highlight +groups. If you want to change the colors used for these highlight groups, +prefix the highlight group name with 'My' and define it in your .vimrc or +.gvimrc file: MyTagListTagName, MyTagListTagScope, MyTagListTitle, +MyTagListComment and MyTagListFileName. For example, to change the colors +used for tag names, you can use the following command: +> + :highlight MyTagListTagName guifg=blue ctermfg=blue +< +Controlling the taglist window~ +To use a horizontally split taglist window, instead of a vertically split +window, set the 'Tlist_Use_Horiz_Window' variable to 1. + +To use a vertically split taglist window on the rightmost side of the Vim +window, set the 'Tlist_Use_Right_Window' variable to 1. + +You can specify the width of the vertically split taglist window, by setting +the 'Tlist_WinWidth' variable. You can specify the height of the horizontally +split taglist window, by setting the 'Tlist_WinHeight' variable. + +When opening a vertically split taglist window, the Vim window width is +increased to accommodate the new taglist window. When the taglist window is +closed, the Vim window is reduced. To disable this, set the +'Tlist_Inc_Winwidth' variable to zero. + +To reduce the number of empty lines in the taglist window, set the +'Tlist_Compact_Format' variable to 1. + +To not display the Vim fold column in the taglist window, set the +'Tlist_Enable_Fold_Column' variable to zero. + +To display the tag prototypes instead of the tag names in the taglist window, +set the 'Tlist_Display_Prototype' variable to 1. + +To not display the scope of the tags next to the tag names, set the +'Tlist_Display_Tag_Scope' variable to zero. + + *taglist-keys* +Taglist window key list~ +The following table lists the description of the keys that can be used +in the taglist window. + + Key Description~ + + Jump to the location where the tag under cursor is + defined. + o Jump to the location where the tag under cursor is + defined in a new window. + P Jump to the tag in the previous (Ctrl-W_p) window. + p Display the tag definition in the file window and + keep the cursor in the taglist window itself. + t Jump to the tag in a new tab. If the file is already + opened in a tab, move to that tab. + Ctrl-t Jump to the tag in a new tab. + Display the prototype of the tag under the cursor. + For file names, display the full path to the file, + file type and the number of tags. For tag types, display the + tag type and the number of tags. + u Update the tags listed in the taglist window + s Change the sort order of the tags (by name or by order) + d Remove the tags for the file under the cursor + x Zoom-in or Zoom-out the taglist window + + Open a fold + - Close a fold + * Open all folds + = Close all folds + [[ Jump to the beginning of the previous file + Jump to the beginning of the previous file + ]] Jump to the beginning of the next file + Jump to the beginning of the next file + q Close the taglist window + Display help + +The above keys will work in both the normal mode and the insert mode. + + *taglist-menu* +Taglist menu~ +When using GUI Vim, the taglist plugin can display the tags defined in the +current file in the drop-down menu and the popup menu. By default, this +feature is turned off. To turn on this feature, set the 'Tlist_Show_Menu' +variable to 1. + +You can jump to a tag by selecting the tag name from the menu. You can use the +taglist menu independent of the taglist window i.e. you don't need to open the +taglist window to get the taglist menu. + +When you switch between files/buffers, the taglist menu is automatically +updated to display the tags defined in the current file/buffer. + +The tags are grouped by their type (variables, functions, classes, methods, +etc.) and displayed as a separate sub-menu for each type. If all the tags +defined in a file are of the same type (e.g. functions), then the sub-menu is +not used. + +If the number of items in a tag type submenu exceeds the value specified by +the 'Tlist_Max_Submenu_Items' variable, then the submenu will be split into +multiple submenus. The default setting for 'Tlist_Max_Submenu_Items' is 25. +The first and last tag names in the submenu are used to form the submenu name. +The menu items are prefixed by alpha-numeric characters for easy selection by +keyboard. + +If the popup menu support is enabled (the |'mousemodel'| option contains +"popup"), then the tags menu is added to the popup menu. You can access +the popup menu by right clicking on the GUI window. + +You can regenerate the tags menu by selecting the 'Tags->Refresh menu' entry. +You can sort the tags listed in the menu either by name or by order by +selecting the 'Tags->Sort menu by->Name/Order' menu entry. + +You can tear-off the Tags menu and keep it on the side of the Vim window +for quickly locating the tags. + +Using the taglist plugin with the winmanager plugin~ +You can use the taglist plugin with the winmanager plugin. This will allow you +to use the file explorer, buffer explorer and the taglist plugin at the same +time in different windows. To use the taglist plugin with the winmanager +plugin, set 'TagList' in the 'winManagerWindowLayout' variable. For example, +to use the file explorer plugin and the taglist plugin at the same time, use +the following setting: > + + let winManagerWindowLayout = 'FileExplorer|TagList' +< +Getting help~ +If you have installed the taglist help file (this file), then you can use the +Vim ":help taglist-" command to get help on the various taglist +topics. + +You can press the key in the taglist window to display the help +information about using the taglist window. If you again press the key, +the help information is removed from the taglist window. + + *taglist-debug* +Debugging the taglist plugin~ +You can use the ":TlistDebug" command to enable logging of the debug messages +from the taglist plugin. To display the logged debug messages, you can use the +":TlistMessages" command. To disable the logging of the debug messages, use +the ":TlistUndebug" command. + +You can specify a file name to the ":TlistDebug" command to log the debug +messages to a file. Otherwise, the debug messages are stored in a script-local +variable. In the later case, to minimize memory usage, only the last 3000 +characters from the debug messages are stored. + +============================================================================== + *taglist-options* +6. Options~ + +A number of Vim variables control the behavior of the taglist plugin. These +variables are initialized to a default value. By changing these variables you +can change the behavior of the taglist plugin. You need to change these +settings only if you want to change the behavior of the taglist plugin. You +should use the |:let| command in your .vimrc file to change the setting of any +of these variables. + +The configurable taglist variables are listed below. For a detailed +description of these variables refer to the text below this table. + +|'Tlist_Auto_Highlight_Tag'| Automatically highlight the current tag in the + taglist. +|'Tlist_Auto_Open'| Open the taglist window when Vim starts. +|'Tlist_Auto_Update'| Automatically update the taglist to include + newly edited files. +|'Tlist_Close_On_Select'| Close the taglist window when a file or tag is + selected. +|'Tlist_Compact_Format'| Remove extra information and blank lines from + the taglist window. +|'Tlist_Ctags_Cmd'| Specifies the path to the ctags utility. +|'Tlist_Display_Prototype'| Show prototypes and not tags in the taglist + window. +|'Tlist_Display_Tag_Scope'| Show tag scope next to the tag name. +|'Tlist_Enable_Fold_Column'| Show the fold indicator column in the taglist + window. +|'Tlist_Exit_OnlyWindow'| Close Vim if the taglist is the only window. +|'Tlist_File_Fold_Auto_Close'| Close tag folds for inactive buffers. +|'Tlist_GainFocus_On_ToggleOpen'| + Jump to taglist window on open. +|'Tlist_Highlight_Tag_On_BufEnter'| + On entering a buffer, automatically highlight + the current tag. +|'Tlist_Inc_Winwidth'| Increase the Vim window width to accommodate + the taglist window. +|'Tlist_Max_Submenu_Items'| Maximum number of items in a tags sub-menu. +|'Tlist_Max_Tag_Length'| Maximum tag length used in a tag menu entry. +|'Tlist_Process_File_Always'| Process files even when the taglist window is + closed. +|'Tlist_Show_Menu'| Display the tags menu. +|'Tlist_Show_One_File'| Show tags for the current buffer only. +|'Tlist_Sort_Type'| Sort method used for arranging the tags. +|'Tlist_Use_Horiz_Window'| Use a horizontally split window for the + taglist window. +|'Tlist_Use_Right_Window'| Place the taglist window on the right side. +|'Tlist_Use_SingleClick'| Single click on a tag jumps to it. +|'Tlist_WinHeight'| Horizontally split taglist window height. +|'Tlist_WinWidth'| Vertically split taglist window width. + + *'Tlist_Auto_Highlight_Tag'* +Tlist_Auto_Highlight_Tag~ +The taglist plugin will automatically highlight the current tag in the taglist +window. If you want to disable this, then you can set the +'Tlist_Auto_Highlight_Tag' variable to zero. Note that even though the current +tag highlighting is disabled, the tags for a new file will still be added to +the taglist window. +> + let Tlist_Auto_Highlight_Tag = 0 +< +With the above variable set to 1, you can use the ":TlistHighlightTag" command +to highlight the current tag. + + *'Tlist_Auto_Open'* +Tlist_Auto_Open~ +To automatically open the taglist window, when you start Vim, you can set the +'Tlist_Auto_Open' variable to 1. By default, this variable is set to zero and +the taglist window will not be opened automatically on Vim startup. +> + let Tlist_Auto_Open = 1 +< +The taglist window is opened only when a supported type of file is opened on +Vim startup. For example, if you open text files, then the taglist window will +not be opened. + + *'Tlist_Auto_Update'* +Tlist_Auto_Update~ +When a new file is edited, the tags defined in the file are automatically +processed and added to the taglist. To stop adding new files to the taglist, +set the 'Tlist_Auto_Update' variable to zero. By default, this variable is set +to 1. +> + let Tlist_Auto_Update = 0 +< +With the above variable set to 1, you can use the ":TlistUpdate" command to +add the tags defined in the current file to the taglist. + + *'Tlist_Close_On_Select'* +Tlist_Close_On_Select~ +If you want to close the taglist window when a file or tag is selected, then +set the 'Tlist_Close_On_Select' variable to 1. By default, this variable is +set zero and when you select a tag or file from the taglist window, the window +is not closed. +> + let Tlist_Close_On_Select = 1 +< + *'Tlist_Compact_Format'* +Tlist_Compact_Format~ +By default, empty lines are used to separate different tag types displayed for +a file and the tags displayed for different files in the taglist window. If +you want to display as many tags as possible in the taglist window, you can +set the 'Tlist_Compact_Format' variable to 1 to get a compact display. +> + let Tlist_Compact_Format = 1 +< + *'Tlist_Ctags_Cmd'* +Tlist_Ctags_Cmd~ +The 'Tlist_Ctags_Cmd' variable specifies the location (path) of the exuberant +ctags utility. If exuberant ctags is present in any one of the directories in +the PATH environment variable, then there is no need to set this variable. + +The exuberant ctags tool can be installed under different names. When the +taglist plugin starts up, if the 'Tlist_Ctags_Cmd' variable is not set, it +checks for the names exuberant-ctags, exctags, ctags, ctags.exe and tags in +the PATH environment variable. If any one of the named executable is found, +then the Tlist_Ctags_Cmd variable is set to that name. + +If exuberant ctags is not present in one of the directories specified in the +PATH environment variable, then set this variable to point to the location of +the ctags utility in your system. Note that this variable should point to the +fully qualified exuberant ctags location and NOT to the directory in which +exuberant ctags is installed. If the exuberant ctags tool is not found in +either PATH or in the specified location, then the taglist plugin will not be +loaded. Examples: +> + let Tlist_Ctags_Cmd = 'd:\tools\ctags.exe' + let Tlist_Ctags_Cmd = '/usr/local/bin/ctags' +< + *'Tlist_Display_Prototype'* +Tlist_Display_Prototype~ +By default, only the tag name will be displayed in the taglist window. If you +like to see tag prototypes instead of names, set the 'Tlist_Display_Prototype' +variable to 1. By default, this variable is set to zero and only tag names +will be displayed. +> + let Tlist_Display_Prototype = 1 +< + *'Tlist_Display_Tag_Scope'* +Tlist_Display_Tag_Scope~ +By default, the scope of a tag (like a C++ class) will be displayed in +square brackets next to the tag name. If you don't want the tag scopes +to be displayed, then set the 'Tlist_Display_Tag_Scope' to zero. By default, +this variable is set to 1 and the tag scopes will be displayed. +> + let Tlist_Display_Tag_Scope = 0 +< + *'Tlist_Enable_Fold_Column'* +Tlist_Enable_Fold_Column~ +By default, the Vim fold column is enabled and displayed in the taglist +window. If you wish to disable this (for example, when you are working with a +narrow Vim window or terminal), you can set the 'Tlist_Enable_Fold_Column' +variable to zero. +> + let Tlist_Enable_Fold_Column = 1 +< + *'Tlist_Exit_OnlyWindow'* +Tlist_Exit_OnlyWindow~ +If you want to exit Vim if only the taglist window is currently opened, then +set the 'Tlist_Exit_OnlyWindow' variable to 1. By default, this variable is +set to zero and the Vim instance will not be closed if only the taglist window +is present. +> + let Tlist_Exit_OnlyWindow = 1 +< + *'Tlist_File_Fold_Auto_Close'* +Tlist_File_Fold_Auto_Close~ +By default, the tags tree displayed in the taglist window for all the files is +opened. You can close/fold the tags tree for the files manually. To +automatically close the tags tree for inactive files, you can set the +'Tlist_File_Fold_Auto_Close' variable to 1. When this variable is set to 1, +the tags tree for the current buffer is automatically opened and for all the +other buffers is closed. +> + let Tlist_File_Fold_Auto_Close = 1 +< + *'Tlist_GainFocus_On_ToggleOpen'* +Tlist_GainFocus_On_ToggleOpen~ +When the taglist window is opened using the ':TlistToggle' command, this +option controls whether the cursor is moved to the taglist window or remains +in the current window. By default, this option is set to 0 and the cursor +remains in the current window. When this variable is set to 1, the cursor +moves to the taglist window after opening the taglist window. +> + let Tlist_GainFocus_On_ToggleOpen = 1 +< + *'Tlist_Highlight_Tag_On_BufEnter'* +Tlist_Highlight_Tag_On_BufEnter~ +When you enter a Vim buffer/window, the current tag in that buffer/window is +automatically highlighted in the taglist window. If the current tag name is +not visible in the taglist window, then the taglist window contents are +scrolled to make that tag name visible. If you like to disable the automatic +highlighting of the current tag when entering a buffer, you can set the +'Tlist_Highlight_Tag_On_BufEnter' variable to zero. The default setting for +this variable is 1. +> + let Tlist_Highlight_Tag_On_BufEnter = 0 +< + *'Tlist_Inc_Winwidth'* +Tlist_Inc_Winwidth~ +By default, when the width of the window is less than 100 and a new taglist +window is opened vertically, then the window width is increased by the value +set in the 'Tlist_WinWidth' variable to accommodate the new window. The value +of this variable is used only if you are using a vertically split taglist +window. + +If your terminal doesn't support changing the window width from Vim (older +version of xterm running in a Unix system) or if you see any weird problems in +the screen due to the change in the window width or if you prefer not to +adjust the window width then set the 'Tlist_Inc_Winwidth' variable to zero. +CAUTION: If you are using the MS-Windows version of Vim in a MS-DOS command +window then you must set this variable to zero, otherwise the system may hang +due to a Vim limitation (explained in :help win32-problems) +> + let Tlist_Inc_Winwidth = 0 +< + *'Tlist_Max_Submenu_Items'* +Tlist_Max_Submenu_Items~ +If a file contains too many tags of a particular type (function, variable, +class, etc.), greater than that specified by the 'Tlist_Max_Submenu_Items' +variable, then the menu for that tag type will be split into multiple +sub-menus. The default setting for the 'Tlist_Max_Submenu_Items' variable is +25. This can be changed by setting the 'Tlist_Max_Submenu_Items' variable: +> + let Tlist_Max_Submenu_Items = 20 +< +The name of the submenu is formed using the names of the first and the last +tag entries in that submenu. + + *'Tlist_Max_Tag_Length'* +Tlist_Max_Tag_Length~ +Only the first 'Tlist_Max_Tag_Length' characters from the tag names will be +used to form the tag type submenu name. The default value for this variable is +10. Change the 'Tlist_Max_Tag_Length' setting if you want to include more or +less characters: +> + let Tlist_Max_Tag_Length = 10 +< + *'Tlist_Process_File_Always'* +Tlist_Process_File_Always~ +By default, the taglist plugin will generate and process the tags defined in +the newly opened files only when the taglist window is opened or when the +taglist menu is enabled. When the taglist window is closed, the taglist plugin +will stop processing the tags for newly opened files. + +You can set the 'Tlist_Process_File_Always' variable to 1 to generate the list +of tags for new files even when the taglist window is closed and the taglist +menu is disabled. +> + let Tlist_Process_File_Always = 1 +< +To use the ":TlistShowTag" and the ":TlistShowPrototype" commands without the +taglist window and the taglist menu, you should set this variable to 1. + + *'Tlist_Show_Menu'* +Tlist_Show_Menu~ +When using GUI Vim, you can display the tags defined in the current file in a +menu named "Tags". By default, this feature is turned off. To turn on this +feature, set the 'Tlist_Show_Menu' variable to 1: +> + let Tlist_Show_Menu = 1 +< + *'Tlist_Show_One_File'* +Tlist_Show_One_File~ +By default, the taglist plugin will display the tags defined in all the loaded +buffers in the taglist window. If you prefer to display the tags defined only +in the current buffer, then you can set the 'Tlist_Show_One_File' to 1. When +this variable is set to 1, as you switch between buffers, the taglist window +will be refreshed to display the tags for the current buffer and the tags for +the previous buffer will be removed. +> + let Tlist_Show_One_File = 1 +< + *'Tlist_Sort_Type'* +Tlist_Sort_Type~ +The 'Tlist_Sort_Type' variable specifies the sort order for the tags in the +taglist window. The tags can be sorted either alphabetically by their name or +by the order of their appearance in the file (chronological order). By +default, the tag names will be listed by the order in which they are defined +in the file. You can change the sort type (from name to order or from order to +name) by pressing the "s" key in the taglist window. You can also change the +default sort order by setting 'Tlist_Sort_Type' to "name" or "order": +> + let Tlist_Sort_Type = "name" +< + *'Tlist_Use_Horiz_Window'* +Tlist_Use_Horiz_Window~ +Be default, the tag names are displayed in a vertically split window. If you +prefer a horizontally split window, then set the 'Tlist_Use_Horiz_Window' +variable to 1. If you are running MS-Windows version of Vim in a MS-DOS +command window, then you should use a horizontally split window instead of a +vertically split window. Also, if you are using an older version of xterm in a +Unix system that doesn't support changing the xterm window width, you should +use a horizontally split window. +> + let Tlist_Use_Horiz_Window = 1 +< + *'Tlist_Use_Right_Window'* +Tlist_Use_Right_Window~ +By default, the vertically split taglist window will appear on the left hand +side. If you prefer to open the window on the right hand side, you can set the +'Tlist_Use_Right_Window' variable to 1: +> + let Tlist_Use_Right_Window = 1 +< + *'Tlist_Use_SingleClick'* +Tlist_Use_SingleClick~ +By default, when you double click on the tag name using the left mouse +button, the cursor will be positioned at the definition of the tag. You +can set the 'Tlist_Use_SingleClick' variable to 1 to jump to a tag when +you single click on the tag name using the mouse. By default this variable +is set to zero. +> + let Tlist_Use_SingleClick = 1 +< +Due to a bug in Vim, if you set 'Tlist_Use_SingleClick' to 1 and try to resize +the taglist window using the mouse, then Vim will crash. This problem is fixed +in Vim 6.3 and above. In the meantime, instead of resizing the taglist window +using the mouse, you can use normal Vim window resizing commands to resize the +taglist window. + + *'Tlist_WinHeight'* +Tlist_WinHeight~ +The default height of the horizontally split taglist window is 10. This can be +changed by modifying the 'Tlist_WinHeight' variable: +> + let Tlist_WinHeight = 20 +< +The |'winfixheight'| option is set for the taglist window, to maintain the +height of the taglist window, when new Vim windows are opened and existing +windows are closed. + + *'Tlist_WinWidth'* +Tlist_WinWidth~ +The default width of the vertically split taglist window is 30. This can be +changed by modifying the 'Tlist_WinWidth' variable: +> + let Tlist_WinWidth = 20 +< +Note that the value of the |'winwidth'| option setting determines the minimum +width of the current window. If you set the 'Tlist_WinWidth' variable to a +value less than that of the |'winwidth'| option setting, then Vim will use the +value of the |'winwidth'| option. + +When new Vim windows are opened and existing windows are closed, the taglist +plugin will try to maintain the width of the taglist window to the size +specified by the 'Tlist_WinWidth' variable. + +============================================================================== + *taglist-commands* +7. Commands~ + +The taglist plugin provides the following ex-mode commands: + +|:TlistAddFiles| Add multiple files to the taglist. +|:TlistAddFilesRecursive| + Add files recursively to the taglist. +|:TlistClose| Close the taglist window. +|:TlistDebug| Start logging of taglist debug messages. +|:TlistLock| Stop adding new files to the taglist. +|:TlistMessages| Display the logged taglist plugin debug messages. +|:TlistOpen| Open and jump to the taglist window. +|:TlistSessionSave| Save the information about files and tags in the + taglist to a session file. +|:TlistSessionLoad| Load the information about files and tags stored + in a session file to taglist. +|:TlistShowPrototype| Display the prototype of the tag at or before the + specified line number. +|:TlistShowTag| Display the name of the tag defined at or before the + specified line number. +|:TlistHighlightTag| Highlight the current tag in the taglist window. +|:TlistToggle| Open or close (toggle) the taglist window. +|:TlistUndebug| Stop logging of taglist debug messages. +|:TlistUnlock| Start adding new files to the taglist. +|:TlistUpdate| Update the tags for the current buffer. + + *:TlistAddFiles* +:TlistAddFiles {file(s)} [file(s) ...] + Add one or more specified files to the taglist. You can + specify multiple filenames using wildcards. To specify a + file name with space character, you should escape the space + character with a backslash. + Examples: +> + :TlistAddFiles *.c *.cpp + :TlistAddFiles file1.html file2.html +< + If you specify a large number of files, then it will take some + time for the taglist plugin to process all of them. The + specified files will not be edited in a Vim window and will + not be added to the Vim buffer list. + + *:TlistAddFilesRecursive* +:TlistAddFilesRecursive {directory} [ {pattern} ] + Add files matching {pattern} recursively from the specified + {directory} to the taglist. If {pattern} is not specified, + then '*' is assumed. To specify the current directory, use "." + for {directory}. To specify a directory name with space + character, you should escape the space character with a + backslash. + Examples: +> + :TlistAddFilesRecursive myproject *.java + :TlistAddFilesRecursive smallproject +< + If large number of files are present in the specified + directory tree, then it will take some time for the taglist + plugin to process all of them. + + *:TlistClose* +:TlistClose Close the taglist window. This command can be used from any + one of the Vim windows. + + *:TlistDebug* +:TlistDebug [filename] + Start logging of debug messages from the taglist plugin. + If {filename} is specified, then the debug messages are stored + in the specified file. Otherwise, the debug messages are + stored in a script local variable. If the file {filename} is + already present, then it is overwritten. + + *:TlistLock* +:TlistLock + Lock the taglist and don't process new files. After this + command is executed, newly edited files will not be added to + the taglist. + + *:TlistMessages* +:TlistMessages + Display the logged debug messages from the taglist plugin + in a window. This command works only when logging to a + script-local variable. + + *:TlistOpen* +:TlistOpen Open and jump to the taglist window. Creates the taglist + window, if the window is not opened currently. After executing + this command, the cursor is moved to the taglist window. When + the taglist window is opened for the first time, all the files + in the buffer list are processed and the tags defined in them + are displayed in the taglist window. + + *:TlistSessionSave* +:TlistSessionSave {filename} + Saves the information about files and tags in the taglist to + the specified file. This command can be used to save and + restore the taglist contents across Vim sessions. + + *:TlistSessionLoad* +:TlistSessionLoad {filename} + Load the information about files and tags stored in the + specified session file to the taglist. + + *:TlistShowPrototype* +:TlistShowPrototype [filename] [linenumber] + Display the prototype of the tag at or before the specified + line number. If the file name and the line number are not + specified, then the current file name and line number are + used. A tag spans multiple lines starting from the line where + it is defined to the line before the next tag. This command + displays the prototype for the tag for any line number in this + range. + + *:TlistShowTag* +:TlistShowTag [filename] [linenumber] + Display the name of the tag defined at or before the specified + line number. If the file name and the line number are not + specified, then the current file name and line number are + used. A tag spans multiple lines starting from the line where + it is defined to the line before the next tag. This command + displays the tag name for any line number in this range. + + *:TlistHighlightTag* +:TlistHighlightTag + Highlight the current tag in the taglist window. By default, + the taglist plugin periodically updates the taglist window to + highlight the current tag. This command can be used to force + the taglist plugin to highlight the current tag. + + *:TlistToggle* +:TlistToggle Open or close (toggle) the taglist window. Opens the taglist + window, if the window is not opened currently. Closes the + taglist window, if the taglist window is already opened. When + the taglist window is opened for the first time, all the files + in the buffer list are processed and the tags are displayed in + the taglist window. After executing this command, the cursor + is not moved from the current window to the taglist window. + + *:TlistUndebug* +:TlistUndebug + Stop logging of debug messages from the taglist plugin. + + *:TlistUnlock* +:TlistUnlock + Unlock the taglist and start processing newly edited files. + + *:TlistUpdate* +:TlistUpdate Update the tags information for the current buffer. This + command can be used to re-process the current file/buffer and + get the tags information. As the taglist plugin uses the file + saved in the disk (instead of the file displayed in a Vim + buffer), you should save a modified buffer before you update + the taglist. Otherwise the listed tags will not include the + new tags created in the buffer. You can use this command even + when the taglist window is not opened. + +============================================================================== + *taglist-functions* +8. Global functions~ + +The taglist plugin provides several global functions that can be used from +other Vim plugins to interact with the taglist plugin. These functions are +described below. + +|Tlist_Update_File_Tags()| Update the tags for the specified file +|Tlist_Get_Tag_Prototype_By_Line()| Return the prototype of the tag at or + before the specified line number in the + specified file. +|Tlist_Get_Tagname_By_Line()| Return the name of the tag at or + before the specified line number in + the specified file. +|Tlist_Set_App()| Set the name of the application + controlling the taglist window. + + *Tlist_Update_File_Tags()* +Tlist_Update_File_Tags({filename}, {filetype}) + Update the tags for the file {filename}. The second argument + specifies the Vim filetype for the file. If the taglist plugin + has not processed the file previously, then the exuberant + ctags tool is invoked to generate the tags for the file. + + *Tlist_Get_Tag_Prototype_By_Line()* +Tlist_Get_Tag_Prototype_By_Line([{filename}, {linenumber}]) + Return the prototype of the tag at or before the specified + line number in the specified file. If the filename and line + number are not specified, then the current buffer name and the + current line number are used. + + *Tlist_Get_Tagname_By_Line()* +Tlist_Get_Tagname_By_Line([{filename}, {linenumber}]) + Return the name of the tag at or before the specified line + number in the specified file. If the filename and line number + are not specified, then the current buffer name and the + current line number are used. + + *Tlist_Set_App()* +Tlist_Set_App({appname}) + Set the name of the plugin that controls the taglist plugin + window and buffer. This can be used to integrate the taglist + plugin with other Vim plugins. + + For example, the winmanager plugin and the Cream package use + this function and specify the appname as "winmanager" and + "cream" respectively. + + By default, the taglist plugin is a stand-alone plugin and + controls the taglist window and buffer. If the taglist window + is controlled by an external plugin, then the appname should + be set appropriately. + +============================================================================== + *taglist-extend* +9. Extending~ + +The taglist plugin supports all the languages supported by the exuberant ctags +tool, which includes the following languages: Assembly, ASP, Awk, Beta, C, +C++, C#, Cobol, Eiffel, Erlang, Fortran, HTML, Java, Javascript, Lisp, Lua, +Make, Pascal, Perl, PHP, Python, Rexx, Ruby, Scheme, Shell, Slang, SML, Sql, +TCL, Verilog, Vim and Yacc. + +You can extend the taglist plugin to add support for new languages and also +modify the support for the above listed languages. + +You should NOT make modifications to the taglist plugin script file to add +support for new languages. You will lose these changes when you upgrade to the +next version of the taglist plugin. Instead you should follow the below +described instructions to extend the taglist plugin. + +You can extend the taglist plugin by setting variables in the .vimrc or _vimrc +file. The name of these variables depends on the language name and is +described below. + +Modifying support for an existing language~ +To modify the support for an already supported language, you have to set the +tlist_xxx_settings variable in the ~/.vimrc or $HOME/_vimrc file. Replace xxx +with the Vim filetype name for the language file. For example, to modify the +support for the perl language files, you have to set the tlist_perl_settings +variable. To modify the support for java files, you have to set the +tlist_java_settings variable. + +To determine the filetype name used by Vim for a file, use the following +command in the buffer containing the file: + + :set filetype + +The above command will display the Vim filetype for the current buffer. + +The format of the value set in the tlist_xxx_settings variable is + + ;flag1:name1;flag2:name2;flag3:name3 + +The different fields in the value are separated by the ';' character. + +The first field 'language_name' is the name used by exuberant ctags to refer +to this language file. This name can be different from the file type name used +by Vim. For example, for C++, the language name used by ctags is 'c++' but the +filetype name used by Vim is 'cpp'. To get the list of language names +supported by exuberant ctags, use the following command: + + $ ctags --list-maps=all + +The remaining fields follow the format "flag:name". The sub-field 'flag' is +the language specific flag used by exuberant ctags to generate the +corresponding tags. For example, for the C language, to list only the +functions, the 'f' flag is used. To get the list of flags supported by +exuberant ctags for the various languages use the following command: + + $ ctags --list-kinds=all + +The sub-field 'name' specifies the title text to use for displaying the tags +of a particular type. For example, 'name' can be set to 'functions'. This +field can be set to any text string name. + +For example, to list only the classes and functions defined in a C++ language +file, add the following line to your .vimrc file: + + let tlist_cpp_settings = 'c++;c:class;f:function' + +In the above setting, 'cpp' is the Vim filetype name and 'c++' is the name +used by the exuberant ctags tool. 'c' and 'f' are the flags passed to +exuberant ctags to list C++ classes and functions and 'class' is the title +used for the class tags and 'function' is the title used for the function tags +in the taglist window. + +For example, to display only functions defined in a C file and to use "My +Functions" as the title for the function tags, use + + let tlist_c_settings = 'c;f:My Functions' + +When you set the tlist_xxx_settings variable, you will override the default +setting used by the taglist plugin for the 'xxx' language. You cannot add to +the default options used by the taglist plugin for a particular file type. To +add to the options used by the taglist plugin for a language, copy the option +values from the taglist plugin file to your .vimrc file and modify it. + +Adding support for a new language~ +If you want to add support for a new language to the taglist plugin, you need +to first extend the exuberant ctags tool. For more information about extending +exuberant ctags, visit the following page: + + http://ctags.sourceforge.net/EXTENDING.html + +To add support for a new language, set the tlist_xxx_settings variable in the +~/.vimrc file appropriately as described above. Replace 'xxx' in the variable +name with the Vim filetype name for the new language. + +For example, to extend the taglist plugin to support the latex language, you +can use the following line (assuming, you have already extended exuberant +ctags to support the latex language): + + let tlist_tex_settings='latex;b:bibitem;c:command;l:label' + +With the above line, when you edit files of filetype "tex" in Vim, the taglist +plugin will invoke the exuberant ctags tool passing the "latex" filetype and +the flags b, c and l to generate the tags. The text heading 'bibitem', +'command' and 'label' will be used in the taglist window for the tags which +are generated for the flags b, c and l respectively. + +============================================================================== + *taglist-faq* +10. Frequently Asked Questions~ + +Q. The taglist plugin doesn't work. The taglist window is empty and the tags + defined in a file are not displayed. +A. Are you using Vim version 6.0 and above? The taglist plugin relies on the + features supported by Vim version 6.0 and above. You can use the following + command to get the Vim version: +> + $ vim --version +< + Are you using exuberant ctags version 5.0 and above? The taglist plugin + relies on the features supported by exuberant ctags and will not work with + GNU ctags or the Unix ctags utility. You can use the following command to + determine whether the ctags installed in your system is exuberant ctags: +> + $ ctags --version +< + Is exuberant ctags present in one of the directories in your PATH? If not, + you need to set the Tlist_Ctags_Cmd variable to point to the location of + exuberant ctags. Use the following Vim command to verify that this is setup + correctly: +> + :echo system(Tlist_Ctags_Cmd . ' --version') +< + The above command should display the version information for exuberant + ctags. + + Did you turn on the Vim filetype detection? The taglist plugin relies on + the filetype detected by Vim and passes the filetype to the exuberant ctags + utility to parse the tags. Check the output of the following Vim command: +> + :filetype +< + The output of the above command should contain "filetype detection:ON". + To turn on the filetype detection, add the following line to the .vimrc or + _vimrc file: +> + filetype on +< + Is your version of Vim compiled with the support for the system() function? + The following Vim command should display 1: +> + :echo exists('*system') +< + In some Linux distributions (particularly Suse Linux), the default Vim + installation is built without the support for the system() function. The + taglist plugin uses the system() function to invoke the exuberant ctags + utility. You need to rebuild Vim after enabling the support for the + system() function. If you use the default build options, the system() + function will be supported. + + Do you have the |'shellslash'| option set? You can try disabling the + |'shellslash'| option. When the taglist plugin invokes the exuberant ctags + utility with the path to the file, if the incorrect slashes are used, then + you will see errors. + + Check the shell related Vim options values using the following command: +> + :set shell? shellcmdflag? shellpipe? + :set shellquote? shellredir? shellxquote? +< + If these options are set in your .vimrc or _vimrc file, try removing those + lines. + + Are you using a Unix shell in a MS-Windows environment? For example, + the Unix shell from the MKS-toolkit. Do you have the SHELL environment + set to point to this shell? You can try resetting the SHELL environment + variable. + + If you are using a Unix shell on MS-Windows, you should try to use + exuberant ctags that is compiled for Unix-like environments so that + exuberant ctags will understand path names with forward slash characters. + + Is your filetype supported by the exuberant ctags utility? The file types + supported by the exuberant ctags utility are listed in the ctags help. If a + file type is not supported, you have to extend exuberant ctags. You can use + the following command to list the filetypes supported by exuberant ctags: +> + ctags --list-languages +< + Run the following command from the shell prompt and check whether the tags + defined in your file are listed in the output from exuberant ctags: +> + ctags -f - --format=2 --excmd=pattern --fields=nks +< + If you see your tags in the output from the above command, then the + exuberant ctags utility is properly parsing your file. + + Do you have the .ctags or _ctags or the ctags.cnf file in your home + directory for specifying default options or for extending exuberant ctags? + If you do have this file, check the options in this file and make sure + these options are not interfering with the operation of the taglist plugin. + + If you are using MS-Windows, check the value of the TEMP and TMP + environment variables. If these environment variables are set to a path + with space characters in the name, then try using the DOS 8.3 short name + for the path or set them to a path without the space characters in the + name. For example, if the temporary directory name is "C:\Documents and + Settings\xyz\Local Settings\Temp", then try setting the TEMP variable to + the following: +> + set TEMP=C:\DOCUMEN~1\xyz\LOCALS~1\Temp +< + If exuberant ctags is installed in a directory with space characters in the + name, then try adding the directory to the PATH environment variable or try + setting the 'Tlist_Ctags_Cmd' variable to the shortest path name to ctags + or try copying the exuberant ctags to a path without space characters in + the name. For example, if exuberant ctags is installed in the directory + "C:\Program Files\Ctags", then try setting the 'Tlist_Ctags_Cmd' variable + as below: +> + let Tlist_Ctags_Cmd='C:\Progra~1\Ctags\ctags.exe' +< + If you are using a cygwin compiled version of exuberant ctags on MS-Windows, + make sure that either you have the cygwin compiled sort utility installed + and available in your PATH or compile exuberant ctags with internal sort + support. Otherwise, when exuberant ctags sorts the tags output by invoking + the sort utility, it may end up invoking the MS-Windows version of + sort.exe, thereby resulting in failure. + +Q. When I try to open the taglist window, I am seeing the following error + message. How do I fix this problem? + + Taglist: Failed to generate tags for /my/path/to/file + ctags: illegal option -- -^@usage: ctags [-BFadtuwvx] [-f tagsfile] file ... + +A. The taglist plugin will work only with the exuberant ctags tool. You + cannot use the GNU ctags or the Unix ctags program with the taglist plugin. + You will see an error message similar to the one shown above, if you try + use a non-exuberant ctags program with Vim. To fix this problem, either add + the exuberant ctags tool location to the PATH environment variable or set + the 'Tlist_Ctags_Cmd' variable. + +Q. A file has more than one tag with the same name. When I select a tag name + from the taglist window, the cursor is positioned at the incorrect tag + location. +A. The taglist plugin uses the search pattern generated by the exuberant ctags + utility to position the cursor at the location of a tag definition. If a + file has more than one tag with the same name and same prototype, then the + search pattern will be the same. In this case, when searching for the tag + pattern, the cursor may be positioned at the incorrect location. + +Q. I have made some modifications to my file and introduced new + functions/classes/variables. I have not yet saved my file. The taglist + plugin is not displaying the new tags when I update the taglist window. +A. The exuberant ctags utility will process only files that are present in the + disk. To list the tags defined in a file, you have to save the file and + then update the taglist window. + +Q. I have created a ctags file using the exuberant ctags utility for my source + tree. How do I configure the taglist plugin to use this tags file? +A. The taglist plugin doesn't use a tags file stored in disk. For every opened + file, the taglist plugin invokes the exuberant ctags utility to get the + list of tags dynamically. The Vim system() function is used to invoke + exuberant ctags and get the ctags output. This function internally uses a + temporary file to store the output. This file is deleted after the output + from the command is read. So you will never see the file that contains the + output of exuberant ctags. + +Q. When I set the |'updatetime'| option to a low value (less than 1000) and if + I keep pressing a key with the taglist window open, the current buffer + contents are changed. Why is this? +A. The taglist plugin uses the |CursorHold| autocmd to highlight the current + tag. The CursorHold autocmd triggers for every |'updatetime'| milliseconds. + If the |'updatetime'| option is set to a low value, then the CursorHold + autocmd will be triggered frequently. As the taglist plugin changes + the focus to the taglist window to highlight the current tag, this could + interfere with the key movement resulting in changing the contents of + the current buffer. The workaround for this problem is to not set the + |'updatetime'| option to a low value. + +============================================================================== + *taglist-license* +11. License~ +Permission is hereby granted to use and distribute the taglist plugin, with or +without modifications, provided that this copyright notice is copied with it. +Like anything else that's free, taglist.vim is provided *as is* and comes with +no warranty of any kind, either expressed or implied. In no event will the +copyright holder be liable for any damamges resulting from the use of this +software. + +============================================================================== + *taglist-todo* +12. Todo~ + +1. Group tags according to the scope and display them. For example, + group all the tags belonging to a C++/Java class +2. Support for displaying tags in a modified (not-yet-saved) file. +3. Automatically open the taglist window only for selected filetypes. + For other filetypes, close the taglist window. +4. When using the shell from the MKS toolkit, the taglist plugin + doesn't work. +5. The taglist plugin doesn't work with files edited remotely using the + netrw plugin. The exuberant ctags utility cannot process files over + scp/rcp/ftp, etc. + +============================================================================== + +vim:tw=78:ts=8:noet:ft=help: diff --git a/.vim/doc/tags b/.vim/doc/tags new file mode 100644 index 0000000..920031f --- /dev/null +++ b/.vim/doc/tags @@ -0,0 +1,229 @@ +'Tlist_Auto_Highlight_Tag' taglist.txt /*'Tlist_Auto_Highlight_Tag'* +'Tlist_Auto_Open' taglist.txt /*'Tlist_Auto_Open'* +'Tlist_Auto_Update' taglist.txt /*'Tlist_Auto_Update'* +'Tlist_Close_On_Select' taglist.txt /*'Tlist_Close_On_Select'* +'Tlist_Compact_Format' taglist.txt /*'Tlist_Compact_Format'* +'Tlist_Ctags_Cmd' taglist.txt /*'Tlist_Ctags_Cmd'* +'Tlist_Display_Prototype' taglist.txt /*'Tlist_Display_Prototype'* +'Tlist_Display_Tag_Scope' taglist.txt /*'Tlist_Display_Tag_Scope'* +'Tlist_Enable_Fold_Column' taglist.txt /*'Tlist_Enable_Fold_Column'* +'Tlist_Exit_OnlyWindow' taglist.txt /*'Tlist_Exit_OnlyWindow'* +'Tlist_File_Fold_Auto_Close' taglist.txt /*'Tlist_File_Fold_Auto_Close'* +'Tlist_GainFocus_On_ToggleOpen' taglist.txt /*'Tlist_GainFocus_On_ToggleOpen'* +'Tlist_Highlight_Tag_On_BufEnter' taglist.txt /*'Tlist_Highlight_Tag_On_BufEnter'* +'Tlist_Inc_Winwidth' taglist.txt /*'Tlist_Inc_Winwidth'* +'Tlist_Max_Submenu_Items' taglist.txt /*'Tlist_Max_Submenu_Items'* +'Tlist_Max_Tag_Length' taglist.txt /*'Tlist_Max_Tag_Length'* +'Tlist_Process_File_Always' taglist.txt /*'Tlist_Process_File_Always'* +'Tlist_Show_Menu' taglist.txt /*'Tlist_Show_Menu'* +'Tlist_Show_One_File' taglist.txt /*'Tlist_Show_One_File'* +'Tlist_Sort_Type' taglist.txt /*'Tlist_Sort_Type'* +'Tlist_Use_Horiz_Window' taglist.txt /*'Tlist_Use_Horiz_Window'* +'Tlist_Use_Right_Window' taglist.txt /*'Tlist_Use_Right_Window'* +'Tlist_Use_SingleClick' taglist.txt /*'Tlist_Use_SingleClick'* +'Tlist_WinHeight' taglist.txt /*'Tlist_WinHeight'* +'Tlist_WinWidth' taglist.txt /*'Tlist_WinWidth'* +:CVSEdit vcscommand.txt /*:CVSEdit* +:CVSEditors vcscommand.txt /*:CVSEditors* +:CVSUnedit vcscommand.txt /*:CVSUnedit* +:CVSWatch vcscommand.txt /*:CVSWatch* +:CVSWatchAdd vcscommand.txt /*:CVSWatchAdd* +:CVSWatchOff vcscommand.txt /*:CVSWatchOff* +:CVSWatchOn vcscommand.txt /*:CVSWatchOn* +:CVSWatchRemove vcscommand.txt /*:CVSWatchRemove* +:CVSWatchers vcscommand.txt /*:CVSWatchers* +:NERDTree NERD_tree.txt /*:NERDTree* +:NERDTreeToggle NERD_tree.txt /*:NERDTreeToggle* +:TlistAddFiles taglist.txt /*:TlistAddFiles* +:TlistAddFilesRecursive taglist.txt /*:TlistAddFilesRecursive* +:TlistClose taglist.txt /*:TlistClose* +:TlistDebug taglist.txt /*:TlistDebug* +:TlistHighlightTag taglist.txt /*:TlistHighlightTag* +:TlistLock taglist.txt /*:TlistLock* +:TlistMessages taglist.txt /*:TlistMessages* +:TlistOpen taglist.txt /*:TlistOpen* +:TlistSessionLoad taglist.txt /*:TlistSessionLoad* +:TlistSessionSave taglist.txt /*:TlistSessionSave* +:TlistShowPrototype taglist.txt /*:TlistShowPrototype* +:TlistShowTag taglist.txt /*:TlistShowTag* +:TlistToggle taglist.txt /*:TlistToggle* +:TlistUndebug taglist.txt /*:TlistUndebug* +:TlistUnlock taglist.txt /*:TlistUnlock* +:TlistUpdate taglist.txt /*:TlistUpdate* +:VCSAdd vcscommand.txt /*:VCSAdd* +:VCSAnnotate vcscommand.txt /*:VCSAnnotate* +:VCSBlame vcscommand.txt /*:VCSBlame* +:VCSCommit vcscommand.txt /*:VCSCommit* +:VCSDelete vcscommand.txt /*:VCSDelete* +:VCSDiff vcscommand.txt /*:VCSDiff* +:VCSGotoOriginal vcscommand.txt /*:VCSGotoOriginal* +:VCSInfo vcscommand.txt /*:VCSInfo* +:VCSLock vcscommand.txt /*:VCSLock* +:VCSLog vcscommand.txt /*:VCSLog* +:VCSRemove vcscommand.txt /*:VCSRemove* +:VCSRevert vcscommand.txt /*:VCSRevert* +:VCSReview vcscommand.txt /*:VCSReview* +:VCSStatus vcscommand.txt /*:VCSStatus* +:VCSUnlock vcscommand.txt /*:VCSUnlock* +:VCSUpdate vcscommand.txt /*:VCSUpdate* +:VCSVimDiff vcscommand.txt /*:VCSVimDiff* +NERDChristmasTree NERD_tree.txt /*NERDChristmasTree* +NERDTree NERD_tree.txt /*NERDTree* +NERDTree-! NERD_tree.txt /*NERDTree-!* +NERDTree-? NERD_tree.txt /*NERDTree-?* +NERDTree-C NERD_tree.txt /*NERDTree-C* +NERDTree-F NERD_tree.txt /*NERDTree-F* +NERDTree-H NERD_tree.txt /*NERDTree-H* +NERDTree-J NERD_tree.txt /*NERDTree-J* +NERDTree-K NERD_tree.txt /*NERDTree-K* +NERDTree-O NERD_tree.txt /*NERDTree-O* +NERDTree-P NERD_tree.txt /*NERDTree-P* +NERDTree-R NERD_tree.txt /*NERDTree-R* +NERDTree-T NERD_tree.txt /*NERDTree-T* +NERDTree-U NERD_tree.txt /*NERDTree-U* +NERDTree-X NERD_tree.txt /*NERDTree-X* +NERDTree-c-j NERD_tree.txt /*NERDTree-c-j* +NERDTree-c-k NERD_tree.txt /*NERDTree-c-k* +NERDTree-contents NERD_tree.txt /*NERDTree-contents* +NERDTree-e NERD_tree.txt /*NERDTree-e* +NERDTree-f NERD_tree.txt /*NERDTree-f* +NERDTree-go NERD_tree.txt /*NERDTree-go* +NERDTree-gtab NERD_tree.txt /*NERDTree-gtab* +NERDTree-m NERD_tree.txt /*NERDTree-m* +NERDTree-o NERD_tree.txt /*NERDTree-o* +NERDTree-p NERD_tree.txt /*NERDTree-p* +NERDTree-q NERD_tree.txt /*NERDTree-q* +NERDTree-r NERD_tree.txt /*NERDTree-r* +NERDTree-t NERD_tree.txt /*NERDTree-t* +NERDTree-tab NERD_tree.txt /*NERDTree-tab* +NERDTree-u NERD_tree.txt /*NERDTree-u* +NERDTree-x NERD_tree.txt /*NERDTree-x* +NERDTreeAuthor NERD_tree.txt /*NERDTreeAuthor* +NERDTreeAutoCenter NERD_tree.txt /*NERDTreeAutoCenter* +NERDTreeAutoCenterThreshold NERD_tree.txt /*NERDTreeAutoCenterThreshold* +NERDTreeCaseSensitiveSort NERD_tree.txt /*NERDTreeCaseSensitiveSort* +NERDTreeChDirMode NERD_tree.txt /*NERDTreeChDirMode* +NERDTreeChangelog NERD_tree.txt /*NERDTreeChangelog* +NERDTreeCommands NERD_tree.txt /*NERDTreeCommands* +NERDTreeCredits NERD_tree.txt /*NERDTreeCredits* +NERDTreeFilesysMenu NERD_tree.txt /*NERDTreeFilesysMenu* +NERDTreeFunctionality NERD_tree.txt /*NERDTreeFunctionality* +NERDTreeHighlightCursorline NERD_tree.txt /*NERDTreeHighlightCursorline* +NERDTreeIgnore NERD_tree.txt /*NERDTreeIgnore* +NERDTreeMappings NERD_tree.txt /*NERDTreeMappings* +NERDTreeMouseMode NERD_tree.txt /*NERDTreeMouseMode* +NERDTreeOptionDetails NERD_tree.txt /*NERDTreeOptionDetails* +NERDTreeOptionSummary NERD_tree.txt /*NERDTreeOptionSummary* +NERDTreeOptions NERD_tree.txt /*NERDTreeOptions* +NERDTreePublicFunctions NERD_tree.txt /*NERDTreePublicFunctions* +NERDTreeShowFiles NERD_tree.txt /*NERDTreeShowFiles* +NERDTreeShowHidden NERD_tree.txt /*NERDTreeShowHidden* +NERDTreeSortOrder NERD_tree.txt /*NERDTreeSortOrder* +NERDTreeSplitVertical NERD_tree.txt /*NERDTreeSplitVertical* +NERDTreeTodo NERD_tree.txt /*NERDTreeTodo* +NERDTreeWinPos NERD_tree.txt /*NERDTreeWinPos* +NERDTreeWinSize NERD_tree.txt /*NERDTreeWinSize* +NERD_tree.txt NERD_tree.txt /*NERD_tree.txt* +OmniCpp_DefaultNamespaces omnicppcomplete.txt /*OmniCpp_DefaultNamespaces* +OmniCpp_DisplayMode omnicppcomplete.txt /*OmniCpp_DisplayMode* +OmniCpp_GlobalScopeSearch omnicppcomplete.txt /*OmniCpp_GlobalScopeSearch* +OmniCpp_LocalSearchDecl omnicppcomplete.txt /*OmniCpp_LocalSearchDecl* +OmniCpp_MayCompleteArrow omnicppcomplete.txt /*OmniCpp_MayCompleteArrow* +OmniCpp_MayCompleteDot omnicppcomplete.txt /*OmniCpp_MayCompleteDot* +OmniCpp_MayCompleteScope omnicppcomplete.txt /*OmniCpp_MayCompleteScope* +OmniCpp_NamespaceSearch omnicppcomplete.txt /*OmniCpp_NamespaceSearch* +OmniCpp_SelectFirstItem omnicppcomplete.txt /*OmniCpp_SelectFirstItem* +OmniCpp_ShowAccess omnicppcomplete.txt /*OmniCpp_ShowAccess* +OmniCpp_ShowPrototypeInAbbr omnicppcomplete.txt /*OmniCpp_ShowPrototypeInAbbr* +OmniCpp_ShowScopeInAbbr omnicppcomplete.txt /*OmniCpp_ShowScopeInAbbr* +Tlist_Get_Tag_Prototype_By_Line() taglist.txt /*Tlist_Get_Tag_Prototype_By_Line()* +Tlist_Get_Tagname_By_Line() taglist.txt /*Tlist_Get_Tagname_By_Line()* +Tlist_Set_App() taglist.txt /*Tlist_Set_App()* +Tlist_Update_File_Tags() taglist.txt /*Tlist_Update_File_Tags()* +VCSCommandCVSDiffOpt vcscommand.txt /*VCSCommandCVSDiffOpt* +VCSCommandCVSExec vcscommand.txt /*VCSCommandCVSExec* +VCSCommandCommitOnWrite vcscommand.txt /*VCSCommandCommitOnWrite* +VCSCommandDeleteOnHide vcscommand.txt /*VCSCommandDeleteOnHide* +VCSCommandDiffSplit vcscommand.txt /*VCSCommandDiffSplit* +VCSCommandDisableExtensionMappings vcscommand.txt /*VCSCommandDisableExtensionMappings* +VCSCommandDisableMappings vcscommand.txt /*VCSCommandDisableMappings* +VCSCommandEdit vcscommand.txt /*VCSCommandEdit* +VCSCommandEnableBufferSetup vcscommand.txt /*VCSCommandEnableBufferSetup* +VCSCommandResultBufferNameExtension vcscommand.txt /*VCSCommandResultBufferNameExtension* +VCSCommandResultBufferNameFunction vcscommand.txt /*VCSCommandResultBufferNameFunction* +VCSCommandSVKExec vcscommand.txt /*VCSCommandSVKExec* +VCSCommandSVNDiffExt vcscommand.txt /*VCSCommandSVNDiffExt* +VCSCommandSVNDiffOpt vcscommand.txt /*VCSCommandSVNDiffOpt* +VCSCommandSVNExec vcscommand.txt /*VCSCommandSVNExec* +VCSCommandSplit vcscommand.txt /*VCSCommandSplit* +b:VCSCommandCommand vcscommand.txt /*b:VCSCommandCommand* +b:VCSCommandOriginalBuffer vcscommand.txt /*b:VCSCommandOriginalBuffer* +b:VCSCommandSourceFile vcscommand.txt /*b:VCSCommandSourceFile* +b:VCSCommandVCSType vcscommand.txt /*b:VCSCommandVCSType* +cvscommand-changes vcscommand.txt /*cvscommand-changes* +loaded_nerd_tree NERD_tree.txt /*loaded_nerd_tree* +omnicpp-download omnicppcomplete.txt /*omnicpp-download* +omnicpp-faq omnicppcomplete.txt /*omnicpp-faq* +omnicpp-features omnicppcomplete.txt /*omnicpp-features* +omnicpp-history omnicppcomplete.txt /*omnicpp-history* +omnicpp-installation omnicppcomplete.txt /*omnicpp-installation* +omnicpp-limitations omnicppcomplete.txt /*omnicpp-limitations* +omnicpp-may-complete omnicppcomplete.txt /*omnicpp-may-complete* +omnicpp-options omnicppcomplete.txt /*omnicpp-options* +omnicpp-overview omnicppcomplete.txt /*omnicpp-overview* +omnicpp-popup omnicppcomplete.txt /*omnicpp-popup* +omnicpp-thanks omnicppcomplete.txt /*omnicpp-thanks* +omnicppcomplete omnicppcomplete.txt /*omnicppcomplete* +omnicppcomplete.txt omnicppcomplete.txt /*omnicppcomplete.txt* +project project.txt /*project* +project-adding-mappings project.txt /*project-adding-mappings* +project-example project.txt /*project-example* +project-flags project.txt /*project-flags* +project-inheritance project.txt /*project-inheritance* +project-invoking project.txt /*project-invoking* +project-mappings project.txt /*project-mappings* +project-plugin project.txt /*project-plugin* +project-settings project.txt /*project-settings* +project-syntax project.txt /*project-syntax* +project-tips project.txt /*project-tips* +project.txt project.txt /*project.txt* +taglist-commands taglist.txt /*taglist-commands* +taglist-debug taglist.txt /*taglist-debug* +taglist-extend taglist.txt /*taglist-extend* +taglist-faq taglist.txt /*taglist-faq* +taglist-functions taglist.txt /*taglist-functions* +taglist-install taglist.txt /*taglist-install* +taglist-internet taglist.txt /*taglist-internet* +taglist-intro taglist.txt /*taglist-intro* +taglist-keys taglist.txt /*taglist-keys* +taglist-license taglist.txt /*taglist-license* +taglist-menu taglist.txt /*taglist-menu* +taglist-options taglist.txt /*taglist-options* +taglist-requirements taglist.txt /*taglist-requirements* +taglist-session taglist.txt /*taglist-session* +taglist-todo taglist.txt /*taglist-todo* +taglist-using taglist.txt /*taglist-using* +taglist.txt taglist.txt /*taglist.txt* +vcscommand vcscommand.txt /*vcscommand* +vcscommand-buffer-management vcscommand.txt /*vcscommand-buffer-management* +vcscommand-buffer-variables vcscommand.txt /*vcscommand-buffer-variables* +vcscommand-bugs vcscommand.txt /*vcscommand-bugs* +vcscommand-commands vcscommand.txt /*vcscommand-commands* +vcscommand-config vcscommand.txt /*vcscommand-config* +vcscommand-contents vcscommand.txt /*vcscommand-contents* +vcscommand-customize vcscommand.txt /*vcscommand-customize* +vcscommand-events vcscommand.txt /*vcscommand-events* +vcscommand-install vcscommand.txt /*vcscommand-install* +vcscommand-intro vcscommand.txt /*vcscommand-intro* +vcscommand-manual vcscommand.txt /*vcscommand-manual* +vcscommand-mappings vcscommand.txt /*vcscommand-mappings* +vcscommand-mappings-override vcscommand.txt /*vcscommand-mappings-override* +vcscommand-naming vcscommand.txt /*vcscommand-naming* +vcscommand-options vcscommand.txt /*vcscommand-options* +vcscommand-ssh vcscommand.txt /*vcscommand-ssh* +vcscommand-ssh-config vcscommand.txt /*vcscommand-ssh-config* +vcscommand-ssh-env vcscommand.txt /*vcscommand-ssh-env* +vcscommand-ssh-other vcscommand.txt /*vcscommand-ssh-other* +vcscommand-ssh-wrapper vcscommand.txt /*vcscommand-ssh-wrapper* +vcscommand-statusline vcscommand.txt /*vcscommand-statusline* +vcscommand.txt vcscommand.txt /*vcscommand.txt* diff --git a/.vim/doc/vcscommand.txt b/.vim/doc/vcscommand.txt new file mode 100644 index 0000000..0c16aac --- /dev/null +++ b/.vim/doc/vcscommand.txt @@ -0,0 +1,771 @@ +*vcscommand.txt* vcscommand +Copyright (c) 2007 Bob Hiestand + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +For instructions on installing this file, type + :help add-local-help +inside Vim. + +Author: Bob Hiestand +Credits: Benji Fisher's excellent MatchIt documentation + +============================================================================== +1. Contents *vcscommand-contents* + + Installation : |vcscommand-install| + vcscommand Intro : |vcscommand| + vcscommand Manual : |vcscommand-manual| + Customization : |vcscommand-customize| + SSH "integration" : |vcscommand-ssh| + Changes from cvscommand : |cvscommand-changes| + Bugs : |vcscommand-bugs| + +============================================================================== + +2. vcscommand Installation *vcscommand-install* + +The vcscommand plugin comprises five files: vcscommand.vim, vcssvn.vim, +vcscvs.vim, vcssvk.vim and vcscommand.txt (this file). In order to install +the plugin, place the vcscommand.vim, vcssvn.vim, vcssvk.vim, and vcscvs.vim +files into a plugin directory in your runtime path (please see +|add-global-plugin| and |'runtimepath'|. + +This help file can be included in the VIM help system by copying it into a +'doc' directory in your runtime path and then executing the |:helptags| +command, specifying the full path of the 'doc' directory. Please see +|add-local-help| for more details. + +vcscommand may be customized by setting variables, creating maps, and +specifying event handlers. Please see |vcscommand-customize| for more +details. + +============================================================================== + +3. vcscommand Intro *vcscommand* + *vcscommand-intro* + +The vcscommand plugin provides global ex commands for manipulating +version-controlled source files, currently those controlled either by CVS or +Subversion. In general, each command operates on the current buffer and +accomplishes a separate source control function, such as update, commit, log, +and others (please see |vcscommand-commands| for a list of all available +commands). The results of each operation are displayed in a scratch buffer. +Several buffer variables are defined for those scratch buffers (please see +|vcscommand-buffer-variables|). + +The notion of "current file" means either the current buffer, or, in the case +of a directory buffer (such as Explorer or netrw buffers), the directory (and +all subdirectories) represented by the the buffer. + +For convenience, any vcscommand invoked on a vcscommand scratch buffer acts as +though it was invoked on the original file and splits the screen so that the +output appears in a new window. + +Many of the commands accept revisions as arguments. By default, most operate +on the most recent revision on the current branch if no revision is specified. + +Each vcscommand is mapped to a key sequence starting with the +keystroke. The default mappings may be overridden by supplying different +mappings before the plugin is loaded, such as in the vimrc, in the standard +fashion for plugin mappings. For examples, please see +|vcscommand-mappings-override|. + +The vcscommand plugin may be configured in several ways. For more details, +please see |vcscommand-customize|. + +============================================================================== + +4. vcscommand Manual *vcscommand-manual* + +4.1 vcscommand commands *vcscommand-commands* + +vcscommand defines the following commands: + +|:VCSAdd| +|:VCSAnnotate| +|:VCSBlame| +|:VCSCommit| +|:VCSDelete| +|:VCSDiff| +|:VCSGotoOriginal| +|:VCSLog| +|:VCSRemove| +|:VCSRevert| +|:VCSReview| +|:VCSStatus| +|:VCSUpdate| +|:VCSVimDiff| + +The following commands are specific to CVS files: + +|:CVSEdit| +|:CVSEditors| +|:CVSUnedit| +|:CVSWatch| +|:CVSWatchAdd| +|:CVSWatchOn| +|:CVSWatchOff| +|:CVSWatchRemove| +|:CVSWatchers| + +:VCSAdd *:VCSAdd* + +This command adds the current file to source control. Please note, this does +not commit the newly-added file. All parameters to the command are passed to +the underlying VCS. + +:VCSAnnotate *:VCSAnnotate* + +This command displays the current file with each line annotated with the +version in which it was most recently changed. If an argument is given, the +argument is used as a revision number to display. If not given an argument, +it uses the most recent version of the file (on the current branch, if under +CVS control). Additionally, if the current buffer is a VCSAnnotate buffer +already, the version number on the current line is used. + +For CVS buffers, the 'VCSCommandCVSAnnotateParent' option, if set to non-zero, +will cause the above behavior to change. Instead of annotating the version on +the current line, the parent revision is used instead, crossing branches if +necessary. + +The filetype of the vcscommand scratch buffer is set to one of 'CVSAnnotate', +'SVNAnnotate', or 'SVKAnnotate' as appropriate, to take advantage of the +bundled syntax files. + +:VCSBlame *:VCSBlame* + +Alias for |:VCSAnnotate|. + +:VCSCommit[!] *:VCSCommit* + +This command commits changes to the current file to source control. + +If called with arguments, the arguments are the log message. + +If '!' is used, an empty log message is committed. + +If called with no arguments, this is a two-step command. The first step opens +a buffer to accept a log message. When that buffer is written, it is +automatically closed and the file is committed using the information from that +log message. The commit can be abandoned if the log message buffer is deleted +or wiped before being written. + +Alternatively, the mapping that is used to invoke :VCSCommit (by default +cc) can be used in the log message buffer to immediately commit. This +is useful if the |VCSCommandCommitOnWrite| variable is set to 0 to disable the +normal commit-on-write behavior. + +:VCSDelete *:VCSDelete* + +Deletes the current file and removes it from source control. All parameters +to the command are passed to the underlying VCS. + +:VCSDiff *:VCSDiff* + +With no arguments, this displays the differences between the current file and +its parent version under source control in a new scratch buffer. + +With one argument, the diff is performed on the current file against the +specified revision. + +With two arguments, the diff is performed between the specified revisions of +the current file. + +For CVS, this command uses the |VCSCommandCVSDiffOpt| variable to specify diff +options. If that variable does not exist, a plugin-specific default is used. +If you wish to have no options, then set it to the empty string. + +For SVN, this command uses the |VCSCommandSVNDiffOpt| variable to specify diff +options. If that variable does not exist, the SVN default is used. +Additionally, |VCSCommandSVNDiffExt| can be used to select an external diff +application. + +:VCSGotoOriginal *:VCSGotoOriginal* + +This command jumps to the source buffer if the current buffer is a VCS scratch +buffer. + +:VCSGotoOriginal! + +Like ":VCSGotoOriginal" but also executes :bufwipeout on all VCS scrach +buffers associated with the original file. + +:VCSInfo *:VCSInfo* + +This command displays extended information about the current file in a new +scratch buffer. + +:VCSLock *:VCSLock* + +This command locks the current file in order to prevent other users from +concurrently modifying it. The exact semantics of this command depend on the +underlying VCS. This does nothing in CVS. All parameters are passed to the +underlying VCS. + +:VCSLog *:VCSLog* + +Displays the version history of the current file in a new scratch buffer. If +there is one parameter supplied, it is taken as as a revision parameters to be +passed through to the underlying VCS. Otherwise, all parameters are passed to +the underlying VCS. + +:VCSRemove *:VCSRemove* + +Alias for |:VCSDelete|. + +:VCSRevert *:VCSRevert* + +This command replaces the current file with the most recent version from the +repository in order to wipe out any undesired changes. + +:VCSReview *:VCSReview* + +Displays a particular version of the current file in a new scratch buffer. If +no argument is given, the most recent version of the file on the current +branch is retrieved. + +:VCSStatus *:VCSStatus* + +Displays versioning information about the current file in a new scratch +buffer. All parameters are passed to the underlying VCS. + + +:VCSUnlock *:VCSUnlock* + +Unlocks the current file in order to allow other users from concurrently +modifying it. The exact semantics of this command depend on the underlying +VCS. All parameters are passed to the underlying VCS. + +:VCSUpdate *:VCSUpdate* + +Updates the current file with any relevant changes from the repository. This +intentionally does not automatically reload the current buffer, though vim +should prompt the user to do so if the underlying file is altered by this +command. + +:VCSVimDiff *:VCSVimDiff* + +Uses vimdiff to display differences between versions of the current file. + +If no revision is specified, the most recent version of the file on the +current branch is used. With one argument, that argument is used as the +revision as above. With two arguments, the differences between the two +revisions is displayed using vimdiff. + +With either zero or one argument, the original buffer is used to perform the +vimdiff. When the scratch buffer is closed, the original buffer will be +returned to normal mode. + +Once vimdiff mode is started using the above methods, additional vimdiff +buffers may be added by passing a single version argument to the command. +There may be up to 4 vimdiff buffers total. + +Using the 2-argument form of the command resets the vimdiff to only those 2 +versions. Additionally, invoking the command on a different file will close +the previous vimdiff buffers. + +:CVSEdit *:CVSEdit* + +This command performs "cvs edit" on the current file. Yes, the output buffer +in this case is almost completely useless. + +:CVSEditors *:CVSEditors* + +This command performs "cvs edit" on the current file. + +:CVSUnedit *:CVSUnedit* + +Performs "cvs unedit" on the current file. Again, yes, the output buffer here +is basically useless. + +:CVSWatch *:CVSWatch* + +This command takes an argument which must be one of [on|off|add|remove]. The +command performs "cvs watch" with the given argument on the current file. + +:CVSWatchAdd *:CVSWatchAdd* + +This command is an alias for ":CVSWatch add" + +:CVSWatchOn *:CVSWatchOn* + +This command is an alias for ":CVSWatch on" + +:CVSWatchOff *:CVSWatchOff* + +This command is an alias for ":CVSWatch off" + +:CVSWatchRemove *:CVSWatchRemove* + +This command is an alias for ":CVSWatch remove" + +:CVSWatchers *:CVSWatchers* + +This command performs "cvs watchers" on the current file. + +4.2 Mappings *vcscommand-mappings* + +By default, a mapping is defined for each command. These mappings execute the +default (no-argument) form of each command. + +ca VCSAdd +cn VCSAnnotate +cc VCSCommit +cD VCSDelete +cd VCSDiff +cg VCSGotoOriginal +cG VCSGotoOriginal! +ci VCSInfo +cl VCSLog +cL VCSLock +cr VCSReview +cs VCSStatus +cu VCSUpdate +cU VCSUnlock +cv VCSVimDiff + +Only for CVS buffers: + +ce CVSEdit +cE CVSEditors +ct CVSUnedit +cwv CVSWatchers +cwa CVSWatchAdd +cwn CVSWatchOn +cwf CVSWatchOff +cwf CVSWatchRemove + + *vcscommand-mappings-override* + +The default mappings can be overriden by user-provided instead by mapping to +CommandName. This is especially useful when these mappings collide with +other existing mappings (vim will warn of this during plugin initialization, +but will not clobber the existing mappings). + +For instance, to override the default mapping for :VCSAdd to set it to '\add', +add the following to the vimrc: + +nmap \add VCSAdd + +4.3 Automatic buffer variables *vcscommand-buffer-variables* + +Several buffer variables are defined in each vcscommand result buffer. These +may be useful for additional customization in callbacks defined in the event +handlers (please see |vcscommand-events|). + +The following variables are automatically defined: + +b:VCSCommandOriginalBuffer *b:VCSCommandOriginalBuffer* + +This variable is set to the buffer number of the source file. + +b:VCSCommandCommand *b:VCSCommandCommand* + +This variable is set to the name of the vcscommand that created the result +buffer. + +b:VCSCommandSourceFile *b:VCSCommandSourceFile* + +This variable is set to the name of the original file under source control. + +b:VCSCommandVCSType *b:VCSCommandVCSType* + +This variable is set to the type of the source control. This variable is also +set on the original file itself. +============================================================================== + +5. Configuration and customization *vcscommand-customize* + *vcscommand-config* + +The vcscommand plugin can be configured in several ways: by setting +configuration variables (see |vcscommand-options|) or by defining vcscommand +event handlers (see |vcscommand-events|). Additionally, the vcscommand plugin +supports a customized status line (see |vcscommand-statusline| and +|vcscommand-buffer-management|). + +5.1 vcscommand configuration variables *vcscommand-options* + +Several variables affect the plugin's behavior. These variables are checked +at time of execution, and may be defined at the window, buffer, or global +level and are checked in that order of precedence. + + +The following variables are available: + +|VCSCommandCommitOnWrite| +|VCSCommandCVSDiffOpt| +|VCSCommandCVSExec| +|VCSCommandDeleteOnHide| +|VCSCommandDiffSplit| +|VCSCommandDisableMappings| +|VCSCommandDisableExtensionMappings| +|VCSCommandEdit| +|VCSCommandEnableBufferSetup| +|VCSCommandResultBufferNameExtension| +|VCSCommandResultBufferNameFunction| +|VCSCommandSplit| +|VCSCommandSVKExec| +|VCSCommandSVNDiffExt| +|VCSCommandSVNDiffOpt| +|VCSCommandSVNExec| + +VCSCommandCommitOnWrite *VCSCommandCommitOnWrite* + +This variable, if set to a non-zero value, causes the pending commit +to take place immediately as soon as the log message buffer is written. +If set to zero, only the VCSCommit mapping will cause the pending commit to +occur. If not set, it defaults to 1. + +VCSCommandCVSExec *VCSCommandCVSExec* + +This variable controls the executable used for all CVS commands If not set, +it defaults to "cvs". + +VCSCommandDeleteOnHide *VCSCommandDeleteOnHide* + +This variable, if set to a non-zero value, causes the temporary result buffers +to automatically delete themselves when hidden. + +VCSCommandCVSDiffOpt *VCSCommandCVSDiffOpt* + +This variable, if set, determines the options passed to the diff command of +CVS. If not set, it defaults to 'u'. + +VCSCommandDiffSplit *VCSCommandDiffSplit* + +This variable overrides the |VCSCommandSplit| variable, but only for buffers +created with |:VCSVimDiff|. + +VCSCommandDisableMappings *VCSCommandDisableMappings* + +This variable, if set to a non-zero value, prevents the default command +mappings from being set. This supercedes +|VCSCommandDisableExtensionMappings|. + +VCSCommandDisableExtensionMappings *VCSCommandDisableExtensionMappings* + +This variable, if set to a non-zero value, prevents the default command +mappings from being set for commands specific to an individual VCS. + +VCSCommandEdit *VCSCommandEdit* + +This variable controls whether the original buffer is replaced ('edit') or +split ('split'). If not set, it defaults to 'split'. + +VCSCommandEnableBufferSetup *VCSCommandEnableBufferSetup* + +This variable, if set to a non-zero value, activates VCS buffer management +mode see (|vcscommand-buffer-management|). This mode means that the +'VCSCommandBufferInfo' variable is filled with version information if the file +is VCS-controlled. This is useful for displaying version information in the +status bar. + +VCSCommandResultBufferNameExtension *VCSCommandResultBufferNameExtension* + +This variable, if set to a non-blank value, is appended to the name of the VCS +command output buffers. For example, '.vcs'. Using this option may help +avoid problems caused by autocommands dependent on file extension. + +VCSCommandResultBufferNameFunction *VCSCommandResultBufferNameFunction* + +This variable, if set, specifies a custom function for naming VCS command +output buffers. This function is expected to return the new buffer name, and +will be passed the following arguments: + + command - name of the VCS command being executed (such as 'Log' or + 'Diff'). + + originalBuffer - buffer number of the source file. + + vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN'). + + statusText - extra text associated with the VCS action (such as version + numbers). + +VCSCommandSplit *VCSCommandSplit* + +This variable controls the orientation of the various window splits that +may occur. + +If set to 'horizontal', the resulting windows will be on stacked on top of +one another. If set to 'vertical', the resulting windows will be +side-by-side. If not set, it defaults to 'horizontal' for all but +VCSVimDiff windows. + +VCSCommandSVKExec *VCSCommandSVKExec* + +This variable controls the executable used for all SVK commands If not set, +it defaults to "svk". + +VCSCommandSVNDiffExt *VCSCommandSVNDiffExt* + +This variable, if set, is passed to SVN via the --diff-cmd command to select +an external application for performing the diff. + +VCSCommandSVNDiffOpt *VCSCommandSVNDiffOpt* + +This variable, if set, determines the options passed with the '-x' parameter +to the SVN diff command. If not set, no options are passed. + +VCSCommandSVNExec *VCSCommandSVNExec* + +This variable controls the executable used for all SVN commands If not set, +it defaults to "svn". + +5.2 VCSCommand events *vcscommand-events* + +For additional customization, vcscommand can trigger user-defined events. +Event handlers are provided by defining User event autocommands (see +|autocommand|, |User|) in the vcscommand group with patterns matching the +event name. + +For instance, the following could be added to the vimrc to provide a 'q' +mapping to quit a vcscommand scratch buffer: + +augroup VCSCommand + au User VCSBufferCreated silent! nmap q: bwipeout +augroup END + +The following hooks are available: + +VCSBufferCreated This event is fired just after a vcscommand + result buffer is created and populated. It is + executed within the context of the vcscommand + buffer. The vcscommand buffer variables may + be useful for handlers of this event (please + see |vcscommand-buffer-variables|). + +VCSBufferSetup This event is fired just after vcscommand buffer + setup occurs, if enabled. + +VCSPluginInit This event is fired when the vcscommand plugin + first loads. + +VCSPluginFinish This event is fired just after the vcscommand + plugin loads. + +VCSVimDiffFinish This event is fired just after the VCSVimDiff + command executes to allow customization of, + for instance, window placement and focus. + +Additionally, there is another hook which is used internally to handle loading +the multiple scripts in order. This hook should probably not be used by an +end user without a good idea of how it works. Among other things, any events +associated with this hook are cleared after they are executed (during +vcscommand.vim script initialization). + +VCSLoadExtensions This event is fired just before the + VCSPluginFinish. It is used internally to + execute any commands from the VCS + implementation plugins that needs to be + deferred until the primary plugin is + initialized. + +5.3 vcscommand buffer naming *vcscommand-naming* + +vcscommand result buffers use the following naming convention: +[{VCS type} {VCS command} {Source file name}] + +If additional buffers are created that would otherwise conflict, a +distinguishing number is added: + +[{VCS type} {VCS command} {Source file name}] (1,2, etc) + +5.4 vcscommand status line support *vcscommand-statusline* + +It is intended that the user will customize the |'statusline'| option to +include vcscommand result buffer attributes. A sample function that may be +used in the |'statusline'| option is provided by the plugin, +VCSCommandGetStatusLine(). In order to use that function in the status line, do +something like the following: + +set statusline=%<%f\ %{VCSCommandGetStatusLine()}\ %h%m%r%=%l,%c%V\ %P + +of which %{VCSCommandGetStatusLine()} is the relevant portion. + +The sample VCSCommandGetStatusLine() function handles both vcscommand result +buffers and VCS-managed files if vcscommand buffer management is enabled +(please see |vcscommand-buffer-management|). + +5.5 vcscommand buffer management *vcscommand-buffer-management* + +The vcscommand plugin can operate in buffer management mode, which means that +it attempts to set a buffer variable ('VCSCommandBufferInfo') upon entry into +a buffer. This is rather slow because it means that the VCS will be invoked +at each entry into a buffer (during the |BufEnter| autocommand). + +This mode is disabled by default. In order to enable it, set the +|VCSCommandEnableBufferSetup| variable to a true (non-zero) value. Enabling +this mode simply provides the buffer variable mentioned above. The user must +explicitly include information from the variable in the |'statusline'| option +if they are to appear in the status line (but see |vcscommand-statusline| for +a simple way to do that). + +The 'VCSCommandBufferInfo' variable is a list which contains, in order, the +revision of the current file, the latest revision of the file in the +repository, and (for CVS) the name of the branch. If those values cannot be +determined, the list is a single element: 'Unknown'. + +============================================================================== + +6. SSH "integration" *vcscommand-ssh* + +The following instructions are intended for use in integrating the +vcscommand.vim plugin with an SSH-based CVS environment. + +Familiarity with SSH and CVS are assumed. + +These instructions assume that the intent is to have a message box pop up in +order to allow the user to enter a passphrase. If, instead, the user is +comfortable using certificate-based authentication, then only instructions +6.1.1 and 6.1.2 (and optionally 6.1.4) need to be followed; ssh should then +work transparently. + +6.1 Environment settings *vcscommand-ssh-env* + +6.1.1 CVSROOT should be set to something like: + + :ext:user@host:/path_to_repository + +6.1.2 CVS_RSH should be set to: + + ssh + + Together, those settings tell CVS to use ssh as the transport when + performing CVS calls. + +6.1.3 SSH_ASKPASS should be set to the password-dialog program. In my case, + running gnome, it's set to: + + /usr/libexec/openssh/gnome-ssh-askpass + + This tells SSH how to get passwords if no input is available. + +6.1.4 OPTIONAL. You may need to set SSH_SERVER to the location of the cvs + executable on the remote (server) machine. + +6.2 CVS wrapper program *vcscommand-ssh-wrapper* + +Now you need to convince SSH to use the password-dialog program. This means +you need to execute SSH (and therefore CVS) without standard input. The +following script is a simple perl wrapper that dissasociates the CVS command +from the current terminal. Specific steps to do this may vary from system to +system; the following example works for me on linux. + +#!/usr/bin/perl -w +use strict; +use POSIX qw(setsid); +open STDIN, '/dev/null'; +fork and do {wait; exit;}; +setsid; +exec('cvs', @ARGV); + +6.3 Configuring vcscommand.vim *vcscommand-ssh-config* + +At this point, you should be able to use your wrapper script to invoke CVS with +various commands, and get the password dialog. All that's left is to make CVS +use your newly-created wrapper script. + +6.3.1 Tell vcscommand.vim what CVS executable to use. The easiest way to do this + is globally, by putting the following in your .vimrc: + + let VCSCommandCVSExec=/path/to/cvs/wrapper/script + +6.4 Where to go from here *vcscommand-ssh-other* + +The script given above works even when non-SSH CVS connections are used, +except possibly when interactively entering the message for CVS commit log +(depending on the editor you use... VIM works fine). Since the vcscommand.vim +plugin handles that message without a terminal, the wrapper script can be used +all the time. + +This allows mixed-mode operation, where some work is done with SSH-based CVS +repositories, and others with pserver or local access. + +It is possible, though beyond the scope of the plugin, to dynamically set the +CVS executable based on the CVSROOT for the file being edited. The user +events provided (such as VCSBufferCreated and VCSBufferSetup) can be used to +set a buffer-local value (b:VCSCommandCVSExec) to override the CVS executable +on a file-by-file basis. Alternatively, much the same can be done (less +automatically) by the various project-oriented plugins out there. + +It is highly recommended for ease-of-use that certificates with no passphrase +or ssh-agent are employed so that the user is not given the password prompt +too often. + +============================================================================== + +7. Changes from cvscommandi *cvscommand-changes* + +1. Require Vim 7 in order to leverage several convenient features; also +because I wanted to play with Vim 7. + +2. Renamed commands to start with 'VCS' instead of 'CVS'. The exceptions are +the 'CVSEdit' and 'CVSWatch' family of commands, which are specific to CVS. + +3. Renamed options, events to start with 'VCSCommand'. + +4. Removed option to jump to the parent version of the current line in an +annotated buffer, as opposed to the version on the current line. This made +little sense in the branching scheme used by subversion, where jumping to a +parent branch required finding a different location in the repository. It +didn't work consistently in CVS anyway. + +5. Removed option to have nameless scratch buffers. + +6. Changed default behavior of scratch buffers to split the window instead of +displaying in the current window. This may still be overridden using the +'VCSCommandEdit' option. + +7. Split plugin into multiple plugins. + +8. Added 'VCSLock' and 'VCSUnlock' commands. These are implemented for +subversion but not for CVS. These were not kept specific to subversion as they +seemed more general in nature and more likely to be supported by any future VCS +supported by this plugin. + +9. Changed name of buffer variables set by commands. + +'b:cvsOrigBuffNR' became 'b:VCSCommandOriginalBuffer' +'b:cvscmd' became 'b:VCSCommandCommand' + +10. Added new automatic variables to command result buffers. + +'b:VCSCommandSourceFile' +'b:VCSCommandVCSType' + +============================================================================== + +8. Known bugs *vcscommand-bugs* + +Please let me know if you run across any. + +CVSUnedit may, if a file is changed from the repository, provide prompt text +to determine whether the changes should be thrown away. Currently, that text +shows up in the CVS result buffer as information; there is no way for the user +to actually respond to the prompt and the CVS unedit command does nothing. If +this really bothers anyone, please let me know. + +VCSVimDiff, when using the original (real) source buffer as one of the diff +buffers, uses some hacks to try to restore the state of the original buffer +when the scratch buffer containing the other version is destroyed. There may +still be bugs in here, depending on many configuration details. + +vim:tw=78:ts=8:ft=help diff --git a/.vim/ftplugin/git.vim b/.vim/ftplugin/git.vim new file mode 100644 index 0000000..e8957a2 --- /dev/null +++ b/.vim/ftplugin/git.vim @@ -0,0 +1,70 @@ +"============================================================================= +" Copyright: Copyright © Pierre Habouzit +" Permission is hereby granted to use and distribute this code, +" with or without modifications, provided that this copyright +" notice is copied with it. Like anything else that's free, +" bufexplorer.vim is provided *as is* and comes with no +" warranty of any kind, either expressed or implied. In no +" event will the copyright holder be liable for any damages +" resulting from the use of this software. +" Description: git-commit(1) helper +" Maintainer: Pierre Habouzit +" Last Changed: Mon, 26 Nov 2007 10:06:15 +0100 +" Usage: This file should live in your ftplugin directory. +" +" The configurations variables are: +" +" g:git_diff_opts - options to add to git diff, +" (default "-C -C") +" g:git_diff_spawn_mode - use auto-split on commit ? +" * 1 == hsplit +" * 2 == vsplit +" * none else (default) +" +" The default keymaping is: +" +" gd - view the diff in a hsplit +" ghd - view the diff in a hsplit +" gvd - view the diff in a vsplit +"========================================================================={{{= + +if exists("b:did_ftplugin") | finish | endif + +let b:did_ftplugin = 1 + +setlocal tw=74 +setlocal nowarn nowb + +function! Git_diff_windows(vertsplit, auto, opts) + if a:vertsplit + rightbelow vnew + else + rightbelow new + endif + silent! setlocal ft=diff previewwindow bufhidden=delete nobackup noswf nobuflisted nowrap buftype=nofile + exe "normal :r!LANG=C git diff --stat -p --cached ".a:opts."\no\1GddO\" + setlocal nomodifiable + noremap q :bw + if a:auto + redraw! + wincmd p + redraw! + endif +endfunction + +noremap gd :call Git_diff_windows(0, 0, g:git_diff_opts) +noremap ghd :call Git_diff_windows(0, 0, g:git_diff_opts) +noremap gvd :call Git_diff_windows(1, 0, g:git_diff_opts) + +if !exists("g:git_diff_opts") + let g:git_diff_opts = "-C -C" +endif +if exists("g:git_diff_spawn_mode") + if g:git_diff_spawn_mode == 1 + call Git_diff_windows(0, 1, g:git_diff_opts) + elseif g:git_diff_spawn_mode == 2 + call Git_diff_windows(1, 1, g:git_diff_opts) + endif +endif + +" }}} diff --git a/.vim/ftplugin/svn.vim b/.vim/ftplugin/svn.vim new file mode 100644 index 0000000..7b22f39 --- /dev/null +++ b/.vim/ftplugin/svn.vim @@ -0,0 +1,57 @@ +" made by Michael Scherer ( misc@mandrake.org ) +" $Id: svn.vim 282 2005-01-31 21:24:55Z misc $ +" +" 2004-09-13 : Lukas Ruf ( lukas.ruf@lpr.ch ) +" - re-ordered windows +" - set focus on svn-commit.tmp (that's where one has to write) +" - set buffer type of new window to 'nofile' to fix 'TODO' +" +" 2005-01-31 : +" - autoclose on exit, thanks to Gintautas Miliauskas ( gintas@akl.lt ) +" and tips from Marius Gedminas ( mgedmin@b4net.lt ) +" +" 2005-02-08 : +" - rewrite in pure vim function, from Kyosuke Takayama ( support@mc.neweb.ne.jp ) +" - simplified installation instruction, from Marius Gedminas ( mgedmin@b4net.lt ) +" +" 2005-02-11 : +" - reindent with space, asked by Marius Gedminas ( mgedmin@b4net.lt ) +" - do not preview if no file are diffed, patch from Marius Gedminas. +" +" to use it, place it in ~/.vim/ftplugins + +function! Svn_diff_windows() + let i = 0 + let list_of_files = '' + + while i <= line('$') + let line = getline(i) + if line =~ '^M' + + let file = substitute(line, '\v^MM?\s*(.*)\s*$', '\1', '') + let list_of_files = list_of_files . ' '.file + endif + + let i = i + 1 + endwhile + + if list_of_files == "" + return + endif + + new + silent! setlocal ft=diff previewwindow bufhidden=delete nobackup noswf nobuflisted nowrap buftype=nofile + exe 'normal :r!LANG=C svn diff ' . list_of_files . "\n" + setlocal nomodifiable + goto 1 + redraw! + wincmd R + wincmd p + goto 1 + redraw! +endfunction + +set nowarn +set nosplitbelow +call Svn_diff_windows() +set nowb diff --git a/.vim/plugin/NERD_tree.vim b/.vim/plugin/NERD_tree.vim new file mode 100644 index 0000000..df2dbc8 --- /dev/null +++ b/.vim/plugin/NERD_tree.vim @@ -0,0 +1,2913 @@ +" vim global plugin that provides a nice tree explorer +" Last Change: 18 jan 2008 +" Maintainer: Martin Grenfell +let s:NERD_tree_version = '2.7.1' + +" SECTION: Script init stuff {{{1 +"============================================================ +if exists("loaded_nerd_tree") + finish +endif +if v:version < 700 + echoerr "NERDTree: this plugin requires vim >= 7. DOWNLOAD IT! You'll thank me later!" + finish +endif +let loaded_nerd_tree = 1 +"Function: s:InitVariable() function {{{2 +"This function is used to initialise a given variable to a given value. The +"variable is only initialised if it does not exist prior +" +"Args: +"var: the name of the var to be initialised +"value: the value to initialise var to +" +"Returns: +"1 if the var is set, 0 otherwise +function! s:InitVariable(var, value) + if !exists(a:var) + exec 'let ' . a:var . ' = ' . "'" . a:value . "'" + return 1 + endif + return 0 +endfunction + +"SECTION: Init variable calls and other random constants {{{2 +call s:InitVariable("g:NERDChristmasTree", 1) +call s:InitVariable("g:NERDTreeAutoCenter", 1) +call s:InitVariable("g:NERDTreeAutoCenterThreshold", 3) +call s:InitVariable("g:NERDTreeCaseSensitiveSort", 0) +call s:InitVariable("g:NERDTreeChDirMode", 1) +if !exists("g:NERDTreeIgnore") + let g:NERDTreeIgnore = ['\~$'] +endif +call s:InitVariable("g:NERDTreeHighlightCursorline", 1) +call s:InitVariable("g:NERDTreeMouseMode", 1) +call s:InitVariable("g:NERDTreeNotificationThreshold", 100) +call s:InitVariable("g:NERDTreeShowHidden", 0) +call s:InitVariable("g:NERDTreeShowFiles", 1) +call s:InitVariable("g:NERDTreeSortDirs", 1) + +if !exists("g:NERDTreeSortOrder") + let g:NERDTreeSortOrder = ['\/$', '*', '\.swp$', '\.bak$', '\~$'] +else + "if there isnt a * in the sort sequence then add one + if count(g:NERDTreeSortOrder, '*') < 1 + call add(g:NERDTreeSortOrder, '*') + endif +endif + +"we need to use this number many times for sorting... so we calculate it only +"once here +let g:NERDTreeSortStarIndex = index(g:NERDTreeSortOrder, '*') + +call s:InitVariable("g:NERDTreeSplitVertical", 1) +call s:InitVariable("g:NERDTreeWinPos", 1) +call s:InitVariable("g:NERDTreeWinSize", 31) + +let s:running_windows = has("win16") || has("win32") || has("win64") + +"init the shell commands that will be used to copy nodes, and remove dir trees +" +"Note: the space after the command is important +if s:running_windows + call s:InitVariable("g:NERDTreeRemoveDirCmd", 'rmdir /s /q ') +else + call s:InitVariable("g:NERDTreeRemoveDirCmd", 'rm -rf ') + call s:InitVariable("g:NERDTreeCopyCmd", 'cp -r ') +endif + + +"SECTION: Init variable calls for key mappings {{{2 +call s:InitVariable("g:NERDTreeMapActivateNode", "o") +call s:InitVariable("g:NERDTreeMapChangeRoot", "C") +call s:InitVariable("g:NERDTreeMapChdir", "cd") +call s:InitVariable("g:NERDTreeMapCloseChildren", "X") +call s:InitVariable("g:NERDTreeMapCloseDir", "x") +call s:InitVariable("g:NERDTreeMapExecute", "!") +call s:InitVariable("g:NERDTreeMapFilesystemMenu", "m") +call s:InitVariable("g:NERDTreeMapHelp", "?") +call s:InitVariable("g:NERDTreeMapJumpFirstChild", "K") +call s:InitVariable("g:NERDTreeMapJumpLastChild", "J") +call s:InitVariable("g:NERDTreeMapJumpNextSibling", "") +call s:InitVariable("g:NERDTreeMapJumpParent", "p") +call s:InitVariable("g:NERDTreeMapJumpPrevSibling", "") +call s:InitVariable("g:NERDTreeMapJumpRoot", "P") +call s:InitVariable("g:NERDTreeMapOpenExpl", "e") +call s:InitVariable("g:NERDTreeMapOpenInTab", "t") +call s:InitVariable("g:NERDTreeMapOpenInTabSilent", "T") +call s:InitVariable("g:NERDTreeMapOpenRecursively", "O") +call s:InitVariable("g:NERDTreeMapOpenSplit", "") +call s:InitVariable("g:NERDTreeMapPreview", "g" . NERDTreeMapActivateNode) +call s:InitVariable("g:NERDTreeMapPreviewSplit", "g" . NERDTreeMapOpenSplit) +call s:InitVariable("g:NERDTreeMapQuit", "q") +call s:InitVariable("g:NERDTreeMapRefresh", "r") +call s:InitVariable("g:NERDTreeMapRefreshRoot", "R") +call s:InitVariable("g:NERDTreeMapToggleFiles", "F") +call s:InitVariable("g:NERDTreeMapToggleFilters", "f") +call s:InitVariable("g:NERDTreeMapToggleHidden", "H") +call s:InitVariable("g:NERDTreeMapUpdir", "u") +call s:InitVariable("g:NERDTreeMapUpdirKeepOpen", "U") + +"SECTION: Script level variable declaration{{{2 +let s:escape_chars = " `|\"~'#" +let s:NERDTreeWinName = '_NERD_tree_' + +"init all the nerd tree markup +let s:tree_vert = '|' +let s:tree_vert_last = '`' +let s:tree_wid = 2 +let s:tree_wid_str = ' ' +let s:tree_wid_strM1 = ' ' +let s:tree_dir_open = '~' +let s:tree_dir_closed = '+' +let s:tree_file = '-' +let s:tree_markup_reg = '[ \-+~`|]' +let s:tree_markup_reg_neg = '[^ \-+~`|]' +let s:tree_up_dir_line = '.. (up a dir)' +let s:tree_RO_str = ' [RO]' +let s:tree_RO_str_reg = ' \[RO\]' + +let s:os_slash = '/' +if s:running_windows + let s:os_slash = '\' +endif + + +" SECTION: Commands {{{1 +"============================================================ +"init the command that users start the nerd tree with +command! -n=? -complete=dir NERDTree :call s:InitNerdTree('') +command! -n=? -complete=dir NERDTreeToggle :call s:Toggle('') +" SECTION: Auto commands {{{1 +"============================================================ +"Save the cursor position whenever we close the nerd tree +exec "autocmd BufWinLeave *". s:NERDTreeWinName ."* :call SaveScreenState()" + +"SECTION: Classes {{{1 +"============================================================ +"CLASS: oTreeFileNode {{{2 +"This class is the parent of the oTreeDirNode class and constitures the +"'Component' part of the composite design pattern between the treenode +"classes. +"============================================================ +let s:oTreeFileNode = {} +"FUNCTION: oTreeFileNode.CompareNodes {{{3 +"This is supposed to be a class level method but i cant figure out how to +"get func refs to work from a dict.. +" +"A class level method that compares two nodes +" +"Args: +"n1, n2: the 2 nodes to compare +function! s:CompareNodes(n1, n2) + return a:n1.path.CompareTo(a:n2.path) +endfunction + +"FUNCTION: oTreeFileNode.Copy(dest) {{{3 +function! s:oTreeFileNode.Copy(dest) dict + call self.path.Copy(a:dest) + let newPath = s:oPath.New(a:dest) + let parentNode = t:NERDTreeRoot.FindNode(newPath.GetDir()) + if !empty(parentNode) + call parentNode.Refresh() + endif +endfunction + +"FUNCTION: oTreeFileNode.Delete {{{3 +"Removes this node from the tree and calls the Delete method for its path obj +function! s:oTreeFileNode.Delete() dict + call self.path.Delete() + call self.parent.RemoveChild(self) +endfunction + +"FUNCTION: oTreeFileNode.Equals(treenode) {{{3 +" +"Compares this treenode to the input treenode and returns 1 if they are the +"same node. +" +"Use this method instead of == because sometimes when the treenodes contain +"many children, vim seg faults when doing == +" +"Args: +"treenode: the other treenode to compare to +function! s:oTreeFileNode.Equals(treenode) dict + return self.path.Str(1) == a:treenode.path.Str(1) +endfunction + +"FUNCTION: oTreeFileNode.FindNode(path) {{{3 +"Returns self if this node.path.Equals the given path. +"Returns {} if not equal. +" +"Args: +"path: the path object to compare against +function! s:oTreeFileNode.FindNode(path) dict + if a:path.Equals(self.path) + return self + endif + return {} +endfunction +"FUNCTION: oTreeFileNode.FindOpenDirSiblingWithChildren(direction) {{{3 +" +"Finds the next sibling for this node in the indicated direction. This sibling +"must be a directory and may/may not have children as specified. +" +"Args: +"direction: 0 if you want to find the previous sibling, 1 for the next sibling +" +"Return: +"a treenode object or {} if no appropriate sibling could be found +function! s:oTreeFileNode.FindOpenDirSiblingWithChildren(direction) dict + "if we have no parent then we can have no siblings + if self.parent != {} + let nextSibling = self.FindSibling(a:direction) + + while nextSibling != {} + if nextSibling.path.isDirectory && nextSibling.HasVisibleChildren() && nextSibling.isOpen + return nextSibling + endif + let nextSibling = nextSibling.FindSibling(a:direction) + endwhile + endif + + return {} +endfunction +"FUNCTION: oTreeFileNode.FindSibling(direction) {{{3 +" +"Finds the next sibling for this node in the indicated direction +" +"Args: +"direction: 0 if you want to find the previous sibling, 1 for the next sibling +" +"Return: +"a treenode object or {} if no sibling could be found +function! s:oTreeFileNode.FindSibling(direction) dict + "if we have no parent then we can have no siblings + if self.parent != {} + + "get the index of this node in its parents children + let siblingIndx = self.parent.GetChildIndex(self.path) + + if siblingIndx != -1 + "move a long to the next potential sibling node + let siblingIndx = a:direction == 1 ? siblingIndx+1 : siblingIndx-1 + + "keep moving along to the next sibling till we find one that is valid + let numSiblings = self.parent.GetChildCount() + while siblingIndx >= 0 && siblingIndx < numSiblings + + "if the next node is not an ignored node (i.e. wont show up in the + "view) then return it + if self.parent.children[siblingIndx].path.Ignore() == 0 + return self.parent.children[siblingIndx] + endif + + "go to next node + let siblingIndx = a:direction == 1 ? siblingIndx+1 : siblingIndx-1 + endwhile + endif + endif + + return {} +endfunction + +"FUNCTION: oTreeFileNode.IsVisible() {{{3 +"returns 1 if this node should be visible according to the tree filters and +"hidden file filters (and their on/off status) +function! s:oTreeFileNode.IsVisible() dict + return !self.path.Ignore() +endfunction + + +"FUNCTION: oTreeFileNode.IsRoot() {{{3 +"returns 1 if this node is t:NERDTreeRoot +function! s:oTreeFileNode.IsRoot() dict + if !s:TreeExistsForTab() + throw "NERDTree.TreeFileNode.IsRoot exception: No tree exists for the current tab" + endif + return self.Equals(t:NERDTreeRoot) +endfunction + +"FUNCTION: oTreeFileNode.New(path) {{{3 +"Returns a new TreeNode object with the given path and parent +" +"Args: +"path: a path object representing the full filesystem path to the file/dir that the node represents +function! s:oTreeFileNode.New(path) dict + if a:path.isDirectory + return s:oTreeDirNode.New(a:path) + else + let newTreeNode = {} + let newTreeNode = copy(self) + let newTreeNode.path = a:path + let newTreeNode.parent = {} + return newTreeNode + endif +endfunction + +"FUNCTION: oTreeFileNode.Rename {{{3 +"Calls the rename method for this nodes path obj +function! s:oTreeFileNode.Rename(newName) dict + call self.path.Rename(a:newName) + call self.parent.RemoveChild(self) + + let parentPath = self.path.GetPathTrunk() + let newParent = t:NERDTreeRoot.FindNode(parentPath) + + if newParent != {} + call newParent.CreateChild(self.path, 1) + endif +endfunction + +"FUNCTION: oTreeFileNode.StrDisplay() {{{3 +" +"Returns a string that specifies how the node should be represented as a +"string +" +"Return: +"a string that can be used in the view to represent this node +function! s:oTreeFileNode.StrDisplay() dict + return self.path.StrDisplay() +endfunction + +"CLASS: oTreeDirNode {{{2 +"This class is a child of the oTreeFileNode class and constitutes the +"'Composite' part of the composite design pattern between the treenode +"classes. +"============================================================ +let s:oTreeDirNode = copy(s:oTreeFileNode) +"FUNCTION: oTreeDirNode.AddChild(treenode, inOrder) {{{3 +"Adds the given treenode to the list of children for this node +" +"Args: +"-treenode: the node to add +"-inOrder: 1 if the new node should be inserted in sorted order +function! s:oTreeDirNode.AddChild(treenode, inOrder) dict + call add(self.children, a:treenode) + let a:treenode.parent = self + + if a:inOrder + call self.SortChildren() + endif +endfunction + +"FUNCTION: oTreeDirNode.Close {{{3 +"Closes this directory +function! s:oTreeDirNode.Close() dict + let self.isOpen = 0 +endfunction + +"FUNCTION: oTreeDirNode.CloseChildren {{{3 +"Closes all the child dir nodes of this node +function! s:oTreeDirNode.CloseChildren() dict + for i in self.children + if i.path.isDirectory + call i.Close() + call i.CloseChildren() + endif + endfor +endfunction + +"FUNCTION: oTreeDirNode.CreateChild(path, inOrder) {{{3 +"Instantiates a new child node for this node with the given path. The new +"nodes parent is set to this node. +" +"Args: +"path: a Path object that this node will represent/contain +"inOrder: 1 if the new node should be inserted in sorted order +" +"Returns: +"the newly created node +function! s:oTreeDirNode.CreateChild(path, inOrder) dict + let newTreeNode = s:oTreeFileNode.New(a:path) + call self.AddChild(newTreeNode, a:inOrder) + return newTreeNode +endfunction + +"FUNCTION: oTreeDirNode.FindNode(path) {{{3 +"Will find one of the children (recursively) that has the given path +" +"Args: +"path: a path object +unlet s:oTreeDirNode.FindNode +function! s:oTreeDirNode.FindNode(path) dict + if a:path.Equals(self.path) + return self + endif + if stridx(a:path.Str(1), self.path.Str(1), 0) == -1 + return {} + endif + + if self.path.isDirectory + for i in self.children + let retVal = i.FindNode(a:path) + if retVal != {} + return retVal + endif + endfor + endif + return {} +endfunction + +"FUNCTION: oTreeDirNode.GetChildDirs() {{{3 +"Returns the number of children this node has +function! s:oTreeDirNode.GetChildCount() dict + return len(self.children) +endfunction + +"FUNCTION: oTreeDirNode.GetChildDirs() {{{3 +"Returns an array of all children of this node that are directories +" +"Return: +"an array of directory treenodes +function! s:oTreeDirNode.GetChildDirs() dict + let toReturn = [] + for i in self.children + if i.path.isDirectory + call add(toReturn, i) + endif + endfor + return toReturn +endfunction + +"FUNCTION: oTreeDirNode.GetChildFiles() {{{3 +"Returns an array of all children of this node that are files +" +"Return: +"an array of file treenodes +function! s:oTreeDirNode.GetChildFiles() dict + let toReturn = [] + for i in self.children + if i.path.isDirectory == 0 + call add(toReturn, i) + endif + endfor + return toReturn +endfunction + +"FUNCTION: oTreeDirNode.GetChild(path) {{{3 +"Returns child node of this node that has the given path or {} if no such node +"exists. +" +"This function doesnt not recurse into child dir nodes +" +"Args: +"path: a path object +function! s:oTreeDirNode.GetChild(path) dict + if stridx(a:path.Str(1), self.path.Str(1), 0) == -1 + return {} + endif + + let index = self.GetChildIndex(a:path) + if index == -1 + return {} + else + return self.children[index] + endif + +endfunction + +"FUNCTION: oTreeDirNode.GetChildByIndex(indx, visible) {{{3 +"returns the child at the given index +"Args: +"indx: the index to get the child from +"visible: 1 if only the visible children array should be used, 0 if all the +"children should be searched. +function! s:oTreeDirNode.GetChildByIndex(indx, visible) dict + let array_to_search = a:visible? self.GetVisibleChildren() : self.children + if a:indx > len(array_to_search) + throw "NERDTree.TreeDirNode.InvalidArguments exception. Index is out of bounds." + endif + return array_to_search[a:indx] +endfunction + +"FUNCTION: oTreeDirNode.GetChildIndex(path) {{{3 +"Returns the index of the child node of this node that has the given path or +"-1 if no such node exists. +" +"This function doesnt not recurse into child dir nodes +" +"Args: +"path: a path object +function! s:oTreeDirNode.GetChildIndex(path) dict + if stridx(a:path.Str(1), self.path.Str(1), 0) == -1 + return -1 + endif + + "do a binary search for the child + let a = 0 + let z = self.GetChildCount() + while a < z + let mid = (a+z)/2 + let diff = a:path.CompareTo(self.children[mid].path) + + if diff == -1 + let z = mid + elseif diff == 1 + let a = mid+1 + else + return mid + endif + endwhile + return -1 +endfunction + +"FUNCTION: oTreeDirNode.GetVisibleChildCount() {{{3 +"Returns the number of visible children this node has +function! s:oTreeDirNode.GetVisibleChildCount() dict + return len(self.GetVisibleChildren()) +endfunction + +"FUNCTION: oTreeDirNode.GetVisibleChildren() {{{3 +"Returns a list of children to display for this node, in the correct order +" +"Return: +"an array of treenodes +function! s:oTreeDirNode.GetVisibleChildren() dict + let toReturn = [] + for i in self.children + if i.path.Ignore() == 0 + call add(toReturn, i) + endif + endfor + return toReturn +endfunction + +"FUNCTION: oTreeDirNode.HasVisibleChildren {{{3 +"returns 1 if this node has any childre, 0 otherwise.. +function! s:oTreeDirNode.HasVisibleChildren() + return self.GetChildCount() != 0 +endfunction + +"FUNCTION: oTreeDirNode.InitChildren {{{3 +"Removes all childen from this node and re-reads them +" +"Args: +"silent: 1 if the function should not echo any "please wait" messages for +"large directories +" +"Return: the number of child nodes read +function! s:oTreeDirNode.InitChildren(silent) dict + "remove all the current child nodes + let self.children = [] + + "get an array of all the files in the nodes dir + let dir = self.path + let filesStr = globpath(dir.StrForOS(0), '*') . "\n" . globpath(dir.StrForOS(0), '.*') + let files = split(filesStr, "\n") + + if !a:silent && len(files) > g:NERDTreeNotificationThreshold + call s:Echo("Please wait, caching a large dir ...") + endif + + let invalidFilesFound = 0 + for i in files + + "filter out the .. and . directories + if i !~ '\.\.$' && i !~ '\.$' + + "put the next file in a new node and attach it + try + let path = s:oPath.New(i) + call self.CreateChild(path, 0) + catch /^NERDTree.Path.InvalidArguments/ + let invalidFilesFound = 1 + endtry + endif + endfor + + call self.SortChildren() + + if !a:silent && len(files) > g:NERDTreeNotificationThreshold + call s:Echo("Please wait, caching a large dir ... DONE (". self.GetChildCount() ." nodes cached).") + endif + + if invalidFilesFound + call s:EchoWarning("some files could not be loaded into the NERD tree") + endif + return self.GetChildCount() +endfunction +"FUNCTION: oTreeDirNode.New(path) {{{3 +"Returns a new TreeNode object with the given path and parent +" +"Args: +"path: a path object representing the full filesystem path to the file/dir that the node represents +unlet s:oTreeDirNode.New +function! s:oTreeDirNode.New(path) dict + if a:path.isDirectory != 1 + throw "NERDTree.TreeDirNode.InvalidArguments exception. A TreeDirNode object must be instantiated with a directory Path object." + endif + + let newTreeNode = copy(self) + let newTreeNode.path = a:path + + let newTreeNode.isOpen = 0 + let newTreeNode.children = [] + + let newTreeNode.parent = {} + + return newTreeNode +endfunction +"FUNCTION: oTreeDirNode.Open {{{3 +"Reads in all this nodes children +" +"Return: the number of child nodes read +function! s:oTreeDirNode.Open() dict + let self.isOpen = 1 + if self.children == [] + return self.InitChildren(0) + else + return 0 + endif +endfunction + +"FUNCTION: oTreeDirNode.OpenRecursively {{{3 +"Opens this treenode and all of its children whose paths arent 'ignored' +"because of the file filters. +" +"This method is actually a wrapper for the OpenRecursively2 method which does +"the work. +function! s:oTreeDirNode.OpenRecursively() dict + call self.OpenRecursively2(1) +endfunction + +"FUNCTION: oTreeDirNode.OpenRecursively2 {{{3 +"Dont call this method from outside this object. +" +"Opens this all children of this treenode recursively if either: +" *they arent filtered by file filters +" *a:forceOpen is 1 +" +"Args: +"forceOpen: 1 if this node should be opened regardless of file filters +function! s:oTreeDirNode.OpenRecursively2(forceOpen) dict + if self.path.Ignore() == 0 || a:forceOpen + let self.isOpen = 1 + if self.children == [] + call self.InitChildren(1) + endif + + for i in self.children + if i.path.isDirectory == 1 + call i.OpenRecursively2(0) + endif + endfor + endif +endfunction + +"FUNCTION: oTreeDirNode.Refresh {{{3 +function! s:oTreeDirNode.Refresh() dict + let newChildNodes = [] + let invalidFilesFound = 0 + + "go thru all the files/dirs under this node + let dir = self.path + let filesStr = globpath(dir.StrForOS(0), '*') . "\n" . globpath(dir.StrForOS(0), '.*') + let files = split(filesStr, "\n") + for i in files + if i !~ '\.\.$' && i !~ '\.$' + + try + "create a new path and see if it exists in this nodes children + let path = s:oPath.New(i) + let newNode = self.GetChild(path) + if newNode != {} + + "if the existing node is a dir can be refreshed then + "refresh it + if newNode.path.isDirectory && (!empty(newNode.children) || newNode.isOpen == 1) + call newNode.Refresh() + + "if we have a filenode then refresh the path + elseif newNode.path.isDirectory == 0 + call newNode.path.Refresh() + endif + + call add(newChildNodes, newNode) + + "the node doesnt exist so create it + else + let newNode = s:oTreeFileNode.New(path) + let newNode.parent = self + call add(newChildNodes, newNode) + endif + + + catch /^NERDTree.InvalidArguments/ + let invalidFilesFound = 1 + endtry + endif + endfor + + "swap this nodes children out for the children we just read/refreshed + let self.children = newChildNodes + call self.SortChildren() + + if invalidFilesFound + call s:EchoWarning("some files could not be loaded into the NERD tree") + endif +endfunction + +"FUNCTION: oTreeDirNode.RemoveChild {{{3 +" +"Removes the given treenode from this nodes set of children +" +"Args: +"treenode: the node to remove +" +"Throws a NERDTree.TreeDirNode exception if the given treenode is not found +function! s:oTreeDirNode.RemoveChild(treenode) dict + for i in range(0, self.GetChildCount()-1) + if self.children[i].Equals(a:treenode) + call remove(self.children, i) + return + endif + endfor + + throw "NERDTree.TreeDirNode exception: child node was not found" +endfunction + +"FUNCTION: oTreeDirNode.SortChildren {{{3 +" +"Sorts the children of this node according to alphabetical order and the +"directory priority. +" +function! s:oTreeDirNode.SortChildren() dict + let CompareFunc = function("s:CompareNodes") + call sort(self.children, CompareFunc) +endfunction + +"FUNCTION: oTreeDirNode.ToggleOpen {{{3 +"Opens this directory if it is closed and vice versa +function! s:oTreeDirNode.ToggleOpen() dict + if self.isOpen == 1 + call self.Close() + else + call self.Open() + endif +endfunction + +"FUNCTION: oTreeDirNode.TransplantChild(newNode) {{{3 +"Replaces the child of this with the given node (where the child node's full +"path matches a:newNode's fullpath). The search for the matching node is +"non-recursive +" +"Arg: +"newNode: the node to graft into the tree +function! s:oTreeDirNode.TransplantChild(newNode) dict + for i in range(0, self.GetChildCount()-1) + if self.children[i].Equals(a:newNode) + let self.children[i] = a:newNode + let a:newNode.parent = self + break + endif + endfor +endfunction +"============================================================ +"CLASS: oPath {{{2 +"============================================================ +let s:oPath = {} +let oPath = s:oPath +"FUNCTION: oPath.ChangeToDir() {{{3 +function! s:oPath.ChangeToDir() dict + let dir = self.Str(1) + if self.isDirectory == 0 + let dir = self.GetPathTrunk().Str(1) + endif + + try + execute "cd " . dir + call s:Echo("CWD is now: " . getcwd()) + catch + throw "NERDTree.Path.Change exception: cannot change to " . dir + endtry +endfunction + +"FUNCTION: oPath.ChopTrailingSlash(str) {{{3 +function! s:oPath.ChopTrailingSlash(str) dict + if a:str =~ '\/$' + return substitute(a:str, "\/$", "", "") + else + return substitute(a:str, "\\$", "", "") + endif +endfunction + +"FUNCTION: oPath.CompareTo() {{{3 +" +"Compares this oPath to the given path and returns 0 if they are equal, -1 if +"this oPath is "less than" the given path, or 1 if it is "greater". +" +"Args: +"path: the path object to compare this to +" +"Return: +"1, -1 or 0 +function! s:oPath.CompareTo(path) dict + let thisPath = self.GetLastPathComponent(1) + let thatPath = a:path.GetLastPathComponent(1) + + "if the paths are the same then clearly we return 0 + if thisPath == thatPath + return 0 + endif + + let thisSS = self.GetSortOrderIndex() + let thatSS = a:path.GetSortOrderIndex() + + "compare the sort sequences, if they are different then the return + "value is easy + if thisSS < thatSS + return -1 + elseif thisSS > thatSS + return 1 + else + "if the sort sequences are the same then compare the paths + "alphabetically + let pathCompare = g:NERDTreeCaseSensitiveSort ? thisPath <# thatPath : thisPath ' . self.symLinkDest + endif + + if self.isReadOnly + let toReturn .= s:tree_RO_str + endif + + return toReturn +endfunction + +"FUNCTION: oPath.StrForEditCmd() {{{3 +" +"Return: the string for this path that is suitable to be used with the :edit +"command +function! s:oPath.StrForEditCmd() dict + if s:running_windows + return self.StrForOS(0) + else + return self.Str(1) + endif + +endfunction +"FUNCTION: oPath.StrForOS(esc) {{{3 +" +"Gets the string path for this path object that is appropriate for the OS. +"EG, in windows c:\foo\bar +" in *nix /foo/bar +" +"Args: +"esc: if 1 then all the tricky chars in the returned string will be +" escaped. If we are running windows then the str is double quoted instead. +function! s:oPath.StrForOS(esc) dict + let lead = s:os_slash + + "if we are running windows then slap a drive letter on the front + if s:running_windows + let lead = strpart(getcwd(), 0, 2) . s:os_slash + endif + + let toReturn = lead . join(self.pathSegments, s:os_slash) + + if a:esc + if s:running_windows + let toReturn = '"' . toReturn . '"' + else + let toReturn = escape(toReturn, s:escape_chars) + endif + endif + return toReturn +endfunction + +"FUNCTION: oPath.StrTrunk() {{{3 +"Gets the path without the last segment on the end. +function! s:oPath.StrTrunk() dict + return '/' . join(self.pathSegments[0:-2], '/') +endfunction + +"FUNCTION: oPath.WinToUnixPath(pathstr){{{3 +"Takes in a windows path and returns the unix equiv +" +"A class level method +" +"Args: +"pathstr: the windows path to convert +function! s:oPath.WinToUnixPath(pathstr) dict + if !s:running_windows + return a:pathstr + endif + + let toReturn = a:pathstr + + "remove the x:\ of the front + let toReturn = substitute(toReturn, '^.*:\(\\\|/\)\?', '/', "") + + "convert all \ chars to / + let toReturn = substitute(toReturn, '\', '/', "g") + + return toReturn +endfunction + +" SECTION: General Functions {{{1 +"============================================================ +"FUNCTION: s:Abs(num){{{2 +"returns the absolute value of the input +function! s:Abs(num) + if a:num > 0 + return a:num + else + return 0 - a:num + end +endfunction + +"FUNCTION: s:BufInWindows(bnum){{{2 +"[[STOLEN FROM VTREEEXPLORER.VIM]] +"Determine the number of windows open to this buffer number. +"Care of Yegappan Lakshman. Thanks! +" +"Args: +"bnum: the subject buffers buffer number +function! s:BufInWindows(bnum) + let cnt = 0 + let winnum = 1 + while 1 + let bufnum = winbufnr(winnum) + if bufnum < 0 + break + endif + if bufnum == a:bnum + let cnt = cnt + 1 + endif + let winnum = winnum + 1 + endwhile + + return cnt +endfunction " >>> + +"FUNCTION: s:InitNerdTree(dir) {{{2 +"Initialized the NERD tree, where the root will be initialized with the given +"directory +" +"Arg: +"dir: the dir to init the root with +function! s:InitNerdTree(dir) + let dir = a:dir == '' ? expand('%:p:h') : a:dir + let dir = resolve(dir) + + if !isdirectory(dir) + call s:EchoWarning("Error reading: " . dir) + return + endif + + "if instructed to, then change the vim CWD to the dir the NERDTree is + "inited in + if g:NERDTreeChDirMode != 0 + exec "cd " . dir + endif + + let t:treeShowHelp = 0 + let t:NERDTreeIgnoreEnabled = 1 + + if s:TreeExistsForTab() + if s:IsTreeOpen() + call s:CloseTree() + endif + unlet t:NERDTreeRoot + endif + + let path = s:oPath.New(dir) + let t:NERDTreeRoot = s:oTreeDirNode.New(path) + call t:NERDTreeRoot.Open() + + call s:CreateTreeWin() + + call s:RenderView() +endfunction + +" Function: s:TreeExistsForTab() {{{2 +" Returns 1 if a nerd tree root exists in the current tab +function! s:TreeExistsForTab() + return exists("t:NERDTreeRoot") +endfunction + +" SECTION: Public Functions {{{1 +"============================================================ +"Returns the node that the cursor is currently on. +" +"If the cursor is not in the NERDTree window, it is temporarily put there. +" +"If no NERD tree window exists for the current tab, a NERDTree.NoTreeForTab +"exception is thrown. +" +"If the cursor is not on a node then an empty dictionary {} is returned. +function! NERDTreeGetCurrentNode() + if !s:TreeExistsForTab() || !s:IsTreeOpen() + throw "NERDTree.NoTreeForTab exception: there is no NERD tree open for the current tab" + endif + + let winnr = winnr() + if winnr != s:GetTreeWinNum() + call s:PutCursorInTreeWin() + endif + + let treenode = s:GetSelectedNode() + + if winnr != winnr() + wincmd w + endif + + return treenode +endfunction + +"Returns the path object for the current node. +" +"Subject to the same conditions as NERDTreeGetCurrentNode +function! NERDTreeGetCurrentPath() + let node = NERDTreeGetCurrentNode() + if node != {} + return node.path + else + return {} + endif +endfunction + +" SECTION: View Functions {{{1 +"============================================================ +"FUNCTION: s:CenterView() {{{2 +"centers the nerd tree window around the cursor (provided the nerd tree +"options permit) +function! s:CenterView() + if g:NERDTreeAutoCenter + let current_line = winline() + let lines_to_top = current_line + let lines_to_bottom = winheight(s:GetTreeWinNum()) - current_line + if lines_to_top < g:NERDTreeAutoCenterThreshold || lines_to_bottom < g:NERDTreeAutoCenterThreshold + normal! zz + endif + endif +endfunction + +"FUNCTION: s:CloseTree() {{{2 +"Closes the NERD tree window +function! s:CloseTree() + if !s:IsTreeOpen() + throw "NERDTree.view.CloseTree exception: no NERDTree is open" + endif + + if winnr("$") != 1 + execute s:GetTreeWinNum() . " wincmd w" + close + execute "wincmd p" + else + :q + endif +endfunction + +"FUNCTION: s:CreateTreeWin() {{{2 +"Inits the NERD tree window. ie. opens it, sizes it, sets all the local +"options etc +function! s:CreateTreeWin() + "create the nerd tree window + let splitLocation = g:NERDTreeWinPos ? "topleft " : "botright " + let splitMode = g:NERDTreeSplitVertical ? "vertical " : "" + let splitSize = g:NERDTreeWinSize + let t:NERDTreeWinName = localtime() . s:NERDTreeWinName + let cmd = splitLocation . splitMode . splitSize . ' new ' . t:NERDTreeWinName + silent! execute cmd + + setlocal winfixwidth + + "throwaway buffer options + setlocal noswapfile + setlocal buftype=nofile + setlocal bufhidden=delete + setlocal nowrap + setlocal foldcolumn=0 + setlocal nobuflisted + setlocal nospell + setlocal nonu + iabc + + if g:NERDTreeHighlightCursorline + setlocal cursorline + endif + + " syntax highlighting + if has("syntax") && exists("g:syntax_on") && !has("syntax_items") + call s:SetupSyntaxHighlighting() + endif + + " for line continuation + let cpo_save1 = &cpo + set cpo&vim + + call s:BindMappings() +endfunction + +"FUNCTION: s:DrawTree {{{2 +"Draws the given node recursively +" +"Args: +"curNode: the node that is being rendered with this call +"depth: the current depth in the tree for this call +"drawText: 1 if we should actually draw the line for this node (if 0 then the +"child nodes are rendered only) +"vertMap: a binary array that indicates whether a vertical bar should be draw +"for each depth in the tree +"isLastChild:true if this curNode is the last child of its parent +function! s:DrawTree(curNode, depth, drawText, vertMap, isLastChild) + if a:drawText == 1 + + let treeParts = '' + + "get all the leading spaces and vertical tree parts for this line + if a:depth > 1 + for j in a:vertMap[0:-2] + if j == 1 + let treeParts = treeParts . s:tree_vert . s:tree_wid_strM1 + else + let treeParts = treeParts . s:tree_wid_str + endif + endfor + endif + + "get the last vertical tree part for this line which will be different + "if this node is the last child of its parent + if a:isLastChild + let treeParts = treeParts . s:tree_vert_last + else + let treeParts = treeParts . s:tree_vert + endif + + + "smack the appropriate dir/file symbol on the line before the file/dir + "name itself + if a:curNode.path.isDirectory + if a:curNode.isOpen + let treeParts = treeParts . s:tree_dir_open + else + let treeParts = treeParts . s:tree_dir_closed + endif + else + let treeParts = treeParts . s:tree_file + endif + let line = treeParts . a:curNode.StrDisplay() + + call setline(line(".")+1, line) + call cursor(line(".")+1, col(".")) + endif + + "if the node is an open dir, draw its children + if a:curNode.path.isDirectory == 1 && a:curNode.isOpen == 1 + + let childNodesToDraw = a:curNode.GetVisibleChildren() + if len(childNodesToDraw) > 0 + + "draw all the nodes children except the last + let lastIndx = len(childNodesToDraw)-1 + if lastIndx > 0 + for i in childNodesToDraw[0:lastIndx-1] + call s:DrawTree(i, a:depth + 1, 1, add(copy(a:vertMap), 1), 0) + endfor + endif + + "draw the last child, indicating that it IS the last + call s:DrawTree(childNodesToDraw[lastIndx], a:depth + 1, 1, add(copy(a:vertMap), 0), 1) + endif + endif +endfunction + + +"FUNCTION: s:DumpHelp {{{2 +"prints out the quick help +function! s:DumpHelp() + let old_h = @h + if t:treeShowHelp == 1 + let @h= "\" NERD tree (" . s:NERD_tree_version . ") quickhelp~\n" + let @h=@h."\" ============================\n" + let @h=@h."\" File node mappings~\n" + let @h=@h."\" ". (g:NERDTreeMouseMode == 3 ? "single" : "double") ."-click,\n" + let @h=@h."\" ". g:NERDTreeMapActivateNode .": open in prev window\n" + let @h=@h."\" ". g:NERDTreeMapPreview .": preview \n" + let @h=@h."\" ". g:NERDTreeMapOpenInTab.": open in new tab\n" + let @h=@h."\" ". g:NERDTreeMapOpenInTabSilent .": open in new tab silently\n" + let @h=@h."\" middle-click,\n" + let @h=@h."\" ". g:NERDTreeMapOpenSplit .": open split\n" + let @h=@h."\" ". g:NERDTreeMapPreviewSplit .": preview split\n" + let @h=@h."\" ". g:NERDTreeMapExecute.": Execute file\n" + + let @h=@h."\" \n\" ----------------------------\n" + let @h=@h."\" Directory node mappings~\n" + let @h=@h."\" ". (g:NERDTreeMouseMode == 1 ? "double" : "single") ."-click,\n" + let @h=@h."\" ". g:NERDTreeMapActivateNode .": open/close node \n" + let @h=@h."\" ". g:NERDTreeMapOpenRecursively .": recursively open node\n" + let @h=@h."\" ". g:NERDTreeMapCloseDir .": close parent of node\n" + let @h=@h."\" ". g:NERDTreeMapCloseChildren .": close all child nodes of\n" + let @h=@h."\" current node recursively\n" + let @h=@h."\" middle-click,\n" + let @h=@h."\" ". g:NERDTreeMapOpenExpl.": Open netrw for selected\n" + let @h=@h."\" node \n" + + let @h=@h."\" \n\" ----------------------------\n" + let @h=@h."\" Tree navigation mappings~\n" + let @h=@h."\" ". g:NERDTreeMapJumpRoot .": go to root\n" + let @h=@h."\" ". g:NERDTreeMapJumpParent .": go to parent\n" + let @h=@h."\" ". g:NERDTreeMapJumpFirstChild .": go to first child\n" + let @h=@h."\" ". g:NERDTreeMapJumpLastChild .": go to last child\n" + let @h=@h."\" ". g:NERDTreeMapJumpNextSibling .": go to next sibling\n" + let @h=@h."\" ". g:NERDTreeMapJumpPrevSibling .": go to prev sibling\n" + + let @h=@h."\" \n\" ----------------------------\n" + let @h=@h."\" Filesystem mappings~\n" + let @h=@h."\" ". g:NERDTreeMapChangeRoot .": change tree root to the\n" + let @h=@h."\" selected dir\n" + let @h=@h."\" ". g:NERDTreeMapUpdir .": move tree root up a dir\n" + let @h=@h."\" ". g:NERDTreeMapUpdirKeepOpen .": move tree root up a dir\n" + let @h=@h."\" but leave old root open\n" + let @h=@h."\" ". g:NERDTreeMapRefresh .": refresh cursor dir\n" + let @h=@h."\" ". g:NERDTreeMapRefreshRoot .": refresh current root\n" + let @h=@h."\" ". g:NERDTreeMapFilesystemMenu .": Show filesystem menu\n" + let @h=@h."\" ". g:NERDTreeMapChdir .":change the CWD to the\n" + let @h=@h."\" selected dir\n" + + let @h=@h."\" \n\" ----------------------------\n" + let @h=@h."\" Tree filtering mappings~\n" + let @h=@h."\" ". g:NERDTreeMapToggleHidden .": hidden files (" . (g:NERDTreeShowHidden ? "on" : "off") . ")\n" + let @h=@h."\" ". g:NERDTreeMapToggleFilters .": file filters (" . (t:NERDTreeIgnoreEnabled ? "on" : "off") . ")\n" + let @h=@h."\" ". g:NERDTreeMapToggleFiles .": files (" . (g:NERDTreeShowFiles ? "on" : "off") . ")\n" + + let @h=@h."\" \n\" ----------------------------\n" + let @h=@h."\" Other mappings~\n" + let @h=@h."\" ". g:NERDTreeMapQuit .": Close the NERDTree window\n" + let @h=@h."\" ". g:NERDTreeMapHelp .": toggle help\n" + else + let @h="\" Press ". g:NERDTreeMapHelp ." for help\n" + endif + + silent! put h + + let @h = old_h +endfunction +"FUNCTION: s:Echo {{{2 +"A wrapper for :echo. Appends 'NERDTree:' on the front of all messages +" +"Args: +"msg: the message to echo +function! s:Echo(msg) + redraw + echo "NERDTree: " . a:msg +endfunction +"FUNCTION: s:EchoWarning {{{2 +"Wrapper for s:Echo, sets the message type to warningmsg for this message +"Args: +"msg: the message to echo +function! s:EchoWarning(msg) + echohl warningmsg + call s:Echo(a:msg) + echohl normal +endfunction +"FUNCTION: s:EchoError {{{2 +"Wrapper for s:Echo, sets the message type to errormsg for this message +"Args: +"msg: the message to echo +function! s:EchoError(msg) + echohl errormsg + call s:Echo(a:msg) + echohl normal +endfunction +"FUNCTION: s:FindNodeLineNumber(treenode){{{2 +"Finds the line number for the given tree node +" +"Args: +"treenode: the node to find the line no. for +function! s:FindNodeLineNumber(treenode) + "if the node is the root then return the root line no. + if a:treenode.IsRoot() + return s:FindRootNodeLineNumber() + endif + + let totalLines = line("$") + + "the path components we have matched so far + let pathcomponents = [substitute(t:NERDTreeRoot.path.Str(0), '/ *$', '', '')] + "the index of the component we are searching for + let curPathComponent = 1 + + let fullpath = a:treenode.path.Str(0) + + + let lnum = s:FindRootNodeLineNumber() + while lnum > 0 + let lnum = lnum + 1 + "have we reached the bottom of the tree? + if lnum == totalLines+1 + return -1 + endif + + let curLine = getline(lnum) + + let indent = match(curLine,s:tree_markup_reg_neg) / s:tree_wid + if indent == curPathComponent + let curLine = s:StripMarkupFromLine(curLine, 1) + + let curPath = join(pathcomponents, '/') . '/' . curLine + if stridx(fullpath, curPath, 0) == 0 + if fullpath == curPath || strpart(fullpath, len(curPath)-1,1) == '/' + let curLine = substitute(curLine, '/ *$', '', '') + call add(pathcomponents, curLine) + let curPathComponent = curPathComponent + 1 + + if fullpath == curPath + return lnum + endif + endif + endif + endif + endwhile + return -1 +endfunction + +"FUNCTION: s:FindRootNodeLineNumber(path){{{2 +"Finds the line number of the root node +function! s:FindRootNodeLineNumber() + let rootLine = 1 + while getline(rootLine) !~ '^/' + let rootLine = rootLine + 1 + endwhile + return rootLine +endfunction + +"FUNCTION: s:GetPath(ln) {{{2 +"Gets the full path to the node that is rendered on the given line number +" +"Args: +"ln: the line number to get the path for +" +"Return: +"A path if a node was selected, {} if nothing is selected. +"If the 'up a dir' line was selected then the path to the parent of the +"current root is returned +function! s:GetPath(ln) + let line = getline(a:ln) + + "check to see if we have the root node + if line =~ '^\/' + return t:NERDTreeRoot.path + endif + + " in case called from outside the tree + if line !~ '^ *[|`]' || line =~ '^$' + return {} + endif + + if line == s:tree_up_dir_line + return t:NERDTreeRoot.path.GetParent() + endif + + "get the indent level for the file (i.e. how deep in the tree it is) + "let indent = match(line,'[^-| `]') / s:tree_wid + let indent = match(line, s:tree_markup_reg_neg) / s:tree_wid + + + "remove the tree parts and the leading space + let curFile = s:StripMarkupFromLine(line, 0) + + let wasdir = 0 + if curFile =~ '/$' + let wasdir = 1 + endif + let curFile = substitute (curFile,' -> .*',"","") " remove link to + if wasdir == 1 + let curFile = substitute (curFile, '/\?$', '/', "") + endif + + + let dir = "" + let lnum = a:ln + while lnum > 0 + let lnum = lnum - 1 + let curLine = getline(lnum) + + "have we reached the top of the tree? + if curLine =~ '^/' + let sd = substitute (curLine, '[ ]*$', "", "") + let dir = sd . dir + break + endif + if curLine =~ '/$' + let lpindent = match(curLine,s:tree_markup_reg_neg) / s:tree_wid + if lpindent < indent + let indent = indent - 1 + let sd = substitute (curLine, '^' . s:tree_markup_reg . '*',"","") + let sd = substitute (sd, ' -> .*', '',"") + + " remove leading escape + let sd = substitute (sd,'^\\', "", "") + + let dir = sd . dir + continue + endif + endif + endwhile + let curFile = dir . curFile + return s:oPath.NewMinimal(curFile) +endfunction + +"FUNCTION: s:GetSelectedDir() {{{2 +"Returns the current node if it is a dir node, or else returns the current +"nodes parent +function! s:GetSelectedDir() + let currentDir = s:GetSelectedNode() + if currentDir != {} && !currentDir.IsRoot() + if currentDir.path.isDirectory == 0 + let currentDir = currentDir.parent + endif + endif + return currentDir +endfunction +"FUNCTION: s:GetSelectedNode() {{{2 +"gets the treenode that the cursor is currently over +function! s:GetSelectedNode() + try + let path = s:GetPath(line(".")) + if path == {} + return {} + endif + return t:NERDTreeRoot.FindNode(path) + catch /^NERDTree/ + return {} + endtry +endfunction +"FUNCTION: s:GetTreeBufNum() {{{2 +"gets the nerd tree buffer number for this tab +function! s:GetTreeBufNum() + if exists("t:NERDTreeWinName") + return bufnr(t:NERDTreeWinName) + else + return -1 + endif +endfunction +"FUNCTION: s:GetTreeWinNum() {{{2 +"gets the nerd tree window number for this tab +function! s:GetTreeWinNum() + if exists("t:NERDTreeWinName") + return bufwinnr(t:NERDTreeWinName) + else + return -1 + endif +endfunction + +"FUNCTION: s:IsTreeOpen() {{{2 +function! s:IsTreeOpen() + return s:GetTreeWinNum() != -1 +endfunction + +" FUNCTION: s:JumpToChild(direction) {{{2 +" Args: +" direction: 0 if going to first child, 1 if going to last +function! s:JumpToChild(direction) + let currentNode = s:GetSelectedNode() + if currentNode == {} || currentNode.IsRoot() + call s:Echo("cannot jump to " . (a:direction ? "last" : "first") . " child") + return + end + let dirNode = currentNode.parent + let childNodes = dirNode.GetVisibleChildren() + + let targetNode = childNodes[0] + if a:direction + let targetNode = childNodes[len(childNodes) - 1] + endif + + if targetNode.Equals(currentNode) + let siblingDir = currentNode.parent.FindOpenDirSiblingWithChildren(a:direction) + if siblingDir != {} + let indx = a:direction ? siblingDir.GetVisibleChildCount()-1 : 0 + let targetNode = siblingDir.GetChildByIndex(indx, 1) + endif + endif + + call s:PutCursorOnNode(targetNode, 1) + + call s:CenterView() +endfunction + + +"FUNCTION: s:OpenDirNodeSplit(treenode) {{{2 +"Open the file represented by the given node in a new window. +"No action is taken for file nodes +" +"ARGS: +"treenode: file node to open +function! s:OpenDirNodeSplit(treenode) + if a:treenode.path.isDirectory == 1 + call s:OpenNodeSplit(a:treenode) + endif +endfunction + +"FUNCTION: s:OpenFileNode(treenode) {{{2 +"Open the file represented by the given node in the current window, splitting +"the window if needed +" +"ARGS: +"treenode: file node to open +function! s:OpenFileNode(treenode) + call s:PutCursorInTreeWin() + + if s:ShouldSplitToOpen(winnr("#")) + call s:OpenFileNodeSplit(a:treenode) + else + try + wincmd p + exec ("edit " . a:treenode.path.StrForEditCmd()) + catch /^Vim\%((\a\+)\)\=:E37/ + call s:PutCursorInTreeWin() + call s:Echo("Cannot open file, it is already open and modified") + catch /^Vim\%((\a\+)\)\=:/ + echo v:exception + endtry + endif +endfunction + +"FUNCTION: s:OpenFileNodeSplit(treenode) {{{2 +"Open the file represented by the given node in a new window. +"No action is taken for dir nodes +" +"ARGS: +"treenode: file node to open +function! s:OpenFileNodeSplit(treenode) + if a:treenode.path.isDirectory == 0 + try + call s:OpenNodeSplit(a:treenode) + catch /^NERDTree.view.FileOpen/ + call s:Echo("Cannot open file, it is already open and modified" ) + endtry + endif +endfunction + +"FUNCTION: s:OpenNodeSplit(treenode) {{{2 +"Open the file/dir represented by the given node in a new window +" +"ARGS: +"treenode: file node to open +function! s:OpenNodeSplit(treenode) + call s:PutCursorInTreeWin() + + " Save the user's settings for splitbelow and splitright + let savesplitbelow=&splitbelow + let savesplitright=&splitright + + " Figure out how to do the split based on the user's preferences. + " We want to split to the (left,right,top,bottom) of the explorer + " window, but we want to extract the screen real-estate from the + " window next to the explorer if possible. + " + " 'there' will be set to a command to move from the split window + " back to the explorer window + " + " 'back' will be set to a command to move from the explorer window + " back to the newly split window + " + " 'right' and 'below' will be set to the settings needed for + " splitbelow and splitright IF the explorer is the only window. + " + if g:NERDTreeSplitVertical == 1 + let there= g:NERDTreeWinPos ? "wincmd h" : "wincmd l" + let back= g:NERDTreeWinPos ? "wincmd l" : "wincmd h" + let right=g:NERDTreeWinPos ? 1 : 0 + let below=0 + else + let there= g:NERDTreeWinPos ? "wincmd k" : "wincmd j" + let back= g:NERDTreeWinPos ? "wincmd j" : "wincmd k" + let right=0 + let below=g:NERDTreeWinPos ? 1 : 0 + endif + + " Attempt to go to adjacent window + exec(back) + + let onlyOneWin = (winnr() == s:GetTreeWinNum()) + + " If no adjacent window, set splitright and splitbelow appropriately + if onlyOneWin + let &splitright=right + let &splitbelow=below + else + " found adjacent window - invert split direction + let &splitright=!right + let &splitbelow=!below + endif + + " Create a variable to use if splitting vertically + let splitMode = "" + if (onlyOneWin && g:NERDTreeSplitVertical) || (!onlyOneWin && !g:NERDTreeSplitVertical) + let splitMode = "vertical" + endif + + " Open the new window + try + exec("silent " . splitMode." sp " . a:treenode.path.StrForEditCmd()) + catch /^Vim\%((\a\+)\)\=:E37/ + call s:PutCursorInTreeWin() + throw "NERDTree.view.FileOpen exception: ". a:treenode.path.Str(0) ." is already open and modified." + catch /^Vim\%((\a\+)\)\=:/ + do nothing + endtry + + " resize the explorer window if it is larger than the requested size + exec(there) + + if g:NERDTreeWinSize =~ '[0-9]\+' && winheight("") > g:NERDTreeWinSize + exec("silent vertical resize ".g:NERDTreeWinSize) + endif + + wincmd p + + " Restore splitmode settings + let &splitbelow=savesplitbelow + let &splitright=savesplitright +endfunction + +"FUNCTION: s:PromptToDelBuffer(bufnum, msg){{{2 +"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: s:PutCursorOnNode(treenode, is_jump){{{2 +"Places the cursor on the line number representing the given node +" +"Args: +"treenode: the node to put the cursor on +"is_jump: 1 if this cursor movement should be counted as a jump by vim +function! s:PutCursorOnNode(treenode, is_jump) + let ln = s:FindNodeLineNumber(a:treenode) + if ln != -1 + if a:is_jump + mark ' + endif + call cursor(ln, col(".")) + endif +endfunction + +"FUNCTION: s:PutCursorInTreeWin(){{{2 +"Places the cursor in the nerd tree window +function! s:PutCursorInTreeWin() + if !s:IsTreeOpen() + throw "NERDTree.view.InvalidOperation Exception: No NERD tree window exists" + endif + + exec s:GetTreeWinNum() . "wincmd w" +endfunction + +"FUNCTION: s:RenderView {{{2 +"The entry function for rendering the tree. Renders the root then calls +"s:DrawTree to draw the children of the root +" +"Args: +function! s:RenderView() + execute s:GetTreeWinNum() . "wincmd w" + + setlocal modifiable + + "remember the top line of the buffer and the current line so we can + "restore the view exactly how it was + let curLine = line(".") + let curCol = col(".") + let topLine = line("w0") + + "delete all lines in the buffer (being careful not to clobber a register) + :silent 1,$delete _ + + call s:DumpHelp() + + "delete the blank line before the help and add one after it + call setline(line(".")+1, " ") + call cursor(line(".")+1, col(".")) + + "add the 'up a dir' line + call setline(line(".")+1, s:tree_up_dir_line) + call cursor(line(".")+1, col(".")) + + "draw the header line + call setline(line(".")+1, t:NERDTreeRoot.path.Str(0)) + call cursor(line(".")+1, col(".")) + + "draw the tree + call s:DrawTree(t:NERDTreeRoot, 0, 0, [], t:NERDTreeRoot.GetChildCount() == 1) + + "delete the blank line at the top of the buffer + :silent 1,1delete _ + + "restore the view + call cursor(topLine, 1) + normal! zt + call cursor(curLine, curCol) + + setlocal nomodifiable +endfunction + +"FUNCTION: s:RenderViewSavingPosition {{{2 +"Renders the tree and ensures the cursor stays on the current node or the +"current nodes parent if it is no longer available upon re-rendering +function! s:RenderViewSavingPosition() + let currentNode = s:GetSelectedNode() + + "go up the tree till we find a node that will be visible or till we run + "out of nodes + while currentNode != {} && !currentNode.IsVisible() && !currentNode.IsRoot() + let currentNode = currentNode.parent + endwhile + + call s:RenderView() + + if currentNode != {} + call s:PutCursorOnNode(currentNode, 0) + endif +endfunction +"FUNCTION: s:RestoreScreenState() {{{2 +" +"Sets the screen state back to what it was when s:SaveScreenState was last +"called. +" +"Assumes the cursor is in the NERDTree window +function! s:RestoreScreenState() + if !exists("t:NERDTreeOldTopLine") || !exists("t:NERDTreeOldPos") + return + endif + + call cursor(t:NERDTreeOldTopLine, 0) + normal! zt + call setpos(".", t:NERDTreeOldPos) +endfunction + +"FUNCTION: s:SaveScreenState() {{{2 +"Saves the current cursor position in the current buffer and the window +"scroll position +" +"Assumes the cursor is in the NERDTree window +function! s:SaveScreenState() + let t:NERDTreeOldPos = getpos(".") + let t:NERDTreeOldTopLine = line("w0") +endfunction + +"FUNCTION: s:SetupSyntaxHighlighting() {{{2 +function! s:SetupSyntaxHighlighting() + "treeFlags are syntax items that should be invisible, but give clues as to + "how things should be highlighted + syn match treeFlag #\~# + syn match treeFlag #\[RO\]# + + "highlighting for the .. (up dir) line at the top of the tree + execute "syn match treeUp #". s:tree_up_dir_line ."#" + + "highlighting for the ~/+ symbols for the directory nodes + syn match treeClosable #\~\<# + syn match treeClosable #\~\.# + syn match treeOpenable #+\<# + syn match treeOpenable #+\.#he=e-1 + + "highlighting for the tree structural parts + syn match treePart #|# + syn match treePart #`# + syn match treePartFile #[|`]-#hs=s+1 contains=treePart + + "quickhelp syntax elements + syn match treeHelpKey #" \{1,2\}[^ ]*:#hs=s+2,he=e-1 + syn match treeHelpKey #" \{1,2\}[^ ]*,#hs=s+2,he=e-1 + syn match treeHelpTitle #" .*\~#hs=s+2,he=e-1 contains=treeFlag + syn match treeToggleOn #".*(on)#hs=e-2,he=e-1 contains=treeHelpKey + syn match treeToggleOff #".*(off)#hs=e-3,he=e-1 contains=treeHelpKey + syn match treeHelp #^" .*# contains=treeHelpKey,treeHelpTitle,treeFlag,treeToggleOff,treeToggleOn + + "highlighting for sym links + syn match treeLink #[^-| `].* -> # + + "highlighting for readonly files + syn match treeRO #[0-9a-zA-Z]\+.*\[RO\]# contains=treeFlag + + "highlighing for directory nodes and file nodes + syn match treeDirSlash #/# + syn match treeDir #[^-| `].*/\([ {}]\{4\}\)*$# contains=treeLink,treeDirSlash,treeOpenable,treeClosable + syn match treeFile #|-.*# contains=treeLink,treePart,treeRO,treePartFile + syn match treeFile #`-.*# contains=treeLink,treePart,treeRO,treePartFile + syn match treeCWD #^/.*$# + + if g:NERDChristmasTree + hi def link treePart Special + hi def link treePartFile Type + hi def link treeFile Macro + hi def link treeDirSlash Identifier + hi def link treeClosable Type + else + hi def link treePart Normal + hi def link treePartFile Normal + hi def link treeFile Normal + hi def link treeClosable Title + endif + + hi def link treeHelp String + hi def link treeHelpKey Identifier + hi def link treeHelpTitle Macro + hi def link treeToggleOn Question + hi def link treeToggleOff WarningMsg + + hi def link treeDir Directory + hi def link treeUp Directory + hi def link treeCWD Statement + hi def link treeLink Title + hi def link treeOpenable Title + hi def link treeFlag ignore + hi def link treeRO WarningMsg + + hi def link NERDTreeCurrentNode Search +endfunction + +"FUNCTION: s:ShouldSplitToOpen() {{{2 +"Returns 1 if opening a file from the tree in the given window requires it to +"be split +" +"Args: +"winnumber: the number of the window in question +function! s:ShouldSplitToOpen(winnumber) + if &hidden + return 0 + endif + let oldwinnr = winnr() + + exec a:winnumber . "wincmd p" + let modified = &modified + exec oldwinnr . "wincmd p" + + return winnr("$") == 1 || (modified && s:BufInWindows(winbufnr(a:winnumber)) < 2) +endfunction + +"FUNCTION: s:StripMarkupFromLine(line){{{2 +"returns the given line with all the tree parts stripped off +" +"Args: +"line: the subject line +"removeLeadingSpaces: 1 if leading spaces are to be removed (leading spaces = +"any spaces before the actual text of the node) +function! s:StripMarkupFromLine(line, removeLeadingSpaces) + let line = a:line + "remove the tree parts and the leading space + let line = substitute (line,"^" . s:tree_markup_reg . "*","","") + + "strip off any read only flag + let line = substitute (line, s:tree_RO_str_reg, "","") + + let wasdir = 0 + if line =~ '/$' + let wasdir = 1 + endif + let line = substitute (line,' -> .*',"","") " remove link to + if wasdir == 1 + let line = substitute (line, '/\?$', '/', "") + endif + + if a:removeLeadingSpaces + let line = substitute (line, '^ *', '', '') + endif + + return line +endfunction + +"FUNCTION: s:Toggle(dir) {{{2 +"Toggles the NERD tree. I.e the NERD tree is open, it is closed, if it is +"closed it is restored or initialized (if it doesnt exist) +" +"Args: +"dir: the full path for the root node (is only used if the NERD tree is being +"initialized. +function! s:Toggle(dir) + if s:TreeExistsForTab() + if !s:IsTreeOpen() + call s:CreateTreeWin() + call s:RenderView() + + call s:RestoreScreenState() + else + call s:CloseTree() + endif + else + call s:InitNerdTree(a:dir) + endif +endfunction +"SECTION: Interface bindings {{{1 +"============================================================ +"FUNCTION: s:ActivateNode() {{{2 +"If the current node is a file, open it in the previous window (or a new one +"if the previous is modified). If it is a directory then it is opened. +function! s:ActivateNode() + if getline(".") == s:tree_up_dir_line + return s:UpDir(0) + endif + let treenode = s:GetSelectedNode() + if treenode == {} + call s:EchoWarning("cannot open selected entry") + return + endif + + if treenode.path.isDirectory + call treenode.ToggleOpen() + call s:RenderView() + call s:PutCursorOnNode(treenode, 0) + else + call s:OpenFileNode(treenode) + endif +endfunction + +"FUNCTION: s:BindMappings() {{{2 +function! s:BindMappings() + " set up mappings and commands for this buffer + nnoremap :call HandleMiddleMouse() + nnoremap :call CheckForActivate() + nnoremap <2-leftmouse> :call ActivateNode() + + exec "nnoremap ". g:NERDTreeMapActivateNode . " :call ActivateNode()" + exec "nnoremap ". g:NERDTreeMapOpenSplit ." :call OpenEntrySplit()" + + exec "nnoremap ". g:NERDTreeMapPreview ." :call PreviewNode(0)" + exec "nnoremap ". g:NERDTreeMapPreviewSplit ." :call PreviewNode(1)" + + + exec "nnoremap ". g:NERDTreeMapExecute ." :call ExecuteNode()" + + exec "nnoremap ". g:NERDTreeMapOpenRecursively ." :call OpenNodeRecursively()" + + exec "nnoremap ". g:NERDTreeMapUpdirKeepOpen ." :call UpDir(1)" + exec "nnoremap ". g:NERDTreeMapUpdir ." :call UpDir(0)" + exec "nnoremap ". g:NERDTreeMapChangeRoot ." :call ChRoot()" + + exec "nnoremap ". g:NERDTreeMapChdir ." :call ChCwd()" + + exec "nnoremap ". g:NERDTreeMapQuit ." :NERDTreeToggle" + + exec "nnoremap ". g:NERDTreeMapRefreshRoot ." :call RefreshRoot()" + exec "nnoremap ". g:NERDTreeMapRefresh ." :call RefreshCurrent()" + + exec "nnoremap ". g:NERDTreeMapHelp ." :call DisplayHelp()" + exec "nnoremap ". g:NERDTreeMapToggleHidden ." :call ToggleShowHidden()" + exec "nnoremap ". g:NERDTreeMapToggleFilters ." :call ToggleIgnoreFilter()" + exec "nnoremap ". g:NERDTreeMapToggleFiles ." :call ToggleShowFiles()" + + exec "nnoremap ". g:NERDTreeMapCloseDir ." :call CloseCurrentDir()" + exec "nnoremap ". g:NERDTreeMapCloseChildren ." :call CloseChildren()" + + exec "nnoremap ". g:NERDTreeMapFilesystemMenu ." :call ShowFileSystemMenu()" + + exec "nnoremap ". g:NERDTreeMapJumpParent ." :call JumpToParent()" + exec "nnoremap ". g:NERDTreeMapJumpNextSibling ." :call JumpToSibling(1)" + exec "nnoremap ". g:NERDTreeMapJumpPrevSibling ." :call JumpToSibling(0)" + exec "nnoremap ". g:NERDTreeMapJumpFirstChild ." :call JumpToFirstChild()" + exec "nnoremap ". g:NERDTreeMapJumpLastChild ." :call JumpToLastChild()" + exec "nnoremap ". g:NERDTreeMapJumpRoot ." :call JumpToRoot()" + + exec "nnoremap ". g:NERDTreeMapOpenInTab ." :call OpenNodeNewTab(0)" + exec "nnoremap ". g:NERDTreeMapOpenInTabSilent ." :call OpenNodeNewTab(1)" + + exec "nnoremap ". g:NERDTreeMapOpenExpl ." :call OpenExplorer()" +endfunction + +"FUNCTION: s:CheckForActivate() {{{2 +"Checks if the click should open the current node, if so then activate() is +"called (directories are automatically opened if the symbol beside them is +"clicked) +function! s:CheckForActivate() + let currentNode = s:GetSelectedNode() + if currentNode != {} + let startToCur = strpart(getline(line(".")), 0, col(".")) + let char = strpart(startToCur, strlen(startToCur)-1, 1) + + "if they clicked a dir, check if they clicked on the + or ~ sign + "beside it + if currentNode.path.isDirectory + let reg = '^' . s:tree_markup_reg .'*[' . s:tree_dir_open . s:tree_dir_closed . ']$' + if startToCur =~ reg + call s:ActivateNode() + return + endif + endif + + if (g:NERDTreeMouseMode == 2 && currentNode.path.isDirectory) || g:NERDTreeMouseMode == 3 + if char !~ s:tree_markup_reg && startToCur !~ '\/$' + call s:ActivateNode() + return + endif + endif + endif +endfunction + +" FUNCTION: s:ChCwd() {{{2 +function! s:ChCwd() + let treenode = s:GetSelectedNode() + if treenode == {} + call s:Echo("Select a node first") + return + endif + + try + call treenode.path.ChangeToDir() + catch /^NERDTree.Path.Change/ + call s:EchoWarning("could not change cwd") + endtry +endfunction + +" FUNCTION: s:ChRoot() {{{2 +" changes the current root to the selected one +function! s:ChRoot() + let treenode = s:GetSelectedNode() + if treenode == {} || treenode.path.isDirectory == 0 + call s:Echo("Select a directory node first") + return + endif + + if treenode.isOpen == 0 + call treenode.Open() + endif + + let t:NERDTreeRoot = treenode + + "change dir to the dir of the new root if instructed to + if g:NERDTreeChDirMode == 2 + exec "cd " . treenode.path.StrForEditCmd() + endif + + + call s:RenderView() + call s:PutCursorOnNode(t:NERDTreeRoot, 0) +endfunction + +" FUNCTION: s:CloseChildren() {{{2 +" closes all childnodes of the current node +function! s:CloseChildren() + let currentNode = s:GetSelectedDir() + if currentNode == {} + call s:Echo("Select a node first") + return + endif + + call currentNode.CloseChildren() + call s:RenderView() + call s:PutCursorOnNode(currentNode, 0) +endfunction +" FUNCTION: s:CloseCurrentDir() {{{2 +" closes the parent dir of the current node +function! s:CloseCurrentDir() + let treenode = s:GetSelectedNode() + if treenode == {} + call s:Echo("Select a node first") + return + endif + + let parent = treenode.parent + if parent.IsRoot() + call s:Echo("cannot close tree root") + else + call treenode.parent.Close() + call s:RenderView() + call s:PutCursorOnNode(treenode.parent, 0) + endif +endfunction + +" FUNCTION: s:CopyNode() {{{2 +function! s:CopyNode() + let currentNode = s:GetSelectedNode() + if currentNode == {} + call s:Echo("Put the cursor on a file node first") + return + endif + + let newNodePath = input("Copy the current node\n" . + \ "==========================================================\n" . + \ "Enter the new path to copy the node to: \n" . + \ "", currentNode.path.Str(0)) + + if newNodePath != "" + let confirmed = 1 + if currentNode.path.CopyingWillOverwrite(newNodePath) + echo "\nWarning: copying may overwrite files! Continue? (yN)" + let choice = nr2char(getchar()) + let confirmed = choice == 'y' + endif + + if confirmed + try + call currentNode.Copy(newNodePath) + catch /^NERDTree/ + call s:EchoWarning("Could not copy node") + endtry + endif + call s:RenderView() + else + call s:Echo("Copy aborted.") + endif + redraw +endfunction + +" FUNCTION: s:DeleteNode() {{{2 +" if the current node is a file, pops up a dialog giving the user the option +" to delete it +function! s:DeleteNode() + let currentNode = s:GetSelectedNode() + if currentNode == {} + call s:Echo("Put the cursor on a file node first") + return + endif + + 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.StrForOS(0) . ": ") + let confirmed = choice == 'yes' + else + echo "Delete the current node\n" . + \ "==========================================================\n". + \ "Are you sure you wish to delete the node:\n" . + \ "" . currentNode.path.StrForOS(0) . " (yN):" + let choice = nr2char(getchar()) + let confirmed = choice == 'y' + endif + + + if confirmed + try + call currentNode.Delete() + call s:RenderView() + + "if the node is open in a buffer, ask the user if they want to + "close that buffer + let bufnum = bufnr(currentNode.path.Str(0)) + 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: s:DisplayHelp() {{{2 +" toggles the help display +function! s:DisplayHelp() + let t:treeShowHelp = t:treeShowHelp ? 0 : 1 + call s:RenderView() + call s:CenterView() +endfunction + +" FUNCTION: s:ExecuteNode() {{{2 +function! s:ExecuteNode() + let treenode = s:GetSelectedNode() + if treenode == {} || treenode.path.isDirectory + call s:Echo("Select an executable file node first" ) + else + echo "NERDTree executor\n" . + \ "==========================================================\n". + \ "Complete the command to execute (add arguments etc): \n\n" + let cmd = treenode.path.StrForOS(1) + let cmd = input(':!', cmd . ' ') + + if cmd != '' + exec ':!' . cmd + else + call s:Echo("command aborted") + endif + endif +endfunction + +" FUNCTION: s:HandleMiddleMouse() {{{2 +function! s:HandleMiddleMouse() + let curNode = s:GetSelectedNode() + if curNode == {} + call s:Echo("Put the cursor on a node first" ) + return + endif + + if curNode.path.isDirectory + call s:OpenExplorer() + else + call s:OpenEntrySplit() + endif +endfunction + + +" FUNCTION: s:InsertNewNode() {{{2 +" Adds a new node to the filesystem and then into the tree +function! s:InsertNewNode() + let curDirNode = s:GetSelectedDir() + if curDirNode == {} + call s:Echo("Put the cursor on a node first" ) + return + endif + + let newNodeName = input("Add a childnode\n". + \ "==========================================================\n". + \ "Enter the dir/file name to be created. Dirs end with a '/'\n" . + \ "", curDirNode.path.Str(0)) + + if newNodeName == '' + call s:Echo("Node Creation Aborted.") + return + endif + + try + let newPath = s:oPath.Create(newNodeName) + + let parentNode = t:NERDTreeRoot.FindNode(newPath.GetPathTrunk()) + + let newTreeNode = s:oTreeFileNode.New(newPath) + if parentNode.isOpen || !empty(parentNode.children) + call parentNode.AddChild(newTreeNode, 1) + call s:RenderView() + call s:PutCursorOnNode(newTreeNode, 1) + endif + catch /^NERDTree/ + call s:EchoWarning("Node Not Created.") + endtry +endfunction + +" FUNCTION: s:JumpToFirstChild() {{{2 +" wrapper for the jump to child method +function! s:JumpToFirstChild() + call s:JumpToChild(0) +endfunction + +" FUNCTION: s:JumpToLastChild() {{{2 +" wrapper for the jump to child method +function! s:JumpToLastChild() + call s:JumpToChild(1) +endfunction + +" FUNCTION: s:JumpToParent() {{{2 +" moves the cursor to the parent of the current node +function! s:JumpToParent() + let currentNode = s:GetSelectedNode() + if !empty(currentNode) + if !empty(currentNode.parent) + call s:PutCursorOnNode(currentNode.parent, 1) + call s:CenterView() + else + call s:Echo("cannot jump to parent") + endif + else + call s:Echo("put the cursor on a node first") + endif +endfunction + +" FUNCTION: s:JumpToRoot() {{{2 +" moves the cursor to the root node +function! s:JumpToRoot() + call s:PutCursorOnNode(t:NERDTreeRoot, 1) + call s:CenterView() +endfunction + +" FUNCTION: s:JumpToSibling() {{{2 +" moves the cursor to the sibling of the current node in the given direction +" +" Args: +" forward: 1 if the cursor should move to the next sibling, 0 if it should +" move back to the previous sibling +function! s:JumpToSibling(forward) + let currentNode = s:GetSelectedNode() + if !empty(currentNode) + + if !currentNode.path.isDirectory + + if a:forward + let sibling = currentNode.parent.FindSibling(1) + else + let sibling = currentNode.parent + endif + + else + let sibling = currentNode.FindSibling(a:forward) + endif + + if !empty(sibling) + call s:PutCursorOnNode(sibling, 1) + call s:CenterView() + endif + else + call s:Echo("put the cursor on a node first") + endif +endfunction + +" FUNCTION: s:OpenEntrySplit() {{{2 +" Opens the currently selected file from the explorer in a +" new window +function! s:OpenEntrySplit() + let treenode = s:GetSelectedNode() + if treenode != {} + call s:OpenFileNodeSplit(treenode) + else + call s:Echo("select a node first") + endif +endfunction + +" FUNCTION: s:OpenExplorer() {{{2 +function! s:OpenExplorer() + let treenode = s:GetSelectedDir() + if treenode != {} + let oldwin = winnr() + wincmd p + if oldwin == winnr() || (&modified && s:BufInWindows(winbufnr(winnr())) < 2) + wincmd p + call s:OpenDirNodeSplit(treenode) + else + exec ("silent edit " . treenode.path.StrForEditCmd()) + endif + else + call s:Echo("select a node first") + endif +endfunction + +" FUNCTION: s:OpenNodeNewTab(stayCurrentTab) {{{2 +" Opens the currently selected file from the explorer in a +" new tab +" +" Args: +" stayCurrentTab: if 1 then vim will stay in the current tab, if 0 then vim +" will go to the tab where the new file is opened +function! s:OpenNodeNewTab(stayCurrentTab) + let treenode = s:GetSelectedNode() + if treenode != {} + let curTabNr = tabpagenr() + exec "tabedit " . treenode.path.StrForEditCmd() + if a:stayCurrentTab + exec "tabnext " . curTabNr + endif + else + call s:Echo("select a node first") + endif +endfunction + + +" FUNCTION: s:OpenNodeRecursively() {{{2 +function! s:OpenNodeRecursively() + let treenode = s:GetSelectedNode() + if treenode == {} || treenode.path.isDirectory == 0 + call s:Echo("Select a directory node first" ) + else + call s:Echo("Recursively opening node. Please wait...") + call treenode.OpenRecursively() + call s:RenderView() + redraw + call s:Echo("Recursively opening node. Please wait... DONE") + endif + +endfunction + +"FUNCTION: s:PreviewNode() {{{2 +function! s:PreviewNode(openNewWin) + let treenode = s:GetSelectedNode() + if treenode == {} || treenode.path.isDirectory + call s:Echo("Select a file node first" ) + return + endif + + if a:openNewWin + call s:OpenEntrySplit() + else + call s:ActivateNode() + end + call s:PutCursorInTreeWin() +endfunction + +" FUNCTION: s:RefreshRoot() {{{2 +" Reloads the current root. All nodes below this will be lost and the root dir +" will be reloaded. +function! s:RefreshRoot() + call s:Echo("Refreshing the root node. This could take a while...") + call t:NERDTreeRoot.Refresh() + call s:RenderView() + redraw + call s:Echo("Refreshing the root node. This could take a while... DONE") +endfunction + +" FUNCTION: s:RefreshCurrent() {{{2 +" refreshes the root for the current node +function! s:RefreshCurrent() + let treenode = s:GetSelectedDir() + if treenode == {} + call s:Echo("Refresh failed. Select a node first") + return + endif + + call s:Echo("Refreshing node. This could take a while...") + call treenode.Refresh() + call s:RenderView() + redraw + call s:Echo("Refreshing node. This could take a while... DONE") +endfunction +" FUNCTION: s:RenameCurrent() {{{2 +" allows the user to rename the current node +function! s:RenameCurrent() + let curNode = s:GetSelectedNode() + if curNode == {} + call s:Echo("Put the cursor on a node first" ) + return + endif + + let newNodePath = input("Rename the current node\n" . + \ "==========================================================\n" . + \ "Enter the new path for the node: \n" . + \ "", curNode.path.Str(0)) + + if newNodePath == '' + call s:Echo("Node Renaming Aborted.") + return + endif + + let newNodePath = substitute(newNodePath, '\/$', '', '') + + try + let bufnum = bufnr(curNode.path.Str(0)) + + call curNode.Rename(newNodePath) + call s:RenderView() + + "if the node is open in a buffer, ask the user if they want to + "close that buffer + if bufnum != -1 + let prompt = "|\n|Node renamed.\n|\n|The old file is open in buffer ". bufnum . (bufwinnr(bufnum) == -1 ? " (hidden)" : "") .". Delete this buffer? (yN)" + call s:PromptToDelBuffer(bufnum, prompt) + endif + + call s:PutCursorOnNode(curNode, 1) + + redraw + catch /^NERDTree/ + call s:EchoWarning("Node Not Renamed.") + endtry +endfunction + +" FUNCTION: s:ShowFileSystemMenu() {{{2 +function! s:ShowFileSystemMenu() + let curNode = s:GetSelectedNode() + if curNode == {} + call s:Echo("Put the cursor on a node first" ) + return + endif + + + let prompt = "NERDTree Filesystem Menu\n" . + \ "==========================================================\n". + \ "Select the desired operation: \n" . + \ " (a)dd a childnode\n". + \ " (m)ove the current node\n". + \ " (d)elete the current node\n" + if s:oPath.CopyingSupported() + let prompt = prompt . " (c)opy the current node\n\n" + else + let prompt = prompt . " \n" + endif + + echo prompt + + let choice = nr2char(getchar()) + + if choice ==? "a" + call s:InsertNewNode() + elseif choice ==? "m" + call s:RenameCurrent() + elseif choice ==? "d" + call s:DeleteNode() + elseif choice ==? "c" && s:oPath.CopyingSupported() + call s:CopyNode() + endif +endfunction + +" FUNCTION: s:ToggleIgnoreFilter() {{{2 +" toggles the use of the NERDTreeIgnore option +function! s:ToggleIgnoreFilter() + let t:NERDTreeIgnoreEnabled = !t:NERDTreeIgnoreEnabled + call s:RenderViewSavingPosition() + call s:CenterView() +endfunction + +" FUNCTION: s:ToggleShowFiles() {{{2 +" toggles the display of hidden files +function! s:ToggleShowFiles() + let g:NERDTreeShowFiles = !g:NERDTreeShowFiles + call s:RenderViewSavingPosition() + call s:CenterView() +endfunction + +" FUNCTION: s:ToggleShowHidden() {{{2 +" toggles the display of hidden files +function! s:ToggleShowHidden() + let g:NERDTreeShowHidden = !g:NERDTreeShowHidden + call s:RenderViewSavingPosition() + call s:CenterView() +endfunction + +"FUNCTION: s:UpDir(keepState) {{{2 +"moves the tree up a level +" +"Args: +"keepState: 1 if the current root should be left open when the tree is +"re-rendered +function! s:UpDir(keepState) + let cwd = t:NERDTreeRoot.path.Str(0) + if cwd == "/" || cwd =~ '^[^/]..$' + call s:Echo("already at top dir") + else + if !a:keepState + call t:NERDTreeRoot.Close() + endif + + let oldRoot = t:NERDTreeRoot + + if empty(t:NERDTreeRoot.parent) + let path = t:NERDTreeRoot.path.GetPathTrunk() + let newRoot = s:oTreeDirNode.New(path) + call newRoot.Open() + call newRoot.TransplantChild(t:NERDTreeRoot) + let t:NERDTreeRoot = newRoot + else + let t:NERDTreeRoot = t:NERDTreeRoot.parent + + endif + + call s:RenderView() + call s:PutCursorOnNode(oldRoot, 0) + endif +endfunction + + diff --git a/.vim/plugin/project.vim b/.vim/plugin/project.vim new file mode 100644 index 0000000..47bd379 --- /dev/null +++ b/.vim/plugin/project.vim @@ -0,0 +1,1293 @@ +"============================================================================= +" File: project.vim +" Author: Aric Blumer (Aric.Blumer at aricvim@charter.net) +" Last Change: Fri 13 Oct 2006 09:47:08 AM EDT +" Version: 1.4.1 +"============================================================================= +" See documentation in accompanying help file +" You may use this code in whatever way you see fit. + +if exists('loaded_project') || &cp + finish +endif +let loaded_project=1 + +function! s:Project(filename) " <<< + " Initialization <<< + if exists("g:proj_running") + if strlen(a:filename) != 0 + call confirm('Project already loaded; ignoring filename "'.a:filename."\".\n".'See ":help project-invoking" for information about changing project files.', "&OK", 1) + endif + let filename=bufname(g:proj_running) + else + if strlen(a:filename) == 0 + let filename ='~/.vimprojects' " Default project filename + else + let filename = a:filename + endif + endif + if !exists('g:proj_window_width') + let g:proj_window_width=24 " Default project window width + endif + if !exists('g:proj_window_increment') + let g:proj_window_increment=100 " Project Window width increment + endif + if !exists('g:proj_flags') + if has("win32") || has("mac") + let g:proj_flags='imst' " Project default flags for windows/mac + else + let g:proj_flags='imstb' " Project default flags for everything else + endif + endif + if !exists("g:proj_running") || (bufwinnr(g:proj_running) == -1) " Open the Project Window + exec 'silent vertical new '.filename + if match(g:proj_flags, '\CF') == -1 " We're floating + silent! wincmd H + exec 'vertical resize '.g:proj_window_width + endif + setlocal nomodeline + else + silent! 99wincmd h + if bufwinnr(g:proj_running) == -1 + vertical split + let v:errmsg="nothing" + silent! bnext + if 'nothing' != v:errmsg + enew + endif + endif + return + endif + " Process the flags + let b:proj_cd_cmd='cd' + if match(g:proj_flags, '\Cl') != -1 + let b:proj_cd_cmd = 'lcd' + endif + + let b:proj_locate_command='silent! wincmd H' + let b:proj_resize_command='exec ''vertical resize ''.g:proj_window_width' + if match(g:proj_flags, '\CF') != -1 " Set the resize commands to nothing + let b:proj_locate_command='' + let b:proj_resize_command='' + endif + + let g:proj_last_buffer = -1 + ">>> + " ProjFoldText() <<< + " The foldtext function for displaying just the description. + function! ProjFoldText() + let line=substitute(getline(v:foldstart),'^[ \t#]*\([^=]*\).*', '\1', '') + let line=strpart(' ', 0, (v:foldlevel - 1)).substitute(line,'\s*{\+\s*', '', '') + return line + endfunction ">>> + " s:DoSetup() <<< + " Ensure everything is set up + function! s:DoSetup() + setlocal foldenable foldmethod=marker foldmarker={,} commentstring=%s foldcolumn=0 nonumber noswapfile shiftwidth=1 + setlocal foldtext=ProjFoldText() nobuflisted nowrap + setlocal winwidth=1 + if match(g:proj_flags, '\Cn') != -1 + setlocal number + endif + endfunction ">>> + call s:DoSetup() + " Syntax Stuff <<< + if match(g:proj_flags, '\Cs')!=-1 && has('syntax') && exists('g:syntax_on') && !has('syntax_items') + syntax match projectDescriptionDir '^\s*.\{-}=\s*\(\\ \|\f\|:\|"\)\+' contains=projectDescription,projectWhiteError + syntax match projectDescription '\<.\{-}='he=e-1,me=e-1 contained nextgroup=projectDirectory contains=projectWhiteError + syntax match projectDescription '{\|}' + syntax match projectDirectory '=\(\\ \|\f\|:\)\+' contained + syntax match projectDirectory '=".\{-}"' contained + syntax match projectScriptinout '\>> + " s:SortR(start, end) <<< + " Sort lines. SortR() is called recursively. + " from ":help eval-examples" by Robert Webb, slightly modified + function! s:SortR(start, end) + if (a:start >= a:end) + return + endif + let partition = a:start - 1 + let middle = partition + let partStr = getline((a:start + a:end) / 2) + let i = a:start + while (i <= a:end) + let str = getline(i) + if str < partStr + let result = -1 + elseif str > partStr + let result = 1 + else + let result = 0 + endif + if (result <= 0) + let partition = partition + 1 + if (result == 0) + let middle = partition + endif + if (i != partition) + let str2 = getline(partition) + call setline(i, str2) + call setline(partition, str) + endif + endif + let i = i + 1 + endwhile + if (middle != partition) + let str = getline(middle) + let str2 = getline(partition) + call setline(middle, str2) + call setline(partition, str) + endif + call s:SortR(a:start, partition - 1) + call s:SortR(partition + 1, a:end) + endfunc ">>> + " s:IsAbsolutePath(path) <<< + " Returns true if filename has an absolute path. + function! s:IsAbsolutePath(path) + if a:path =~ '^ftp:' || a:path =~ '^rcp:' || a:path =~ '^scp:' || a:path =~ '^http:' + return 2 + endif + if a:path =~ '\$' + let path=expand(a:path) " Expand any environment variables that might be in the path + else + let path=a:path + endif + if path[0] == '/' || path[0] == '~' || path[0] == '\\' || path[1] == ':' + return 1 + endif + return 0 + endfunction " >>> + " s:DoSetupAndSplit() <<< + " Call DoSetup to ensure the settings are correct. Split to the next + " file. + function! s:DoSetupAndSplit() + call s:DoSetup() " Ensure that all the settings are right + let n = winnr() " Determine if there is a CTRL_W-p window + silent! wincmd p + if n == winnr() + silent! wincmd l + endif + if n == winnr() + " If n == winnr(), then there is no CTRL_W-p window + " So we have to create a new one + if bufnr('%') == g:proj_running + exec 'silent vertical new' + else + exec 'silent vertical split | silent! bnext' + endif + wincmd p " Go back to the Project Window and ensure it is the right width + exec b:proj_locate_command + exec b:proj_resize_command + wincmd p + endif + endfunction ">>> + " s:DoSetupAndSplit_au() <<< + " Same as above but ensure that the Project window is the current + " window. Only called from an autocommand + function! s:DoSetupAndSplit_au() + if winbufnr(0) != g:proj_running + return + endif + call s:DoSetup() " Ensure that all the settings are right + if winbufnr(2) == -1 " We're the only window right now. + exec 'silent vertical split | bnext' + if bufnr('%') == g:proj_running + enew + endif + if bufnr('%') == g:proj_last_buffer | bnext | bprev | bnext | endif + wincmd p " Go back to the Project Window and ensure it is the right width + exec b:proj_locate_command + exec b:proj_resize_command + elseif(winnr() != 1) + exec b:proj_locate_command + exec b:proj_resize_command + endif + endfunction + function! s:RecordPrevBuffer_au() + let g:proj_last_buffer = bufnr('%') + endfunction ">>> + " s:RecursivelyConstructDirectives(lineno) <<< + " Construct the inherited directives + function! s:RecursivelyConstructDirectives(lineno) + let lineno=s:FindFoldTop(a:lineno) + let foldlineno = lineno + let foldlev=foldlevel(lineno) + let parent_infoline = '' + if foldlev > 1 + while foldlevel(lineno) >= foldlev " Go to parent fold + if lineno < 1 + echoerr 'Some kind of fold error. Check your syntax.' + return + endif + let lineno = lineno - 1 + endwhile + let parent_infoline = s:RecursivelyConstructDirectives(lineno) + endif + let parent_home = s:GetHome(parent_infoline, '') + let parent_c_d = s:GetCd(parent_infoline, parent_home) + let parent_scriptin = s:GetScriptin(parent_infoline, parent_home) + let parent_scriptout = s:GetScriptout(parent_infoline, parent_home) + let parent_filter = s:GetFilter(parent_infoline, '*') + let infoline = getline(foldlineno) + " Extract the home directory of this fold + let home=s:GetHome(infoline, parent_home) + if home != '' + if (foldlevel(foldlineno) == 1) && !s:IsAbsolutePath(home) + call confirm('Outermost Project Fold must have absolute path! Or perhaps the path does not exist.', "&OK", 1) + let home = '~' " Some 'reasonable' value + endif + endif + " Extract any CD information + let c_d = s:GetCd(infoline, home) + if c_d != '' + if (foldlevel(foldlineno) == 1) && !s:IsAbsolutePath(c_d) + call confirm('Outermost Project Fold must have absolute CD path! Or perhaps the path does not exist.', "&OK", 1) + let c_d = '.' " Some 'reasonable' value + endif + else + let c_d=parent_c_d + endif + " Extract scriptin + let scriptin = s:GetScriptin(infoline, home) + if scriptin == '' + let scriptin = parent_scriptin + endif + " Extract scriptout + let scriptout = s:GetScriptout(infoline, home) + if scriptout == '' + let scriptout = parent_scriptout + endif + " Extract filter + let filter = s:GetFilter(infoline, parent_filter) + if filter == '' | let filter = parent_filter | endif + return s:ConstructInfo(home, c_d, scriptin, scriptout, '', filter) + endfunction ">>> + " s:ConstructInfo(home, c_d, scriptin, scriptout, flags, filter) <<< + function! s:ConstructInfo(home, c_d, scriptin, scriptout, flags, filter) + let retval='Directory='.a:home + if a:c_d[0] != '' + let retval=retval.' CD='.a:c_d + endif + if a:scriptin[0] != '' + let retval=retval.' in='.a:scriptin + endif + if a:scriptout[0] != '' + let retval=retval.' out='.a:scriptout + endif + if a:filter[0] != '' + let retval=retval.' filter="'.a:filter.'"' + endif + return retval + endfunction ">>> + " s:OpenEntry(line, precmd, editcmd) <<< + " Get the filename under the cursor, and open a window with it. + function! s:OpenEntry(line, precmd, editcmd, dir) + silent exec a:precmd + if (a:editcmd[0] != '') + if a:dir + let fname='.' + else + if (foldlevel(a:line) == 0) && (a:editcmd[0] != '') + return 0 " If we're outside a fold, do nothing + endif + let fname=substitute(getline(a:line), '\s*#.*', '', '') " Get rid of comments and whitespace before comment + let fname=substitute(fname, '^\s*\(.*\)', '\1', '') " Get rid of leading whitespace + if strlen(fname) == 0 + return 0 " The line is blank. Do nothing. + endif + endif + else + let fname='.' + endif + let infoline = s:RecursivelyConstructDirectives(a:line) + let retval=s:OpenEntry2(a:line, infoline, fname, a:editcmd) + call s:DisplayInfo() + return retval + endfunction + ">>> + " s:OpenEntry2(line, infoline, precmd, editcmd) <<< + " Get the filename under the cursor, and open a window with it. + function! s:OpenEntry2(line, infoline, fname, editcmd) + let fname=escape(a:fname, ' %#') " Thanks to Thomas Link for cluing me in on % and # + let home=s:GetHome(a:infoline, '').'/' + if home=='/' + echoerr 'Project structure error. Check your syntax.' + return + endif + "Save the cd command + let cd_cmd = b:proj_cd_cmd + if a:editcmd[0] != '' " If editcmd is '', then just set up the environment in the Project Window + call s:DoSetupAndSplit() + " If it is an absolute path, don't prepend home + if !s:IsAbsolutePath(fname) + let fname=home.fname + endif + if s:IsAbsolutePath(fname) == 2 + exec a:editcmd.' '.fname + else + silent exec 'silent '.a:editcmd.' '.fname + endif + else " only happens in the Project File + exec 'au! BufEnter,BufLeave '.expand('%:p') + endif + " Extract any CD information + let c_d = s:GetCd(a:infoline, home) + if c_d != '' && (s:IsAbsolutePath(home) != 2) + if match(g:proj_flags, '\CL') != -1 + call s:SetupAutoCommand(c_d) + endif + if !isdirectory(glob(c_d)) + call confirm("From this fold's entry,\nCD=".'"'.c_d.'" is not a valid directory.', "&OK", 1) + else + silent exec cd_cmd.' '.c_d + endif + endif + " Extract any scriptin information + let scriptin = s:GetScriptin(a:infoline, home) + if scriptin != '' + if !filereadable(glob(scriptin)) + call confirm('"'.scriptin.'" not found. Ignoring.', "&OK", 1) + else + call s:SetupScriptAutoCommand('BufEnter', scriptin) + exec 'source '.scriptin + endif + endif + let scriptout = s:GetScriptout(a:infoline, home) + if scriptout != '' + if !filereadable(glob(scriptout)) + call confirm('"'.scriptout.'" not found. Ignoring.', "&OK", 1) + else + call s:SetupScriptAutoCommand('BufLeave', scriptout) + endif + endif + return 1 + endfunction + ">>> + " s:DoFoldOrOpenEntry(cmd0, cmd1) <<< + " Used for double clicking. If the mouse is on a fold, open/close it. If + " not, try to open the file. + function! s:DoFoldOrOpenEntry(cmd0, cmd1) + if getline('.')=~'{\|}' || foldclosed('.') != -1 + normal! za + else + call s:DoEnsurePlacementSize_au() + call s:OpenEntry(line('.'), a:cmd0, a:cmd1, 0) + if (match(g:proj_flags, '\Cc') != -1) + let g:proj_mywinnumber = winbufnr(0) + Project + hide + if(g:proj_mywinnumber != winbufnr(0)) + wincmd p + endif + wincmd = + endif + endif + endfunction ">>> + " s:VimDirListing(filter, padding, separator, filevariable, filecount, dirvariable, dircount) <<< + function! s:VimDirListing(filter, padding, separator, filevariable, filecount, dirvariable, dircount) + let end = 0 + let files='' + let filter = a:filter + " Chop up the filter + " Apparently glob() cannot take something like this: glob('*.c *.h') + let while_var = 1 + while while_var + let end = stridx(filter, ' ') + if end == -1 + let end = strlen(filter) + let while_var = 0 + endif + let single=glob(strpart(filter, 0, end)) + if strlen(single) != 0 + let files = files.single."\010" + endif + let filter = strpart(filter, end + 1) + endwhile + " files now contains a list of everything in the directory. We need to + " weed out the directories. + let fnames=files + let {a:filevariable}='' + let {a:dirvariable}='' + let {a:filecount}=0 + let {a:dircount}=0 + while strlen(fnames) > 0 + let fname = substitute(fnames, '\(\(\f\|[ :\[\]]\)*\).*', '\1', '') + let fnames = substitute(fnames, '\(\f\|[ :\[\]]\)*.\(.*\)', '\2', '') + if isdirectory(glob(fname)) + let {a:dirvariable}={a:dirvariable}.a:padding.fname.a:separator + let {a:dircount}={a:dircount} + 1 + else + let {a:filevariable}={a:filevariable}.a:padding.fname.a:separator + let {a:filecount}={a:filecount} + 1 + endif + endwhile + endfunction ">>> + " s:GenerateEntry(recursive, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) <<< + function! s:GenerateEntry(recursive, line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) + let line=a:line + if a:dir =~ '\\ ' + let dir='"'.substitute(a:dir, '\\ ', ' ', 'g').'"' + else + let dir=a:dir + endif + let spaces=strpart(' ', 0, a:foldlev) + let c_d=(strlen(a:c_d) > 0) ? 'CD='.a:c_d.' ' : '' + let c_d=(strlen(a:filter_directive) > 0) ? c_d.'filter="'.a:filter_directive.'" ': c_d + call append(line, spaces.'}') + call append(line, spaces.a:name.'='.dir.' '.c_d.'{') + if a:recursive + exec 'cd '.a:absolute_dir + call s:VimDirListing("*", '', "\010", 'b:files', 'b:filecount', 'b:dirs', 'b:dircount') + cd - + let dirs=b:dirs + let dcount=b:dircount + unlet b:files b:filecount b:dirs b:dircount + while dcount > 0 + let dname = substitute(dirs, '\(\( \|\f\|:\)*\).*', '\1', '') + let edname = escape(dname, ' ') + let dirs = substitute(dirs, '\( \|\f\|:\)*.\(.*\)', '\2', '') + let line=s:GenerateEntry(1, line + 1, dname, a:absolute_dir.'/'.edname, edname, '', '', a:filter, a:foldlev+1, a:sort) + let dcount=dcount-1 + endwhile + endif + return line+1 + endfunction " >>> + " s:DoEntryFromDir(line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) <<< + " Generate the fold from the directory hierarchy (if recursive), then + " fill it in with RefreshEntriesFromDir() + function! s:DoEntryFromDir(recursive, line, name, absolute_dir, dir, c_d, filter_directive, filter, foldlev, sort) + call s:GenerateEntry(a:recursive, a:line, a:name, escape(a:absolute_dir, ' '), escape(a:dir, ' '), escape(a:c_d, ' '), a:filter_directive, a:filter, a:foldlev, a:sort) + normal! j + call s:RefreshEntriesFromDir(1) + endfunction ">>> + " s:CreateEntriesFromDir(recursive) <<< + " Prompts user for information and then calls s:DoEntryFromDir() + function! s:CreateEntriesFromDir(recursive) + " Save a mark for the current cursor position + normal! mk + let line=line('.') + let name = inputdialog('Enter the Name of the Entry: ') + if strlen(name) == 0 + return + endif + let foldlev=foldlevel(line) + if (foldclosed(line) != -1) || (getline(line) =~ '}') + let foldlev=foldlev - 1 + endif + let absolute = (foldlev <= 0)?'Absolute ': '' + let home='' + let filter='*' + if (match(g:proj_flags, '\Cb') != -1) && has('browse') + " Note that browse() is inconsistent: On Win32 you can't select a + " directory, and it gives you a relative path. + let dir = browse(0, 'Enter the '.absolute.'Directory to Load: ', '', '') + let dir = fnamemodify(dir, ':p') + else + let dir = inputdialog('Enter the '.absolute.'Directory to Load: ', '') + endif + if (dir[strlen(dir)-1] == '/') || (dir[strlen(dir)-1] == '\\') + let dir=strpart(dir, 0, strlen(dir)-1) " Remove trailing / or \ + endif + let dir = substitute(dir, '^\~', $HOME, 'g') + if (foldlev > 0) + let parent_directive=s:RecursivelyConstructDirectives(line) + let filter = s:GetFilter(parent_directive, '*') + let home=s:GetHome(parent_directive, '') + if home[strlen(home)-1] != '/' && home[strlen(home)-1] != '\\' + let home=home.'/' + endif + unlet parent_directive + if s:IsAbsolutePath(dir) + " It is not a relative path Try to make it relative + let hend=matchend(dir, '\C'.glob(home)) + if hend != -1 + let dir=strpart(dir, hend) " The directory can be a relative path + else + let home="" + endif + endif + endif + if strlen(home.dir) == 0 + return + endif + if !isdirectory(home.dir) + if has("unix") + silent exec '!mkdir '.home.dir.' > /dev/null' + else + call confirm('"'.home.dir.'" is not a valid directory.', "&OK", 1) + return + endif + endif + let c_d = inputdialog('Enter the CD parameter: ', '') + let filter_directive = inputdialog('Enter the File Filter: ', '') + if strlen(filter_directive) != 0 + let filter = filter_directive + endif + " If I'm on a closed fold, go to the bottom of it + if foldclosedend(line) != -1 + let line = foldclosedend(line) + endif + let foldlev = foldlevel(line) + " If we're at the end of a fold . . . + if getline(line) =~ '}' + let foldlev = foldlev - 1 " . . . decrease the indentation by 1. + endif + " Do the work + call s:DoEntryFromDir(a:recursive, line, name, home.dir, dir, c_d, filter_directive, filter, foldlev, 0) + " Restore the cursor position + normal! `k + endfunction ">>> + " s:RefreshEntriesFromDir(recursive) <<< + " Finds metadata at the top of the fold, and then replaces all files + " with the contents of the directory. Works recursively if recursive is 1. + function! s:RefreshEntriesFromDir(recursive) + if foldlevel('.') == 0 + echo 'Nothing to refresh.' + return + endif + " Open the fold. + if getline('.') =~ '}' + normal! zo[z + else + normal! zo]z[z + endif + let just_a_fold=0 + let infoline = s:RecursivelyConstructDirectives(line('.')) + let immediate_infoline = getline('.') + if strlen(substitute(immediate_infoline, '[^=]*=\(\(\f\|:\|\\ \)*\).*', '\1', '')) == strlen(immediate_infoline) + let just_a_fold = 1 + endif + " Extract the home directory of the fold + let home = s:GetHome(infoline, '') + if home == '' + " No Match. This means that this is just a label with no + " directory entry. + if a:recursive == 0 + return " We're done--nothing to do + endif + " Mark that it is just a fold, so later we don't delete filenames + " that aren't there. + let just_a_fold = 1 + endif + if just_a_fold == 0 + " Extract the filter between quotes (we don't care what CD is). + let filter = s:GetFilter(infoline, '*') + " Extract the description (name) of the fold + let name = substitute(infoline, '^[#\t ]*\([^=]*\)=.*', '\1', '') + if strlen(name) == strlen(infoline) + return " If there's no name, we're done. + endif + if (home == '') || (name == '') + return + endif + " Extract the flags + let flags = s:GetFlags(immediate_infoline) + let sort = (match(g:proj_flags, '\CS') != -1) + if flags != '' + if match(flags, '\Cr') != -1 + " If the flags do not contain r (refresh), then treat it just + " like a fold + let just_a_fold = 1 + endif + if match(flags, '\CS') != -1 + let sort = 1 + endif + if match(flags, '\Cs') != -1 + let sort = 0 + endif + else + let flags='' + endif + endif + " Move to the first non-fold boundary line + normal! j + " Delete filenames until we reach the end of the fold + while getline('.') !~ '}' + if line('.') == line('$') + break + endif + if getline('.') !~ '{' + " We haven't reached a sub-fold, so delete what's there. + if (just_a_fold == 0) && (getline('.') !~ '^\s*#') && (getline('.') !~ '#.*pragma keep') + d _ + else + " Skip lines only in a fold and comment lines + normal! j + endif + else + " We have reached a sub-fold. If we're doing recursive, then + " call this function again. If not, find the end of the fold. + if a:recursive == 1 + call s:RefreshEntriesFromDir(1) + normal! ]zj + else + if foldclosed('.') == -1 + normal! zc + endif + normal! j + endif + endif + endwhile + if just_a_fold == 0 + " We're not just in a fold, and we have deleted all the filenames. + " Now it is time to regenerate what is in the directory. + if !isdirectory(glob(home)) + call confirm('"'.home.'" is not a valid directory.', "&OK", 1) + else + let foldlev=foldlevel('.') + " T flag. Thanks Tomas Z. + if (match(flags, '\Ct') != -1) || ((match(g:proj_flags, '\CT') == -1) && (match(flags, '\CT') == -1)) + " Go to the top of the fold (force other folds to the + " bottom) + normal! [z + normal! j + " Skip any comments + while getline('.') =~ '^\s*#' + normal! j + endwhile + endif + normal! k + let cwd=getcwd() + let spaces=strpart(' ', 0, foldlev) + exec 'cd '.home + if match(g:proj_flags, '\Ci') != -1 + echon home."\r" + endif + call s:VimDirListing(filter, spaces, "\n", 'b:files', 'b:filecount', 'b:dirs', 'b:dircount') + if b:filecount > 0 + normal! mk + silent! put =b:files + normal! `kj + if sort + call s:SortR(line('.'), line('.') + b:filecount - 1) + endif + else + normal! j + endif + unlet b:files b:filecount b:dirs b:dircount + exec 'cd '.cwd + endif + endif + " Go to the top of the refreshed fold. + normal! [z + endfunction ">>> + " s:MoveUp() <<< + " Moves the entity under the cursor up a line. + function! s:MoveUp() + let lineno=line('.') + if lineno == 1 + return + endif + let fc=foldclosed('.') + let a_reg=@a + if lineno == line('$') + normal! "add"aP + else + normal! "addk"aP + endif + let @a=a_reg + if fc != -1 + normal! zc + endif + endfunction ">>> + " s:MoveDown() <<< + " Moves the entity under the cursor down a line. + function! s:MoveDown() + let fc=foldclosed('.') + let a_reg=@a + normal! "add"ap + let @a=a_reg + if (fc != -1) && (foldclosed('.') == -1) + normal! zc + endif + endfunction " >>> + " s:DisplayInfo() <<< + " Displays filename and current working directory when i (info) is in + " the flags. + function! s:DisplayInfo() + if match(g:proj_flags, '\Ci') != -1 + echo 'file: '.expand('%').', cwd: '.getcwd().', lines: '.line('$') + endif + endfunction ">>> + " s:SetupAutoCommand(cwd) <<< + " Sets up an autocommand to ensure that the cwd is set to the one + " desired for the fold regardless. :lcd only does this on a per-window + " basis, not a per-buffer basis. + function! s:SetupAutoCommand(cwd) + if !exists("b:proj_has_autocommand") + let b:proj_cwd_save = escape(getcwd(), ' ') + let b:proj_has_autocommand = 1 + let bufname=escape(substitute(expand('%:p', 0), '\\', '/', 'g'), ' ') + exec 'au BufEnter '.bufname." let b:proj_cwd_save=escape(getcwd(), ' ') | cd ".a:cwd + exec 'au BufLeave '.bufname.' exec "cd ".b:proj_cwd_save' + exec 'au BufWipeout '.bufname.' au! * '.bufname + endif + endfunction ">>> + " s:SetupScriptAutoCommand(bufcmd, script) <<< + " Sets up an autocommand to run the scriptin script. + function! s:SetupScriptAutoCommand(bufcmd, script) + if !exists("b:proj_has_".a:bufcmd) + let b:proj_has_{a:bufcmd} = 1 + exec 'au '.a:bufcmd.' '.escape(substitute(expand('%:p', 0), '\\', '/', 'g'), ' ').' source '.a:script + endif + endfunction " >>> + " s:DoEnsurePlacementSize_au() <<< + " Ensure that the Project window is on the left of the window and has + " the correct size. Only called from an autocommand + function! s:DoEnsurePlacementSize_au() + if (winbufnr(0) != g:proj_running) || (winnr() != 1) + if exists("g:proj_doinghelp") + if g:proj_doinghelp > 0 + let g:proj_doinghelp = g:proj_doinghelp - 1 + return + endif + unlet g:proj_doinghelp + return + endif + exec b:proj_locate_command + endif + exec b:proj_resize_command + endfunction ">>> + " s:Spawn(number) <<< + " Spawn an external command on the file + function! s:Spawn(number) + echo | if exists("g:proj_run".a:number) + let fname=getline('.') + if fname!~'{\|}' + let fname=substitute(fname, '\s*#.*', '', '') + let fname=substitute(fname, '^\s*\(.*\)\s*', '\1', '') + if fname == '' | return | endif + let parent_infoline = s:RecursivelyConstructDirectives(line('.')) + let home=expand(s:GetHome(parent_infoline, '')) + let c_d=expand(s:GetCd(parent_infoline, '')) + let command=substitute(g:proj_run{a:number}, '%%', "\010", 'g') + let command=substitute(command, '%f', escape(home.'/'.fname, '\'), 'g') + let command=substitute(command, '%F', substitute(escape(home.'/'.fname, '\'), ' ', '\\\\ ', 'g'), 'g') + let command=substitute(command, '%s', escape(home.'/'.fname, '\'), 'g') + let command=substitute(command, '%n', escape(fname, '\'), 'g') + let command=substitute(command, '%N', substitute(fname, ' ', '\\\\ ', 'g'), 'g') + let command=substitute(command, '%h', escape(home, '\'), 'g') + let command=substitute(command, '%H', substitute(escape(home, '\'), ' ', '\\\\ ', 'g'), 'g') + if c_d != '' + if c_d == home + let percent_r='.' + else + let percent_r=substitute(home, escape(c_d.'/', '\'), '', 'g') + endif + else + let percent_r=home + endif + let command=substitute(command, '%r', percent_r, 'g') + let command=substitute(command, '%R', substitute(percent_r, ' ', '\\\\ ', 'g'), 'g') + let command=substitute(command, '%d', escape(c_d, '\'), 'g') + let command=substitute(command, '%D', substitute(escape(c_d, '\'), ' ', '\\\\ ', 'g'), 'g') + let command=substitute(command, "\010", '%', 'g') + exec command + endif + endif + endfunction ">>> + " s:ListSpawn(varnamesegment) <<< + " List external commands + function! s:ListSpawn(varnamesegment) + let number = 1 + while number < 10 + if exists("g:proj_run".a:varnamesegment.number) + echohl LineNr | echo number.':' | echohl None | echon ' '.substitute(escape(g:proj_run{a:varnamesegment}{number}, '\'), "\n", '\\n', 'g') + else + echohl LineNr | echo number.':' | echohl None + endif + let number=number + 1 + endwhile + endfunction ">>> + " s:FindFoldTop(line) <<< + " Return the line number of the directive line + function! s:FindFoldTop(line) + let lineno=a:line + if getline(lineno) =~ '}' + let lineno = lineno - 1 + endif + while getline(lineno) !~ '{' && lineno > 1 + if getline(lineno) =~ '}' + let lineno=s:FindFoldTop(lineno) + endif + let lineno = lineno - 1 + endwhile + return lineno + endfunction ">>> + " s:FindFoldBottom(line) <<< + " Return the line number of the directive line + function! s:FindFoldBottom(line) + let lineno=a:line + if getline(lineno) =~ '{' + let lineno=lineno + 1 + endif + while getline(lineno) !~ '}' && lineno < line('$') + if getline(lineno) =~ '{' + let lineno=s:FindFoldBottom(lineno) + endif + let lineno = lineno + 1 + endwhile + return lineno + endfunction ">>> + " s:LoadAll(recurse, line) <<< + " Load all files in a project + function! s:LoadAll(recurse, line) + let b:loadcount=0 + function! s:SpawnExec(infoline, fname, lineno, data) + if s:OpenEntry2(a:lineno, a:infoline, a:fname, 'e') + wincmd p + let b:loadcount=b:loadcount+1 + echon b:loadcount."\r" + if getchar(0) != 0 + let b:stop_everything=1 + endif + endif + endfunction + call Project_ForEach(a:recurse, line('.'), "*SpawnExec", 0, '^\(.*l\)\@!') + delfunction s:SpawnExec + echon b:loadcount." Files Loaded\r" + unlet b:loadcount + if exists("b:stop_everything") | unlet b:stop_everything | endif + endfunction ">>> + " s:WipeAll(recurse, line) <<< + " Wipe all files in a project + function! s:WipeAll(recurse, line) + let b:wipecount=0 + let b:totalcount=0 + function! s:SpawnExec(home, c_d, fname, lineno, data) + let fname=escape(a:fname, ' ') + if s:IsAbsolutePath(fname) + let fname=fnamemodify(fname, ':n') " :n is coming, won't break anything now + else + let fname=fnamemodify(a:home.'/'.fname, ':n') " :n is coming, won't break anything now + endif + let b:totalcount=b:totalcount+1 + let fname=substitute(fname, '^\~', $HOME, 'g') + if bufloaded(substitute(fname, '\\ ', ' ', 'g')) + if getbufvar(fname.'\>', '&modified') == 1 + exec 'sb '.fname + wincmd L + w + wincmd p + endif + let b:wipecount=b:wipecount+1 + exec 'bwipe! '.fname + endif + if b:totalcount % 5 == 0 + echon b:wipecount.' of '.b:totalcount."\r" + redraw + endif + if getchar(0) != 0 + let b:stop_everything=1 + endif + endfunction + call Project_ForEach(a:recurse, line('.'), "SpawnExec", 0, '^\(.*w\)\@!') + delfunction s:SpawnExec + echon b:wipecount.' of '.b:totalcount." Files Wiped\r" + unlet b:wipecount b:totalcount + if exists("b:stop_everything") | unlet b:stop_everything | endif + endfunction ">>> + " s:LoadAllSplit(recurse, line) <<< + " Load all files in a project using split windows. + " Contributed by A. Harrison + function! s:LoadAllSplit(recurse, line) + let b:loadcount=0 + function! s:SpawnExec(infoline, fname, lineno, data) + let winNr = winnr() "get ProjectWindow number + if s:OpenEntry2(a:lineno, a:infoline, a:fname, 'sp') + exec winNr."wincmd w" + let b:loadcount=b:loadcount+1 + echon b:loadcount."\r" + if getchar(0) != 0 + let b:stop_everything=1 + endif + endif + endfunction + call Project_ForEach(a:recurse, line('.'), "*SpawnExec", 0, '^\(.*l\)\@!') + delfunction s:SpawnExec + echon b:loadcount." Files Loaded\r" + unlet b:loadcount + if exists("b:stop_everything") | unlet b:stop_everything | endif + endfunction ">>> + " s:GrepAll(recurse, lineno, pattern) <<< + " Grep all files in a project, optionally recursively + function! s:GrepAll(recurse, lineno, pattern) + cunmap help + let pattern=(a:pattern[0] == '')?input("GREP options and pattern: "):a:pattern + cnoremap help let g:proj_doinghelp = 1:help + if pattern[0] == '' + return + endif + let b:escape_spaces=1 + let fnames=Project_GetAllFnames(a:recurse, a:lineno, ' ') + unlet b:escape_spaces + cclose " Make sure grep window is closed + call s:DoSetupAndSplit() + if match(g:proj_flags, '\Cv') == -1 + silent! exec 'silent! grep '.pattern.' '.fnames + if v:shell_error != 0 + echo 'GREP error. Perhaps there are too many filenames.' + else + copen + endif + else + silent! exec 'silent! vimgrep '.pattern.' '.fnames + copen + endif + endfunction ">>> + " GetXXX Functions <<< + function! s:GetHome(info, parent_home) + " Thanks to Adam Montague for pointing out the need for @ in urls. + let home=substitute(a:info, '^[^=]*=\(\(\\ \|\f\|:\|@\)\+\).*', '\1', '') + if strlen(home) == strlen(a:info) + let home=substitute(a:info, '.\{-}"\(.\{-}\)".*', '\1', '') + if strlen(home) != strlen(a:info) | let home=escape(home, ' ') | endif + endif + if strlen(home) == strlen(a:info) + let home=a:parent_home + elseif home=='.' + let home=a:parent_home + elseif !s:IsAbsolutePath(home) + let home=a:parent_home.'/'.home + endif + return home + endfunction + function! s:GetFilter(info, parent_filter) + let filter = substitute(a:info, '.*\>> + " Project_GetAllFnames(recurse, lineno, separator) <<< + " Grep all files in a project, optionally recursively + function! Project_GetAllFnames(recurse, lineno, separator) + let b:fnamelist='' + function! s:SpawnExec(home, c_d, fname, lineno, data) + if exists('b:escape_spaces') + let fname=escape(a:fname, ' ') + else + let fname=a:fname + endif + if !s:IsAbsolutePath(a:fname) + let fname=a:home.'/'.fname + endif + let b:fnamelist=b:fnamelist.a:data.fname + endfunction + call Project_ForEach(a:recurse, line('.'), "SpawnExec", a:separator, '') + delfunction s:SpawnExec + let retval=b:fnamelist + unlet b:fnamelist + return retval + endfunction ">>> + " Project_GetAllFnames(recurse, lineno, separator) <<< + " Grep all files in a project, optionally recursively + function! Project_GetFname(line) + if (foldlevel(a:line) == 0) + return '' + endif + let fname=substitute(getline(a:line), '\s*#.*', '', '') " Get rid of comments and whitespace before comment + let fname=substitute(fname, '^\s*\(.*\)', '\1', '') " Get rid of leading whitespace + if strlen(fname) == 0 + return '' " The line is blank. Do nothing. + endif + if s:IsAbsolutePath(fname) + return fname + endif + let infoline = s:RecursivelyConstructDirectives(a:line) + return s:GetHome(infoline, '').'/'.fname + endfunction ">>> + " Project_ForEach(recurse, lineno, cmd, data, match) <<< + " Grep all files in a project, optionally recursively + function! Project_ForEach(recurse, lineno, cmd, data, match) + let info=s:RecursivelyConstructDirectives(a:lineno) + let lineno=s:FindFoldTop(a:lineno) + 1 + let flags=s:GetFlags(getline(lineno - 1)) + if (flags == '') || (a:match=='') || (match(flags, a:match) != -1) + call s:Project_ForEachR(a:recurse, lineno, info, a:cmd, a:data, a:match) + endif + endfunction + function! s:Project_ForEachR(recurse, lineno, info, cmd, data, match) + let home=s:GetHome(a:info, '') + let c_d=s:GetCd(a:info, home) + let scriptin = s:GetScriptin(a:info, home) + let scriptout = s:GetScriptout(a:info, home) + let filter = s:GetFilter(a:info, '') + let lineno = a:lineno + let curline=getline(lineno) + while (curline !~ '}') && (curline < line('$')) + if exists("b:stop_everything") && b:stop_everything | return 0 | endif + if curline =~ '{' + if a:recurse + let flags=s:GetFlags(curline) + if (flags == '') || (a:match=='') || (match(flags, a:match) != -1) + let this_home=s:GetHome(curline, home) + let this_cd=s:GetCd(curline, this_home) + if this_cd=='' | let this_cd=c_d | endif + let this_scriptin=s:GetScriptin(curline, this_home) + if this_scriptin == '' | let this_scriptin=scriptin | endif + let this_scriptout=s:GetScriptin(curline, this_home) + if this_scriptout == '' | let this_scriptout=scriptout | endif + let this_filter=s:GetFilter(curline, filter) + let lineno=s:Project_ForEachR(1, lineno+1, + \s:ConstructInfo(this_home, this_cd, this_scriptin, this_scriptout, flags, this_filter), a:cmd, a:data, a:match) + else + let lineno=s:FindFoldBottom(lineno) + endif + else + let lineno=s:FindFoldBottom(lineno) + endif + else + let fname=substitute(curline, '\s*#.*', '', '') + let fname=substitute(fname, '^\s*\(.*\)', '\1', '') + if (strlen(fname) != strlen(curline)) && (fname[0] != '') + if a:cmd[0] == '*' + call {strpart(a:cmd, 1)}(a:info, fname, lineno, a:data) + else + call {a:cmd}(home, c_d, fname, lineno, a:data) + endif + endif + endif + let lineno=lineno + 1 + let curline=getline(lineno) + endwhile + return lineno + endfunction ">>> + " s:SpawnAll(recurse, number) <<< + " Spawn an external command on the files of a project + function! s:SpawnAll(recurse, number) + echo | if exists("g:proj_run_fold".a:number) + if g:proj_run_fold{a:number}[0] == '*' + function! s:SpawnExec(home, c_d, fname, lineno, data) + let command=substitute(strpart(g:proj_run_fold{a:data}, 1), '%s', escape(a:fname, ' \'), 'g') + let command=substitute(command, '%f', escape(a:fname, '\'), 'g') + let command=substitute(command, '%h', escape(a:home, '\'), 'g') + let command=substitute(command, '%d', escape(a:c_d, '\'), 'g') + let command=substitute(command, '%F', substitute(escape(a:fname, '\'), ' ', '\\\\ ', 'g'), 'g') + exec command + endfunction + call Project_ForEach(a:recurse, line('.'), "SpawnExec", a:number, '.') + delfunction s:SpawnExec + else + let info=s:RecursivelyConstructDirectives(line('.')) + let home=s:GetHome(info, '') + let c_d=s:GetCd(info, '') + let b:escape_spaces=1 + let fnames=Project_GetAllFnames(a:recurse, line('.'), ' ') + unlet b:escape_spaces + let command=substitute(g:proj_run_fold{a:number}, '%f', substitute(escape(fnames, '\'), '\\ ', ' ', 'g'), 'g') + let command=substitute(command, '%s', escape(fnames, '\'), 'g') + let command=substitute(command, '%h', escape(home, '\'), 'g') + let command=substitute(command, '%d', escape(c_d, '\'), 'g') + let command=substitute(command, '%F', escape(fnames, '\'), 'g') + exec command + if v:shell_error != 0 + echo 'Shell error. Perhaps there are too many filenames.' + endif + endif + endif + endfunction ">>> + if !exists("g:proj_running") + " s:DoProjectOnly(void) <<< + " Make the file window the only one. + function! s:DoProjectOnly() + if winbufnr(0) != g:proj_running + let lzsave=&lz + set lz + only + Project + silent! wincmd p + let &lz=lzsave + unlet lzsave + endif + endfunction + " >>> + + " Mappings <<< + nnoremap \|:call DoFoldOrOpenEntry('', 'e') + nnoremap \|:call DoFoldOrOpenEntry('', 'sp') + nnoremap \|:call DoFoldOrOpenEntry('silent! only', 'e') + nnoremap T \|:call DoFoldOrOpenEntry('', 'tabe') + nmap s + nnoremap S \|:call LoadAllSplit(0, line('.')) + nmap o + nnoremap i :echo RecursivelyConstructDirectives(line('.')) + nnoremap I :echo Project_GetFname(line('.')) + nmap p + nmap v + nnoremap l \|:call LoadAll(0, line('.')) + nnoremap L \|:call LoadAll(1, line('.')) + nnoremap w \|:call WipeAll(0, line('.')) + nnoremap W \|:call WipeAll(1, line('.')) + nnoremap W \|:call WipeAll(1, line('.')) + nnoremap g \|:call GrepAll(0, line('.'), "") + nnoremap G \|:call GrepAll(1, line('.'), "") + nnoremap <2-LeftMouse> \|:call DoFoldOrOpenEntry('', 'e') + nnoremap \|:call DoFoldOrOpenEntry('', 'sp') + nnoremap + nnoremap + nmap + nnoremap + nnoremap <3-LeftMouse> + nmap + nmap <2-RightMouse> + nmap <3-RightMouse> + nmap <4-RightMouse> + nnoremap \|:silent exec 'vertical resize '.(match(g:proj_flags, '\Ct')!=-1 && winwidth('.') > g:proj_window_width?(g:proj_window_width):(winwidth('.') + g:proj_window_increment)) + nnoremap \|:silent call MoveUp() + nnoremap \|:silent call MoveDown() + nmap + nmap + let k=1 + while k < 10 + exec 'nnoremap '.k.' \|:call Spawn('.k.')' + exec 'nnoremap f'.k.' \|:call SpawnAll(0, '.k.')' + exec 'nnoremap F'.k.' \|:call SpawnAll(1, '.k.')' + let k=k+1 + endwhile + nnoremap 0 \|:call ListSpawn("") + nnoremap f0 \|:call ListSpawn("_fold") + nnoremap F0 \|:call ListSpawn("_fold") + nnoremap c :call CreateEntriesFromDir(0) + nnoremap C :call CreateEntriesFromDir(1) + nnoremap r :call RefreshEntriesFromDir(0) + nnoremap R :call RefreshEntriesFromDir(1) + " For Windows users: same as \R + nnoremap :call RefreshEntriesFromDir(1) + nnoremap e :call OpenEntry(line('.'), '', '', 0) + nnoremap E :call OpenEntry(line('.'), '', 'e', 1) + " The :help command stomps on the Project Window. Try to avoid that. + " This is not perfect, but it is alot better than without the mappings. + cnoremap help let g:proj_doinghelp = 1:help + nnoremap :let g:proj_doinghelp = 1 + " This is to avoid changing the buffer, but it is not fool-proof. + nnoremap + "nnoremap