Commit fa42d243 authored by Murukesh Mohanan's avatar Murukesh Mohanan

Initialized vim

parents
.VimballRecord
.netrwhist
[submodule "bundle/diffchar.vim"]
path = bundle/diffchar.vim
url = https://github.com/vim-scripts/diffchar.vim
[submodule "bundle/eregex.vim"]
path = bundle/eregex.vim
url = https://github.com/othree/eregex.vim.git
[submodule "bundle/nerdtree"]
path = bundle/nerdtree
url = https://github.com/scrooloose/nerdtree.git
[submodule "bundle/supertab"]
path = bundle/supertab
url = git@github.com:ervandew/supertab.git
[submodule "bundle/syntastic"]
path = bundle/syntastic
url = https://github.com/scrooloose/syntastic.git
[submodule "bundle/vim2hs"]
path = bundle/vim2hs
url = https://github.com/dag/vim2hs
[submodule "bundle/vim-surround"]
path = bundle/vim-surround
url = https://github.com/tpope/vim-surround.git
" Vim autoload file for browsing debian package.
" copyright (C) 2007-2008, arno renevier <arenevier@fdn.fr>
" Distributed under the GNU General Public License (version 2 or above)
" Last Change: 2008 april 1
"
" Inspired by autoload/tar.vim by Charles E Campbell
"
" Latest version of that file can be found at
" http://www.fdn.fr/~arenevier/vim/autoload/deb.vim
" It should also be available at
" http://www.vim.org/scripts/script.php?script_id=1970
if &cp || exists("g:loaded_deb") || v:version < 700
finish
endif
let g:loaded_deb= "v1.4"
fun! deb#read(debfile, member)
" checks if ar and tar are installed
if !s:hascmd("ar") || !s:hascmd("tar")
return
endif
let l:target = a:member
let l:archmember = s:dataFileName(a:debfile) " default archive member to extract
if l:archmember == ""
echohl WarningMsg | echo "***error*** (deb#read) no valid data file found in debian archive"
return
elseif l:archmember == "data.tar.gz"
let l:unpcmp = "tar zxfO "
elseif l:archmember == "data.tar.bz2"
let l:unpcmp = "tar jxfO "
elseif l:archmember == "data.tar.lzma"
if !s:hascmd("lzma")
return
endif
let l:unpcmp = "lzma -d | tar xfO "
elseif l:archmember == "data.tar"
let l:unpcmp = "tar xfO "
endif
if a:member =~ '^\* ' " information control file
let l:archmember = "control.tar.gz"
let l:target = substitute(l:target, "^\* ", "", "")
let l:unpcmp = "tar zxfO "
elseif a:member =~ ' -> ' " symbolic link
let l:target = split(a:member,' -> ')[0]
let l:linkname = split(a:member,' -> ')[1]
if l:linkname =~ "^\/" " direct symlink: path is already absolute
let l:target = ".".l:linkname
else
" transform relative path to absolute path
" first, get basename for target
let l:target = substitute(l:target, "\/[^/]*$", "", "")
" while it begins with ../
while l:linkname =~ "^\.\.\/"
" removes one level of ../ in linkname
let l:linkname = substitute(l:linkname, "^\.\.\/", "", "")
" go one directory up in target
let l:target = substitute(l:target, "\/[^/]*$", "", "")
endwhile
let l:target = l:target."/".l:linkname
endif
endif
" we may preprocess some files (such as man pages, or changelogs)
let l:preproccmd = ""
"
" unzip man pages
"
if l:target =~ "\.\/usr\/share\/man\/.*\.gz$"
" try to fail gracefully if a command is not available
if !s:hascmd("gzip")
return
elseif !s:hascmd("nroff")
let l:preproccmd = "| gzip -cd"
elseif !s:hascmd("col")
let l:preproccmd = "| gzip -cd | nroff -mandoc"
else
let l:preproccmd = "| gzip -cd | nroff -mandoc | col -b"
endif
"
" unzip other .gz files
"
elseif l:target =~ '.*\.gz$'
if !s:hascmd("gzip")
return
endif
let l:preproccmd = "| gzip -cd"
endif
" read content
exe "silent r! ar p " . s:QuoteFile(a:debfile) . " " . s:QuoteFile(l:archmember) . " | " . l:unpcmp . " - " . s:QuoteFile(l:target) . l:preproccmd
" error will be treated in calling function
if v:shell_error != 0
return
endif
exe "file deb:".l:target
0d
setlocal nomodifiable nomodified readonly
endfun
fun! deb#browse(file)
" checks if necessary utils are installed
if !s:hascmd("dpkg") || !s:hascmd("ar") || !s:hascmd("tar")
return
endif
" checks if file is readable
if !filereadable(a:file)
return
endif
if a:file =~ "'"
echohl WarningMsg | echo "***error*** (deb#Browse) filename cannot contain quote character (" . a:file . ")"
return
endif
let keepmagic = &magic
set magic
" set filetype to "deb"
set ft=deb
setlocal modifiable noreadonly
" set header
exe "$put ='".'\"'." deb.vim version ".g:loaded_deb."'"
exe "$put ='".'\"'." Browsing debian package ".a:file."'"
$put=''
" package info
"exe "silent read! dpkg -I ".a:file
"$put=''
" display information control files
let l:infopos = line(".")
exe "silent read! ar p " . s:QuoteFile(a:file) . " control.tar.gz | tar zt"
$put=''
" display data files
let l:listpos = line(".")
exe "silent read! dpkg -c ". s:QuoteFile(a:file)
" format information control list
" removes '* ./' line
exe (l:infopos + 1). 'd'
" add a star before each line
exe "silent " . (l:infopos + 1). ',' . (l:listpos - 2) . 's/^/\* /'
" format data list
exe "silent " . l:listpos . ',$s/^.*\s\(\.\/\(\S\|\).*\)$/\1/'
if v:shell_error != 0
echohl WarningMsg | echo "***warning*** (deb#Browse) error when listing content of " . a:file
let &magic = keepmagic
return
endif
0d
setlocal nomodifiable readonly
noremap <silent> <buffer> <cr> :call <SID>DebBrowseSelect()<cr>
let &magic = keepmagic
endfun
fun! s:DebBrowseSelect()
let l:fname= getline(".")
" sanity check
if (l:fname !~ '^\.\/') && (l:fname !~ '^\* \.\/')
return
endif
if l:fname =~ "'"
echohl WarningMsg | echo "***error*** (DebBrowseSelect) filename cannot contain quote character (" . l:fname . ")"
return
endif
" do nothing on directories
" TODO: find a way to detect symlinks to directories, to be able not to
" open them
if (l:fname =~ '\/$')
return
endif
" need to get it now since a new window will open
let l:curfile= expand("%")
" open new window
new
wincmd _
call deb#read(l:curfile, l:fname)
if v:shell_error != 0
echohl WarningMsg | echo "***warning*** (DebBrowseSelect) error when reading " . l:fname
return
endif
filetype detect
" zipped files, are unziped in deb#read, but filetype may not
" automatically work.
if l:fname =~ "\.\/usr\/share\/man\/.*\.gz$"
set filetype=man
elseif l:fname =~ "\.\/usr\/share\/doc\/.*\/changelog.Debian.gz$"
set filetype=debchangelog
endif
endfun
" return data file name for debian package. This can be either data.tar.gz,
" data.tar.bz2 or data.tar.lzma
fun s:dataFileName(deb)
for fn in ["data.tar.gz", "data.tar.bz2", "data.tar.lzma", "data.tar"]
" [0:-2] is to remove trailing null character from command output
if (system("ar t " . "'" . a:deb . "'" . " " . fn))[0:-2] == fn
return fn
endif
endfor
return "" " no debian data format in this archive
endfun
fun s:QuoteFile(file)
" we need to escape %, #, <, and >
" see :help cmdline-specialk
return "'" . substitute(a:file, '\([%#<>]\)', '\\\1', 'g') . "'"
endfun
" return 1 if cmd exists
" display error message and return 0 otherwise
fun s:hascmd(cmd)
if executable(a:cmd)
return 1
else
echohl Error | echo "***error*** " . a:cmd . " not available on your system"
return 0
else
endfu
"
" utility functions for haskellmode plugins
"
" (Claus Reinke; last modified: 22/06/2010)
"
" part of haskell plugins: http://projects.haskell.org/haskellmode-vim
" please send patches to <claus.reinke@talk21.com>
" find start/extent of name/symbol under cursor;
" return start, symbolic flag, qualifier, unqualified id
" (this is used in both haskell_doc.vim and in GHC.vim)
function! haskellmode#GetNameSymbol(line,col,off)
let name = "[a-zA-Z0-9_']"
let symbol = "[-!#$%&\*\+/<=>\?@\\^|~:.]"
"let [line] = getbufline(a:buf,a:lnum)
let line = a:line
" find the beginning of unqualified id or qualified id component
let start = (a:col - 1) + a:off
if line[start] =~ name
let pattern = name
elseif line[start] =~ symbol
let pattern = symbol
else
return []
endif
while start > 0 && line[start - 1] =~ pattern
let start -= 1
endwhile
let id = matchstr(line[start :],pattern.'*')
" call confirm(id)
" expand id to left and right, to get full id
let idPos = id[0] == '.' ? start+2 : start+1
let posA = match(line,'\<\(\([A-Z]'.name.'*\.\)\+\)\%'.idPos.'c')
let start = posA>-1 ? posA+1 : idPos
let posB = matchend(line,'\%'.idPos.'c\(\([A-Z]'.name.'*\.\)*\)\('.name.'\+\|'.symbol.'\+\)')
let end = posB>-1 ? posB : idPos
" special case: symbolic ids starting with .
if id[0]=='.' && posA==-1
let start = idPos-1
let end = posB==-1 ? start : end
endif
" classify full id and split into qualifier and unqualified id
let fullid = line[ (start>1 ? start-1 : 0) : (end-1) ]
let symbolic = fullid[-1:-1] =~ symbol " might also be incomplete qualified id ending in .
let qualPos = matchend(fullid, '\([A-Z]'.name.'*\.\)\+')
let qualifier = qualPos>-1 ? fullid[ 0 : (qualPos-2) ] : ''
let unqualId = qualPos>-1 ? fullid[ qualPos : -1 ] : fullid
" call confirm(start.'/'.end.'['.symbolic.']:'.qualifier.' '.unqualId)
return [start,symbolic,qualifier,unqualId]
endfunction
function! haskellmode#GatherImports()
let imports={0:{},1:{}}
let i=1
while i<=line('$')
let res = haskellmode#GatherImport(i)
if !empty(res)
let [i,import] = res
let prefixPat = '^import\s*\%({-#\s*SOURCE\s*#-}\)\?\(qualified\)\?\s\+'
let modulePat = '\([A-Z][a-zA-Z0-9_''.]*\)'
let asPat = '\(\s\+as\s\+'.modulePat.'\)\?'
let hidingPat = '\(\s\+hiding\s*\((.*)\)\)\?'
let listPat = '\(\s*\((.*)\)\)\?'
let importPat = prefixPat.modulePat.asPat.hidingPat.listPat ".'\s*$'
let ml = matchlist(import,importPat)
if ml!=[]
let [_,qualified,module,_,as,_,hiding,_,explicit;x] = ml
let what = as=='' ? module : as
let hidings = split(hiding[1:-2],',')
let explicits = split(explicit[1:-2],',')
let empty = {'lines':[],'hiding':hidings,'explicit':[],'modules':[]}
let entry = has_key(imports[1],what) ? imports[1][what] : deepcopy(empty)
let imports[1][what] = haskellmode#MergeImport(deepcopy(entry),i,hidings,explicits,module)
if !(qualified=='qualified')
let imports[0][what] = haskellmode#MergeImport(deepcopy(entry),i,hidings,explicits,module)
endif
else
echoerr "haskellmode#GatherImports doesn't understand: ".import
endif
endif
let i+=1
endwhile
if !has_key(imports[1],'Prelude')
let imports[0]['Prelude'] = {'lines':[],'hiding':[],'explicit':[],'modules':[]}
let imports[1]['Prelude'] = {'lines':[],'hiding':[],'explicit':[],'modules':[]}
endif
return imports
endfunction
function! haskellmode#ListElem(list,elem)
for e in a:list | if e==a:elem | return 1 | endif | endfor
return 0
endfunction
function! haskellmode#ListIntersect(list1,list2)
let l = []
for e in a:list1 | if index(a:list2,e)!=-1 | let l += [e] | endif | endfor
return l
endfunction
function! haskellmode#ListUnion(list1,list2)
let l = []
for e in a:list2 | if index(a:list1,e)==-1 | let l += [e] | endif | endfor
return a:list1 + l
endfunction
function! haskellmode#ListWithout(list1,list2)
let l = []
for e in a:list1 | if index(a:list2,e)==-1 | let l += [e] | endif | endfor
return l
endfunction
function! haskellmode#MergeImport(entry,line,hiding,explicit,module)
let lines = a:entry['lines'] + [ a:line ]
let hiding = a:explicit==[] ? haskellmode#ListIntersect(a:entry['hiding'], a:hiding)
\ : haskellmode#ListWithout(a:entry['hiding'],a:explicit)
let explicit = haskellmode#ListUnion(a:entry['explicit'], a:explicit)
let modules = haskellmode#ListUnion(a:entry['modules'], [ a:module ])
return {'lines':lines,'hiding':hiding,'explicit':explicit,'modules':modules}
endfunction
" collect lines belonging to a single import statement;
" return number of last line and collected import statement
" (assume opening parenthesis, if any, is on the first line)
function! haskellmode#GatherImport(lineno)
let lineno = a:lineno
let import = getline(lineno)
if !(import=~'^import\s') | return [] | endif
let open = strlen(substitute(import,'[^(]','','g'))
let close = strlen(substitute(import,'[^)]','','g'))
while open!=close
let lineno += 1
let linecont = getline(lineno)
let open += strlen(substitute(linecont,'[^(]','','g'))
let close += strlen(substitute(linecont,'[^)]','','g'))
let import .= linecont
endwhile
return [lineno,import]
endfunction
function! haskellmode#UrlEncode(string)
let pat = '\([^[:alnum:]]\)'
let code = '\=printf("%%%02X",char2nr(submatch(1)))'
let url = substitute(a:string,pat,code,'g')
return url
endfunction
" TODO: we could have buffer-local settings, at the expense of
" reconfiguring for every new buffer.. do we want to?
function! haskellmode#GHC()
if (!exists("g:ghc") || !executable(g:ghc))
if !executable('ghc')
echoerr s:scriptname.": can't find ghc. please set g:ghc, or extend $PATH"
return 0
else
let g:ghc = 'ghc'
endif
endif
return 1
endfunction
function! haskellmode#GHC_Version()
if !exists("g:ghc_version")
let g:ghc_version = substitute(system(g:ghc . ' --numeric-version'),'\n','','')
endif
return g:ghc_version
endfunction
function! haskellmode#GHC_VersionGE(target)
let current = split(haskellmode#GHC_Version(), '\.' )
let target = a:target
for i in current
if ((target==[]) || (i>target[0]))
return 1
elseif (i==target[0])
let target = target[1:]
else
return 0
endif
endfor
return 1
endfunction
" pathogen.vim - path option manipulation
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 2.2
" Install in ~/.vim/autoload (or ~\vimfiles\autoload).
"
" For management of individually installed plugins in ~/.vim/bundle (or
" ~\vimfiles\bundle), adding `execute pathogen#infect()` to the top of your
" .vimrc is the only other setup necessary.
"
" The API is documented inline below. For maximum ease of reading,
" :set foldmethod=marker
if exists("g:loaded_pathogen") || &cp
finish
endif
let g:loaded_pathogen = 1
function! s:warn(msg)
echohl WarningMsg
echomsg a:msg
echohl NONE
endfunction
" Point of entry for basic default usage. Give a relative path to invoke
" pathogen#incubate() (defaults to "bundle/{}"), or an absolute path to invoke
" pathogen#surround(). For backwards compatibility purposes, a full path that
" does not end in {} or * is given to pathogen#runtime_prepend_subdirectories()
" instead.
function! pathogen#infect(...) abort " {{{1
for path in a:0 ? reverse(copy(a:000)) : ['bundle/{}']
if path =~# '^[^\\/]\+$'
call s:warn('Change pathogen#infect('.string(path).') to pathogen#infect('.string(path.'/{}').')')
call pathogen#incubate(path . '/{}')
elseif path =~# '^[^\\/]\+[\\/]\%({}\|\*\)$'
call pathogen#incubate(path)
elseif path =~# '[\\/]\%({}\|\*\)$'
call pathogen#surround(path)
else
call s:warn('Change pathogen#infect('.string(path).') to pathogen#infect('.string(path.'/{}').')')
call pathogen#surround(path . '/{}')
endif
endfor
call pathogen#cycle_filetype()
return ''
endfunction " }}}1
" Split a path into a list.
function! pathogen#split(path) abort " {{{1
if type(a:path) == type([]) | return a:path | endif
let split = split(a:path,'\\\@<!\%(\\\\\)*\zs,')
return map(split,'substitute(v:val,''\\\([\\,]\)'',''\1'',"g")')
endfunction " }}}1
" Convert a list to a path.
function! pathogen#join(...) abort " {{{1
if type(a:1) == type(1) && a:1
let i = 1
let space = ' '
else
let i = 0
let space = ''
endif
let path = ""
while i < a:0
if type(a:000[i]) == type([])
let list = a:000[i]
let j = 0
while j < len(list)
let escaped = substitute(list[j],'[,'.space.']\|\\[\,'.space.']\@=','\\&','g')
let path .= ',' . escaped
let j += 1
endwhile
else
let path .= "," . a:000[i]
endif
let i += 1
endwhile
return substitute(path,'^,','','')
endfunction " }}}1
" Convert a list to a path with escaped spaces for 'path', 'tag', etc.
function! pathogen#legacyjoin(...) abort " {{{1
return call('pathogen#join',[1] + a:000)
endfunction " }}}1
" Remove duplicates from a list.
function! pathogen#uniq(list) abort " {{{1
let i = 0
let seen = {}
while i < len(a:list)
if (a:list[i] ==# '' && exists('empty')) || has_key(seen,a:list[i])
call remove(a:list,i)
elseif a:list[i] ==# ''
let i += 1
let empty = 1
else
let seen[a:list[i]] = 1
let i += 1
endif
endwhile
return a:list
endfunction " }}}1
" \ on Windows unless shellslash is set, / everywhere else.
function! pathogen#separator() abort " {{{1
return !exists("+shellslash") || &shellslash ? '/' : '\'
endfunction " }}}1
" Convenience wrapper around glob() which returns a list.
function! pathogen#glob(pattern) abort " {{{1
let files = split(glob(a:pattern),"\n")
return map(files,'substitute(v:val,"[".pathogen#separator()."/]$","","")')
endfunction "}}}1
" Like pathogen#glob(), only limit the results to directories.
function! pathogen#glob_directories(pattern) abort " {{{1
return filter(pathogen#glob(a:pattern),'isdirectory(v:val)')
endfunction "}}}1
" Turn filetype detection off and back on again if it was already enabled.
function! pathogen#cycle_filetype() " {{{1
if exists('g:did_load_filetypes')
filetype off
filetype on
endif
endfunction " }}}1
" Check if a bundle is disabled. A bundle is considered disabled if it ends
" in a tilde or its basename or full name is included in the list
" g:pathogen_disabled.
function! pathogen#is_disabled(path) " {{{1
if a:path =~# '\~$'
return 1
elseif !exists("g:pathogen_disabled")
return 0
endif
let sep = pathogen#separator()
let blacklist = g:pathogen_disabled
return index(blacklist, strpart(a:path, strridx(a:path, sep)+1)) != -1 && index(blacklist, a:path) != 1
endfunction "}}}1
" Prepend the given directory to the runtime path and append its corresponding
" after directory. If the directory is already included, move it to the
" outermost position. Wildcards are added as is. Ending a path in /{} causes
" all subdirectories to be added (except those in g:pathogen_disabled).
function! pathogen#surround(path) abort " {{{1
let sep = pathogen#separator()
let rtp = pathogen#split(&rtp)
if a:path =~# '[\\/]{}$'
let path = fnamemodify(a:path[0:-4], ':p:s?[\\/]\=$??')
let before = filter(pathogen#glob_directories(path.sep.'*'), '!pathogen#is_disabled(v:val)')
let after = filter(reverse(pathogen#glob_directories(path.sep."*".sep."after")), '!pathogen#is_disabled(v:val[0:-7])')
call filter(rtp,'v:val[0:strlen(path)-1] !=# path')
else
let path = fnamemodify(a:path, ':p:s?[\\/]\=$??')
let before = [path]
let after = [path . sep . 'after']
call filter(rtp, 'index(before + after, v:val) == -1')
endif
let &rtp = pathogen#join(before, rtp, after)
return &rtp
endfunction " }}}1
" Prepend all subdirectories of path to the rtp, and append all 'after'
" directories in those subdirectories. Deprecated.
function! pathogen#runtime_prepend_subdirectories(path) " {{{1
call s:warn('Change pathogen#runtime_prepend_subdirectories('.string(a:path).') to pathogen#surround('.string(a:path.'/{}').')')
return pathogen#surround(a:path . pathogen#separator() . '{}')
endfunction " }}}1
" For each directory in the runtime path, add a second entry with the given
" argument appended. If the argument ends in '/{}', add a separate entry for
" each subdirectory. The default argument is 'bundle/{}', which means that
" .vim/bundle/*, $VIM/vimfiles/bundle/*, $VIMRUNTIME/bundle/*,
" $VIM/vim/files/bundle/*/after, and .vim/bundle/*/after will be added (on
" UNIX).
function! pathogen#incubate(...) abort " {{{1
let sep = pathogen#separator()
let name = a:0 ? a:1 : 'bundle/{}'
if "\n".s:done_bundles =~# "\\M\n".name."\n"
return ""
endif
let s:done_bundles .= name . "\n"
let list = []
for dir in pathogen#split(&rtp)
if dir =~# '\<after$'
if name =~# '{}$'
let list += filter(pathogen#glob_directories(substitute(dir,'after$',name[0:-3],'').'*'.sep.'after'), '!pathogen#is_disabled(v:val[0:-7])') + [dir]
else
let list += [dir, substitute(dir, 'after$', '', '') . name . sep . 'after']
endif
else
if name =~# '{}$'
let list += [dir] + filter(pathogen#glob_directories(dir.sep.name[0:-3].'*'), '!pathogen#is_disabled(v:val)')
else
let list += [dir . sep . name, dir]
endif
endif
endfor
let &rtp = pathogen#join(pathogen#uniq(list))
return 1
endfunction " }}}1
" Deprecated alias for pathogen#incubate().
function! pathogen#runtime_append_all_bundles(...) abort " {{{1
if a:0
call s:warn('Change pathogen#runtime_append_all_bundles('.string(a:1).') to pathogen#incubate('.string(a:1.'/{}').')')
else
call s:warn('Change pathogen#runtime_append_all_bundles() to pathogen#incubate()')
endif
return call('pathogen#incubate', map(copy(a:000),'v:val . "/{}"'))
endfunction
let s:done_bundles = ''
" }}}1
" Invoke :helptags on all non-$VIM doc directories in runtimepath.
function! pathogen#helptags() abort " {{{1
let sep = pathogen#separator()
for glob in pathogen#split(&rtp)
for dir in split(glob(glob), "\n")
if (dir.sep)[0 : strlen($VIMRUNTIME)] !=# $VIMRUNTIME.sep && filewritable(dir.sep.'doc') == 2 && !empty(filter(split(glob(dir.sep.'doc'.sep.'*'),"\n>"),'!isdirectory(v:val)')) && (!filereadable(dir.sep.'doc'.sep.'tags') || filewritable(dir.sep.'doc'.sep.'tags'))
silent! execute 'helptags' pathogen#fnameescape(dir.'/doc')
endif
endfor
endfor
endfunction " }}}1
command! -bar Helptags :call pathogen#helptags()
" Execute the given command. This is basically a backdoor for --remote-expr.
function! pathogen#execute(...) abort " {{{1
for command in a:000
execute command
endfor
return ''
endfunction " }}}1
" Like findfile(), but hardcoded to use the runtimepath.
function! pathogen#runtime_findfile(file,count) abort "{{{1
let rtp = pathogen#join(1,pathogen#split(&rtp))
let file = findfile(a:file,rtp,a:count)
if file ==# ''
return ''
else
return fnamemodify(file,':p')
endif
endfunction " }}}1
" Backport of fnameescape().
function! pathogen#fnameescape(string) abort " {{{1
if exists('*fnameescape')
return fnameescape(a:string)
elseif a:string ==# '-'
return '\-'
else
return substitute(escape(a:string," \t\n*?[{`$\\%#'\"|!<"),'^[+>]','\\&','')
endif
endfunction " }}}1
if exists(':Vedit')
finish
endif
let s:vopen_warning = 0
function! s:find(count,cmd,file,lcd) " {{{1
let rtp = pathogen#join(1,pathogen#split(&runtimepath))
let file = pathogen#runtime_findfile(a:file,a:count)
if file ==# ''
return "echoerr 'E345: Can''t find file \"".a:file."\" in runtimepath'"
endif
if !s:vopen_warning
let s:vopen_warning = 1
let warning = '|echohl WarningMsg|echo "Install scriptease.vim to continue using :V'.a:cmd.'"|echohl NONE'
else
let warning = ''
endif
if a:lcd
let path = file[0:-strlen(a:file)-2]
execute 'lcd `=path`'
return a:cmd.' '.pathogen#fnameescape(a:file) . warning
else
return a:cmd.' '.pathogen#fnameescape(file) . warning
endif
endfunction " }}}1
function! s:Findcomplete(A,L,P) " {{{1
let sep = pathogen#separator()
let cheats = {
\'a': 'autoload',
\'d': 'doc',
\'f': 'ftplugin',
\'i': 'indent',
\'p': 'plugin',
\'s': 'syntax'}
if a:A =~# '^\w[\\/]' && has_key(cheats,a:A[0])
let request = cheats[a:A[0]].a:A[1:-1]
else
let request = a:A
endif
let pattern = substitute(request,'/\|\'.sep,'*'.sep,'g').'*'
let found = {}
for path in pathogen#split(&runtimepath)
let path = expand(path, ':p')
let matches = split(glob(path.sep.pattern),"\n")
call map(matches,'isdirectory(v:val) ? v:val.sep : v:val')
call map(matches,'expand(v:val, ":p")[strlen(path)+1:-1]')
for match in matches
let found[match] = 1
endfor
endfor
return sort(keys(found))
endfunction " }}}1
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Ve :execute s:find(<count>,'edit<bang>',<q-args>,0)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vedit :execute s:find(<count>,'edit<bang>',<q-args>,0)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vopen :execute s:find(<count>,'edit<bang>',<q-args>,1)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vsplit :execute s:find(<count>,'split',<q-args>,<bang>1)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vvsplit :execute s:find(<count>,'vsplit',<q-args>,<bang>1)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vtabedit :execute s:find(<count>,'tabedit',<q-args>,<bang>1)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vpedit :execute s:find(<count>,'pedit',<q-args>,<bang>1)
command! -bar -bang -range=1 -nargs=1 -complete=customlist,s:Findcomplete Vread :execute s:find(<count>,'read',<q-args>,<bang>1)
" vim:set et sw=2:
Subproject commit 8bbc4b17331e0cec40e1c1d7a9b39493ef90a612
Subproject commit 64c2e53af2715311e8d76f548aa3435c26adc76e
Subproject commit 3b98a7fcae8f9fff356907171f0406ff8cd28921
Subproject commit 454c06e25680799b6f408622d6bfbaf920ace825
Subproject commit 7d9aec0bee91be677c38b94ff222d02aa732fe52
Subproject commit fa433e0b7330753688f715f3be5d10dc480f20e5
Subproject commit f2afd55704bfe0a2d66e6b270d247e9b8a7b1664
" Vim Compiler File
" Compiler: GHC
" Maintainer: Claus Reinke <claus.reinke@talk21.com>
" Last Change: 22/06/2010
"
" part of haskell plugins: http://projects.haskell.org/haskellmode-vim
" ------------------------------ paths & quickfix settings first
"
if exists("current_compiler") && current_compiler == "ghc"
finish
endif
let current_compiler = "ghc"
let s:scriptname = "ghc.vim"
if !haskellmode#GHC() | finish | endif
if (!exists("b:ghc_staticoptions"))
let b:ghc_staticoptions = ''
endif
" set makeprg (for quickfix mode)
execute 'setlocal makeprg=' . g:ghc . '\ ' . escape(b:ghc_staticoptions,' ') .'\ -e\ :q\ %'
"execute 'setlocal makeprg=' . g:ghc .'\ -e\ :q\ %'
"execute 'setlocal makeprg=' . g:ghc .'\ --make\ %'
" quickfix mode:
" fetch file/line-info from error message
" TODO: how to distinguish multiline errors from warnings?
" (both have the same header, and errors have no common id-tag)
" how to get rid of first empty message in result list?
setlocal errorformat=
\%-Z\ %#,
\%W%f:%l:%c:\ Warning:\ %m,
\%E%f:%l:%c:\ %m,
\%E%>%f:%l:%c:,
\%+C\ \ %#%m,
\%W%>%f:%l:%c:,
\%+C\ \ %#%tarning:\ %m,
" oh, wouldn't you guess it - ghc reports (partially) to stderr..
setlocal shellpipe=2>
" ------------------------- but ghc can do a lot more for us..
"
" allow map leader override
if !exists("maplocalleader")
let maplocalleader='_'
endif
" initialize map of identifiers to their types
" associate type map updates to changedtick
if !exists("b:ghc_types")
let b:ghc_types = {}
let b:my_changedtick = b:changedtick
endif
if exists("g:haskell_functions")
finish
endif
let g:haskell_functions = "ghc"
" avoid hit-enter prompts
set cmdheight=3
" edit static GHC options
" TODO: add completion for options/packages?
command! GHCStaticOptions call GHC_StaticOptions()
function! GHC_StaticOptions()
let b:ghc_staticoptions = input('GHC static options: ',b:ghc_staticoptions)
execute 'setlocal makeprg=' . g:ghc . '\ ' . escape(b:ghc_staticoptions,' ') .'\ -e\ :q\ %'
let b:my_changedtick -=1
endfunction
map <LocalLeader>T :call GHC_ShowType(1)<cr>
map <LocalLeader>t :call GHC_ShowType(0)<cr>
function! GHC_ShowType(addTypeDecl)
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [_,symb,qual,unqual] = namsym
let name = qual=='' ? unqual : qual.'.'.unqual
let pname = ( symb ? '('.name.')' : name )
call GHC_HaveTypes()
if !has_key(b:ghc_types,name)
redraw
echo pname "type not known"
else
redraw
for type in split(b:ghc_types[name],' -- ')
echo pname "::" type
if a:addTypeDecl
call append( line(".")-1, pname . " :: " . type )
endif
endfor
endif
endfunction
" show type of identifier under mouse pointer in balloon
" TODO: it isn't a good idea to tie potentially time-consuming tasks
" (querying GHCi for the types) to cursor movements (#14). Currently,
" we ask the user to call :GHCReload explicitly. Should there be an
" option to reenable the old implicit querying?
if has("balloon_eval")
set ballooneval
set balloondelay=600
set balloonexpr=GHC_TypeBalloon()
function! GHC_TypeBalloon()
if exists("b:current_compiler") && b:current_compiler=="ghc"
let [line] = getbufline(v:beval_bufnr,v:beval_lnum)
let namsym = haskellmode#GetNameSymbol(line,v:beval_col,0)
if namsym==[]
return ''
endif
let [start,symb,qual,unqual] = namsym
let name = qual=='' ? unqual : qual.'.'.unqual
let pname = name " ( symb ? '('.name.')' : name )
if b:ghc_types == {}
redraw
echo "no type information (try :GHGReload)"
elseif (b:my_changedtick != b:changedtick)
redraw
echo "type information may be out of date (try :GHGReload)"
endif
" silent call GHC_HaveTypes()
if b:ghc_types!={}
if has("balloon_multiline")
return (has_key(b:ghc_types,pname) ? split(b:ghc_types[pname],' -- ') : '')
else
return (has_key(b:ghc_types,pname) ? b:ghc_types[pname] : '')
endif
else
return ''
endif
else
return ''
endif
endfunction
endif
map <LocalLeader>si :call GHC_ShowInfo()<cr>
function! GHC_ShowInfo()
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [_,symb,qual,unqual] = namsym
let name = qual=='' ? unqual : (qual.'.'.unqual)
let output = GHC_Info(name)
pclose | new
setlocal previewwindow
setlocal buftype=nofile
setlocal noswapfile
put =output
wincmd w
"redraw
"echo output
endfunction
" fill the type map, unless nothing has changed since the last attempt
function! GHC_HaveTypes()
if b:ghc_types == {} && (b:my_changedtick != b:changedtick)
let b:my_changedtick = b:changedtick
return GHC_BrowseAll()
endif
endfunction
" update b:ghc_types after successful make
au QuickFixCmdPost make if GHC_CountErrors()==0 | silent call GHC_BrowseAll() | endif
" count only error entries in quickfix list, ignoring warnings
function! GHC_CountErrors()
let c=0
for e in getqflist() | if e.type=='E' && e.text !~ "^[ \n]*Warning:" | let c+=1 | endif | endfor
return c
endfunction
command! GHCReload call GHC_BrowseAll()
function! GHC_BrowseAll()
" let imports = haskellmode#GatherImports()
" let modules = keys(imports[0]) + keys(imports[1])
let b:my_changedtick = b:changedtick
let imports = {} " no need for them at the moment
let current = GHC_NameCurrent()
let module = current==[] ? 'Main' : current[0]
if haskellmode#GHC_VersionGE([6,8,1])
return GHC_BrowseBangStar(module)
else
return GHC_BrowseMultiple(imports,['*'.module])
endif
endfunction
function! GHC_NameCurrent()
let last = line("$")
let l = 1
while l<last
let ml = matchlist( getline(l), '^module\s*\([^ (]*\)')
if ml != []
let [_,module;x] = ml
return [module]
endif
let l += 1
endwhile
redraw
echo "cannot find module header for file " . expand("%")
return []
endfunction
function! GHC_BrowseBangStar(module)
redraw
echo "browsing module " a:module
let command = ":browse! *" . a:module
let orig_shellredir = &shellredir
let &shellredir = ">" " ignore error/warning messages, only output or lack of it
let output = system(g:ghc . ' ' . b:ghc_staticoptions . ' -v0 --interactive ' . expand("%") , command )
let &shellredir = orig_shellredir
return GHC_ProcessBang(a:module,output)
endfunction
function! GHC_BrowseMultiple(imports,modules)
redraw
echo "browsing modules " a:modules
let command = ":browse " . join( a:modules, " \n :browse ")
let command = substitute(command,'\(:browse \(\S*\)\)','putStrLn "-- \2" \n \1','g')
let output = system(g:ghc . ' ' . b:ghc_staticoptions . ' -v0 --interactive ' . expand("%") , command )
return GHC_Process(a:imports,output)
endfunction
function! GHC_Info(what)
" call GHC_HaveTypes()
let output = system(g:ghc . ' ' . b:ghc_staticoptions . ' -v0 --interactive ' . expand("%"), ":info ". a:what)
return output
endfunction
function! GHC_ProcessBang(module,output)
let module = a:module
let b = a:output
let linePat = '^\(.\{-}\)\n\(.*\)'
let contPat = '\s\+\(.\{-}\)\n\(.*\)'
let typePat = '^\(\)\(\S*\)\s*::\(.*\)'
let commentPat = '^-- \(\S*\)'
let definedPat = '^-- defined locally'
let importedPat = '^-- imported via \(.*\)'
if !(b=~commentPat)
echo s:scriptname.": GHCi reports errors (try :make?)"
return 0
endif
let b:ghc_types = {}
let ml = matchlist( b , linePat )
while ml != []
let [_,l,rest;x] = ml
let mlDecl = matchlist( l, typePat )
if mlDecl != []
let [_,indent,id,type;x] = mlDecl
let ml2 = matchlist( rest , '^'.indent.contPat )
while ml2 != []
let [_,c,rest;x] = ml2
let type .= c
let ml2 = matchlist( rest , '^'.indent.contPat )
endwhile
let id = substitute( id, '^(\(.*\))$', '\1', '')
let type = substitute( type, '\s\+', " ", "g" )
" using :browse! *<current>, we get both unqualified and qualified ids
let qualified = (id =~ '\.') && (id =~ '[A-Z]')
let b:ghc_types[id] = type
if !qualified
for qual in qualifiers
let b:ghc_types[qual.'.'.id] = type
endfor
endif
else
let mlImported = matchlist( l, importedPat )
let mlDefined = matchlist( l, definedPat )
if mlImported != []
let [_,modules;x] = mlImported
let qualifiers = split( modules, ', ' )
elseif mlDefined != []
let qualifiers = [module]
endif
endif
let ml = matchlist( rest , linePat )
endwhile
return 1
endfunction
function! GHC_Process(imports,output)
let b = a:output
let imports = a:imports
let linePat = '^\(.\{-}\)\n\(.*\)'
let contPat = '\s\+\(.\{-}\)\n\(.*\)'
let typePat = '^\(\s*\)\(\S*\)\s*::\(.*\)'
let modPat = '^-- \(\S*\)'
" add '-- defined locally' and '-- imported via ..'
if !(b=~modPat)
echo s:scriptname.": GHCi reports errors (try :make?)"
return 0
endif
let b:ghc_types = {}
let ml = matchlist( b , linePat )
while ml != []
let [_,l,rest;x] = ml
let mlDecl = matchlist( l, typePat )
if mlDecl != []
let [_,indent,id,type;x] = mlDecl
let ml2 = matchlist( rest , '^'.indent.contPat )
while ml2 != []
let [_,c,rest;x] = ml2
let type .= c
let ml2 = matchlist( rest , '^'.indent.contPat )
endwhile
let id = substitute(id, '^(\(.*\))$', '\1', '')
let type = substitute( type, '\s\+', " ", "g" )
" using :browse *<current>, we get both unqualified and qualified ids
if current_module " || has_key(imports[0],module)
if has_key(b:ghc_types,id) && !(matchstr(b:ghc_types[id],escape(type,'[].'))==type)
let b:ghc_types[id] .= ' -- '.type
else
let b:ghc_types[id] = type
endif
endif
if 0 " has_key(imports[1],module)
let qualid = module.'.'.id
let b:ghc_types[qualid] = type
endif
else
let mlMod = matchlist( l, modPat )
if mlMod != []
let [_,module;x] = mlMod
let current_module = module[0]=='*'
let module = current_module ? module[1:] : module
endif
endif
let ml = matchlist( rest , linePat )
endwhile
return 1
endfunction
let s:ghc_templates = ["module _ () where","class _ where","class _ => _ where","instance _ where","instance _ => _ where","type family _","type instance _ = ","data _ = ","newtype _ = ","type _ = "]
" use ghci :browse index for insert mode omnicompletion (CTRL-X CTRL-O)
function! GHC_CompleteImports(findstart, base)
if a:findstart
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),-1) " insert-mode: we're 1 beyond the text
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return -1
endif
let [start,symb,qual,unqual] = namsym
return (start-1)
else " find keys matching with "a:base"
let res = []
let l = len(a:base)-1
call GHC_HaveTypes()
for key in keys(b:ghc_types)
if key[0 : l]==a:base
let res += [{"word":key,"menu":":: ".b:ghc_types[key],"dup":1}]
endif
endfor
return res
endif
endfunction
set omnifunc=GHC_CompleteImports
"
" Vim's default completeopt is menu,preview
" you probably want at least menu, or you won't see alternatives listed
" setlocal completeopt+=menu
" menuone is useful, but other haskellmode menus will try to follow your choice here in future
" setlocal completeopt+=menuone
" longest sounds useful, but doesn't seem to do what it says, and interferes with CTRL-E
" setlocal completeopt-=longest
map <LocalLeader>ct :call GHC_CreateTagfile()<cr>
function! GHC_CreateTagfile()
redraw
echo "creating tags file"
let output = system(g:ghc . ' ' . b:ghc_staticoptions . ' -e ":ctags" ' . expand("%"))
" for ghcs older than 6.6, you would need to call another program
" here, such as hasktags
echo output
endfunction
command! -nargs=1 GHCi redraw | echo system(g:ghc. ' ' . b:ghc_staticoptions .' '.expand("%").' -e "'.escape(<f-args>,'"').'"')
" use :make 'not in scope' errors to explicitly list imported ids
" cursor needs to be on import line, in correctly loadable module
map <LocalLeader>ie :call GHC_MkImportsExplicit()<cr>
function! GHC_MkImportsExplicit()
let save_cursor = getpos(".")
let line = getline('.')
let lineno = line('.')
let ml = matchlist(line,'^import\(\s*qualified\)\?\s*\([^( ]\+\)')
if ml!=[]
let [_,q,mod;x] = ml
silent make
if getqflist()==[]
if line=~"import[^(]*Prelude"
call setline(lineno,substitute(line,"(.*","","").'()')
else
call setline(lineno,'-- '.line)
endif
silent write
silent make
let qflist = getqflist()
call setline(lineno,line)
silent write
let ids = {}
for d in qflist
let ml = matchlist(d.text,'Not in scope: \([^`]*\)`\([^'']*\)''')
if ml!=[]
let [_,what,qid;x] = ml
let id = ( qid =~ "^[A-Z]" ? substitute(qid,'.*\.\([^.]*\)$','\1','') : qid )
let pid = ( id =~ "[a-zA-Z0-9_']\\+" ? id : '('.id.')' )
if what =~ "data"
call GHC_HaveTypes()
if has_key(b:ghc_types,id)
let pid = substitute(b:ghc_types[id],'^.*->\s*\(\S*\).*$','\1','').'('.pid.')'
else
let pid = '???('.pid.')'
endif
endif
let ids[pid] = 1
endif
endfor
call setline(lineno,'import'.q.' '.mod.'('.join(keys(ids),',').')')
else
copen
endif
endif
call setpos('.', save_cursor)
endfunction
" no need to ask GHC about its supported languages and
" options with every editing session. cache the info in
" ~/.vim/haskellmode.config
" TODO: should we store more info (see haskell_doc.vim)?
" move to autoload?
" should we keep a history of GHC versions encountered?
function! GHC_SaveConfig()
let vimdir = expand('~').'/'.'.vim'
let config = vimdir.'/haskellmode.config'
if !isdirectory(vimdir)
call mkdir(vimdir)
endif
let entries = ['-- '.g:ghc_version]
for l in s:ghc_supported_languages
let entries += [l]
endfor
let entries += ['--']
for l in s:opts
let entries += [l]
endfor
call writefile(entries,config)
endfunction
" reuse cached GHC configuration info, if using the same
" GHC version.
function! GHC_LoadConfig()
let vimdir = expand('~').'/'.'.vim'
let config = vimdir.'/haskellmode.config'
if filereadable(config)
let lines = readfile(config)
if lines[0]=='-- '.g:ghc_version
let i=1
let s:ghc_supported_languages = []
while i<len(lines) && lines[i]!='--'
let s:ghc_supported_languages += [lines[i]]
let i+=1
endwhile
let i+=1
let s:opts = []
while i<len(lines)
let s:opts += [lines[i]]
let i+=1
endwhile
return 1
else
return 0
endif
else
return 0
endif
endfunction
let s:GHC_CachedConfig = haskellmode#GHC_VersionGE([6,8]) && GHC_LoadConfig()
if haskellmode#GHC_VersionGE([6,8,2])
if !s:GHC_CachedConfig
let s:opts = filter(split(substitute(system(g:ghc . ' -v0 --interactive', ':set'), ' ', '','g'), '\n'), 'v:val =~ "-f"')
endif
else
let s:opts = ["-fglasgow-exts","-fallow-undecidable-instances","-fallow-overlapping-instances","-fno-monomorphism-restriction","-fno-mono-pat-binds","-fno-cse","-fbang-patterns","-funbox-strict-fields"]
endif
let s:opts = sort(s:opts)
amenu ]OPTIONS_GHC.- :echo '-'<cr>
aunmenu ]OPTIONS_GHC
for o in s:opts
exe 'amenu ]OPTIONS_GHC.'.o.' :call append(0,"{-# OPTIONS_GHC '.o.' #-}")<cr>'
endfor
if has("gui_running")
map <LocalLeader>opt :popup ]OPTIONS_GHC<cr>
else
map <LocalLeader>opt :emenu ]OPTIONS_GHC.
endif
amenu ]LANGUAGES_GHC.- :echo '-'<cr>
aunmenu ]LANGUAGES_GHC
if haskellmode#GHC_VersionGE([6,8])
if !s:GHC_CachedConfig
let s:ghc_supported_languages = sort(split(system(g:ghc . ' --supported-languages'),'\n'))
endif
for l in s:ghc_supported_languages
exe 'amenu ]LANGUAGES_GHC.'.l.' :call append(0,"{-# LANGUAGE '.l.' #-}")<cr>'
endfor
if has("gui_running")
map <LocalLeader>lang :popup ]LANGUAGES_GHC<cr>
else
map <LocalLeader>lang :emenu ]LANGUAGES_GHC.
endif
endif
if !s:GHC_CachedConfig
call GHC_SaveConfig()
endif
*eregex.jax*
ファイル: eregex.vim, eregex_e.vim
作者: AKUTSU toshiyuki <locrian@mbd.ocn.ne.jp>
バージョン: 2.56
必要なもの: Vim version 6.1 かそれ以降。
説明: eregex.vim は、拡張正規表現を Vim の正規表現に変換します。
eregex_e.vim は、eregex.vim のコマンドを評価します。
1. 使用許諾 |eregex-license-to-use|
2. インストール |eregex-installations|
3. 関数 |eregex-functions|
4. コマンド |eregex-commands|
5. 使い方 |eregex-examples|
6. キーマップ |eregex-keymappings|
7. 原則 |eregex-principle|
8. 内部的な変換を表す一覧 |eregex-table|
9. 特殊なオプションとアトム |eregex-options|
10. マルチライン |eregex-multiline|
11. デリミタの制限 |eregex-limitation-of-delimiter|
12. Vim の正規表現について |eregex-about-vimregex|
==============================================================================
1. 使用許諾 *eregex-license-to-use*
eregex.vim と eregex_e.vim の著作権は、作者である AKUTSU toshiyuki に
帰属します。しかし、改変、再配布は自由にしてかまいません。
# GPL とか分かんないのだ。(^^ )>>
作者は本スクリプト(eregex.vim, eregex_e.vim) を使用したことによって生じた
いかなる損害について、一切の責任を負いません。
==============================================================================
2. インストール *eregex-installations*
参考 |add-plugin|
(1) UNIX/Linux
$HOME/.vim/plugin/eregex.vim
$HOME/.vim/plugin/eregex_e.vim
$HOME/.vim/doc/eregex_j.txt
それから、次のようにして helptags の再構築をします。
:helptags ~/.vim/doc
これで、:h :E2v とかできます。
(2) MS-Windows
eregex_j.txt は EUC-JP です。
MS-Windows の場合は予め ShiftJIS にしておいてください。
%HOME%\vimfiles\plugin\eregex.vim
%HOME%\vimfiles\plugin\eregex_e.vim
%HOME%\vimfiles\doc\eregex_j.txt
または、
%VIM%\vimfiles\plugin\eregex.vim
%VIM%\vimfiles\plugin\eregex_e.vim
%VIM%\vimfiles\doc\eregex_j.vim
それから、次のようにして helptags の再構築をします。
:helptags $HOME\vimfiles\doc
または、
:helptags $VIM\vimfiles\doc
これで、:h :E2v とかできます。
==============================================================================
3. 関数 *eregex-functions* *eregex*
*E2v()*
E2v({extendedregex} [, {iISCDMm}])
返り値は Vim の正規表現です。
>
:let vimregex = E2v('(?<=abc),\d+,(?=xzy)','i')
:echo vimregex
\c\%(abc\)\@<=,\d\+,\%(xzy\)\@=
<
オプションの詳しい説明は |eregex-options| や |eregex-multiline|
を見てください。
E2v("","V")
返り値は eregex.vim のバージョンです。
>
:echo E2v('','V')
248
<
E2v({replacement}, {R1,R2,R3})
これは、:S/pattern/to/ の "to" の部分で使う文字列を返します。
>
E2v('\r,\n,\&,&,\~,~', 'R1') => \n,\r,\&,&,\~,~
E2v('\r,\n,\&,&,\~,~', 'R2') => \r,\n,&,\&,~,\~
E2v('\r,\n,\&,&,\~,~', 'R3') => \n,\r,&,\&,~,\~
<
==============================================================================
4. コマンド *eregex-commands*
*:E2v*
:[range]E2v [iISCDMm]
Extended regex To Vim regex.
Replace each extended-regex in [range] with vim-style-regex.
*:M*
:M/eregex[/{offset} [iISCDMm]]
Match
:M/<span class="foo">.*?<\/span>/Im
==> /\C<span class="foo">\_.\{-}<\/span>
*:S*
:[range]S/{eregex}/{string}/[&cegpriISCDMm]
Substitute
:'<,'>S/(\d{1,3})(?=(\d\d\d)+($|\D))/\1,/g
==> :'<,'>s/\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=/\1,/g
*:G* *:G!*
:[range]G/{eregex}/{command}
:[range]G!/{eregex}/{command}
Global
:G/<<-(["'])?EOD\1/,/^\s*EOD\>/:left 8
==> :g/<<-\(["']\)\=EOD\1/,/^\s*EOD\>/:left 8
*:V*
:[range]V/{eregex}/{command}
Vglobal
==============================================================================
5. 使い方 *eregex-examples*
(1) :E2v コマンド
次の拡張正規表現の行にカーソルを置く。
(\d{1,3})(?=(\d\d\d)+($|\D))
んで、:E2v を実行すると、次のようになる。
\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=
(2) :M コマンド
>
:M/<Items\s+attr="media">.+?<\/Items>/Im
<
:normal! /\C<Items[ \t\r\n^L]\+attr="media">\_.\{-1,}<\/Items>
<Items attr="media">
<item name="cdrom" price="90" />
<item name="cdrw" price="500" />
<item name="dvd" price="1000" />
</Items>
(3) :S コマンド
>
:'<,'>S/(\d{1,3})(?=(\d\d\d)+($|\D))/\1,/g
<
:'<,'>s/\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=/\1,/g
1 --> 1
12 --> 12
123 --> 123
1234 --> 1,234
12345 --> 12,345
123456 --> 123,456
1234567 --> 1,234,567
12345678 --> 12,345,678
123456789 --> 123,456,789
(4) :G コマンド
>
:G/^begin$/+1;/^end$/-1:S/\l+/\U&/g
<
:g/^begin$/+1;/^end$/-1:s/\l\+/\U&/g
begin
hello world.
hello world wide web.
hello The Internet.
end
|begin
| HELLO WORLD.
| HELLO WORLD WIDE WEB.
| HELLO THE INTERNET.
|end
(5) :V コマンド
説明省略。
==============================================================================
6. キーマップ *eregex-keymappings*
/ で行なう通常の検索と :M/ を入れ替える。
.vimrc に以下を書く。 ( MS-Windows の場合 _vimrc か _gvimrc )
nnoremap / :M/
nnoremap ,/ /
"/" で、:M/ になり、",/" で従来の "/" が使えます。
--------------------
~/.vimrc の中に、
let eregex_replacement=3
を書いておくと :S コマンドの動作が次のように変わります。
:S/pattern/\r,\n,\&,&,\~,~/
:s/pattern/\n,\r,&,\&,~,\~/
+--------------------+-----------------------------+
| eregex_replacement | :S/pattern/\n,\r,&,\&,~,\~/ |
+--------------------+-----------------------------+
| 0 | :s/pattern/\n,\r,&,\&,~,\~/ |
| 1 | :s/pattern/\r,\n,&,\&,~,\~/ |
| 2 | :s/pattern/\n,\r,\&,&,\~,~/ |
| 3 | :s/pattern/\r,\n,\&,&,\~,~/ |
+--------------------+-----------------------------+
==============================================================================
7. 原則 *eregex-principle*
eregex.vim において、
「選択」「繰り返し」「丸カッコ」は、拡張正規表現流 を採用する。
それ以外は Vim の正規表現に従う。
==============================================================================
8. 内部的な変換を表す一覧 *eregex-table*
左には拡張正規表現を書き、右には Vim 流正規表現('magic')を書く。
選択
--------------------
:M/a|b /a\|b
繰り返し
--------------------
:M/a* /a*
:M/a+ /a\+
:M/a? /a\=
:M/a*? /a\{-}
:M/a+? /a\{-1,}
:M/a?? /a\{-,1}
:M/a{3,5} /a\{3,5}
:M/a{3,} /a\{3,}
:M/a{,5} /a\{,5}
:M/a{3,5}? /a\{-3,5}
:M/a{3,}? /a\{-3,}
:M/a{,5}? /a\{-,5}
丸カッコ(パレン)
--------------------
:M/(abc) /\(abc\)
:M/(?:abc) /\%(abc\)
:M/(?<=abc) /\%(abc\)\@<=
:M/(?<!abc) /\%(abc\)\@<!
:M/(?=abc) /\%(abc\)\@=
:M/(?!abc) /\%(abc\)\@!
:M/(?>abc) /\%(abc\)\@>
文字そのもの
--------------------
:M/\\,\|,\(,\),\{,\},\?,\+,\*,\[,\] /\\,|,(,),{,},?,+,\*,\[,\]
:M/\^,\$ /\^,\$
拡張正規表現で使えないもの
--------------------
\A, \b, \B, \G, \Z, \z
これらは全て Vim のものとして扱われる。
(?i:a) や (?-i) なども使えない。
Vim の正規表現で使えないもの
--------------------
\%(re\) 等、パレン(丸カッコ) を使うもの全般。
~ matches the last given substitute string
\m 'magic' on for the following chars in the pattern
\M 'magic' off for the following chars in the pattern
\v the following chars in the pattern are "very magic"
\V the following chars in the pattern are "very nomagic"
\x hex digit: [0-9A-Fa-f]
\\x[0-9A-Fa-f]{1,2} の場合、文字そのものに変換する。
\x82\xa0 => 'あ' ( shift-jis, cp932 )
ただし、0x00 と 0x0a と 0x08 は変換しません。
Vim の正規表現で使えるもの
--------------------
大抵使えます。(^^;)
\d, \D, \w, \W, \s, \S, \a, \A, \u, \U, \b, ...
\<, \>, \zs, \ze
\_[a-z], \%[abc], [[:alpha:]], \_., \_^, \_$
\%23l, \%23c, \%23v, \%#
など。
==============================================================================
9. 特殊なオプションとアトム *eregex-options*
Note: "^L" は \x0c
eregex.vim Vim
---------------------------------------
:M/a/i /\ca/
:M/\ca/ /\ca/
:M/a/I /\Ca/
:M/\Ca/ /\Ca/
:M/\s/S /[ \t\r\n^L]
:M/\S/S /[^ \t\r^L]
:M/[^az]/C /\_[^az]/
:M/\W/C /\_W/
:M/./D /\_./
:M/\s[^az]./M /[ \t\r\n^L]\_[^az]./
:M/\s[^az].\M/ 同上。
:M/\s[^az]./m /[ \t\r\n^L]\_[^az]\_./
:M/\s[^az].\m/ 同上。
+--------+------+--------------------------------------------------------+
| OPTION | ATOM | 説明 |
+--------+------+--------------------------------------------------------+
| /i | \c | 大小文字の区別無し。 |
| /I | \C | 大小文字の区別あり。 |
+--------+------+--------------------------------------------------------+
| /S | | \s および \S を [ \t\r\n^L] や [^ \t\r^L] に変換する。 |
| /C | | 補集合が改行にもマッチする。 |
| /D | | ドットが改行にもマッチする。 |
+--------+------+--------------------------------------------------------+
| /M | \M | /S と /C を行なう。 部分マルチライン。 |
| /m | \m | /S と /C と /D を行なう。完全マルチライン。 |
+--------+------+--------------------------------------------------------+
Note:
(A) オプション /iImM
(B) \c, \C, \m, \M
(C) (?i), (?I), (?m), (?M)
これらが同時に指定された場合、上の方が優先順位が高い。
ちなみに、(?M) と (?m) は、ブラケットの中の \s には適用されません。
==============================================================================
10. マルチライン *eregex-multiline*
とりあえず以下の表を見て。(^^;)
+-----+----------------------------------------------+--------------------+
| Num | eregex.vim => vim regex | ruby regex |
+-----+----------------------------------------------+--------------------+
| (1) | :M/a\s[^az].z/ => /a\s[^az].z/ | /a[ \t][^az\n].z/ |
+-----+----------------------------------------------+--------------------+
| | :M/a\s[^az].z/S => /a[ \t\r\n^L][^az].z/ | /a\s[^az\n].z/ |
| | :M/a\s[^az].z/C => /a\s\_[^az].z/ | /a[ \t][^az].z/ |
| | :M/a\s[^az].z/D => /a\s[^az]\_.z/ | /a[ \t][^az\n].z/m |
+-----+----------------------------------------------+--------------------+
| (2) | :M/a\s[^az].z/M => /a[ \t\r\n^L]\_[^az].z/ | /a\s[^az].z/ |
| (3) | :M/a\s[^az].z/m => /a[ \t\r\n^L]\_[^az]\_.z/ | /a\s[^az].z/m |
+-----+----------------------------------------------+--------------------+
(1) は、「文字クラス」が Vim 流。
(2) は、「文字クラス」が Ruby 流。
Vim 流に言えば、改行にマッチする所が増えたので、部分マルチライン。
Ruby 流に言えば、マルチラインでない。よってオプションは大文字の M 。
(3) は、いわゆる Ruby 流のマルチライン。
Note:
Vim の正規表現では、/[^az]/ は改行にマッチしません。
改行にマッチしないことを明示して /[^az\n]/ と書く必要はありません。
/[^az\n]/ は意図に反して改行にもマッチします。
よって、本来 /[^ \t\r\n^L]/ とするべきところを、/[^ \t\r^L]/ に
変換している場合があります。
原則的に Vim では、[^...] の中に \n を書いてはいけません。
==============================================================================
11. デリミタの制限 *eregex-limitation-of-delimiter*
:M で使える区切り文字は / と ? だけです。
:S 、:G および :V で使える区切り文字は /, #, @ です。
これらの使用方法は :s 、:g 、:v と同じです。
制限も同様です。
区切り文字を @ にするといろいろ制限があります。
一見うまくいきそうに見えてダメな例。
"foo@bar.baz.co.jp" を "foo@hoge.co.jp" に置換しようとして、
>
:%s@\<foo\@bar\.baz\.co\.jp\>@foo\@hoge.co.jp@Ig
<
は、エラーです。
Vim の正規表現で、\@ は特別な扱いを受けています。
==============================================================================
12. Vim の正規表現について *eregex-about-vimregex*
以下 カーソルを "111,222,333" の行に置いて、:S... を実行してください。
(1)通常のサブマッチ。
111,222,333
>
:S/(\d+),(\d+),(\d+)/\=submatch(1) + submatch(2) + submatch(3)
<
666
(2)Vim 独自機能。
マッチデータ($&, &, matchdata) と、サブマッチを分離できます。
\zs と \ze を使う。 See :h /\zs
111,222,333
>
:S/(\d+),\zs\d+\ze,(\d+)/\=submatch(1) + submatch(0) + submatch(2)
<
111,666,333
(3)
以下の方が分かりやすいかも。
111,222,333
>
:S/(\d+),\zs(\d+)\ze,(\d+)/\=submatch(1) + submatch(2) + submatch(3)
<
111,666,333
\zs と \ze を使うと、マッチデータに含まれないサブマッチを操作できます。
(4) \_x の機能。
\u で [A-Z] を表す。
\_u で [A-Z\n] を表す。
\_[A-Z] は [A-Z\n] と同じ。
大文字以外で改行を含む文字。
\_U == \_[^A-Z]
\_. は改行を含む任意の文字。
(5) ^ と \_^ および $ と \_$ の違い。
$ を例にとります。
通常 $ は
(1)正規表現の一番最後。
(2) ) の直前。
(3) | の直前。
にある場合だけ行末を表す。
ところが任意の場所で行末を表せるのが \_$ 。
111,222,333
>
:S/(\d+),(\d+),(\d+)\zs\_$\ze/\=',' . (submatch(1) + submatch(2) + submatch(3))
<
111,222,333,666
ここで使っている \_$ の代わりに $ を使っても意図した結果になりません。
Note:
\_^ と \_$ は perl の /m オプションとは全然違います。
==============================================================================
13. 履歴
revision 2.55
(1) E2v() にバージョン番号や、sub-replace-special の置換を加えた。
(2) \v を 0x0b に置換するようにした。
(3) :M/pattern/ でマッチしなくても、@/ を更新した。
revision 2.35
(1) オプション S,C,D,M,m の追加と変更。
revision 1.4x
(1) :S/\x2f/\\/g とかすると、:s///\\/g に変換してしまうバグ修正。
(2) エスケープされたデリミタを検索履歴ではアンエスケープした。
デリミタが '@' の場合を除く。
(3) オプション m の修正。
revision 1.13
:G で ! を使えるようにした。
revision 1.1.1.21
:S の /c オプションで確認のプロンプトが見えなくなってしまう問題修正。
-- vim:ft=help:
*eregex.txt*
File: eregex.vim, eregex_e.vim
Author: AKUTSU toshiyuki <locrian@mbd.ocn.ne.jp>
Maintainer: othree <othree@gmail.com>
Version: 2.56
Required: Vim version 6.1
Note: eregex.vim is used to convert regexp notation style.
eregex_e.vim is used to map command for eregex.vim.
1. License |eregex-license-to-use|
2. Installation |eregex-installations|
3. Functions |eregex-functions|
4. Command |eregex-commands|
5. Usage |eregex-examples|
6. Keymap |eregex-keymappings|
7. Principle |eregex-principle|
8. Convert Table |eregex-table|
9. Options |eregex-options|
10. Multiline |eregex-multiline|
11. Limitation of Delimiter |eregex-limitation-of-delimiter|
12. About Vim Regexp |eregex-about-vimregex|
==============================================================================
1. License *eregex-license-to-use*
Copyright of eregex.vim and eregex_e.vim belongs to AKUTSU toshiyuki.
It is free to change and redistribute this script. You can think as an
GPL License software.
Author will not take any responsibility for damages due to using this
script (eregex.vim, eregex_e.vim).
==============================================================================
2. Installation *eregex-installations*
Open eregex.vba using Vim. And execute the following command.
>
:so %
<
==============================================================================
3. Functions *eregex-functions* *eregex*
*E2v()*
E2v({extendedregex} [, {iISCDMm}])
Vim regexp notation will return.
>
:let vimregex = E2v('(?<=abc),\d+,(?=xzy)','i')
:echo vimregex
<
Detail of option value can be found at |eregex-options|
or |eregex-multiline|
E2v("","V")
Return eregex.vim version number
>
:echo E2v('','V')
248
<
E2v({replacement}, {R1,R2,R3})
Return the "to" part of :S/pattern/to/ .
>
E2v('\r,\n,\&,&,\~,~', 'R1') => \n,\r,\&,&,\~,~
E2v('\r,\n,\&,&,\~,~', 'R2') => \r,\n,&,\&,~,\~
E2v('\r,\n,\&,&,\~,~', 'R3') => \n,\r,&,\&,~,\~
<
==============================================================================
4. Command *eregex-commands*
*:E2v*
:[range]E2v [iISCDMm]
Extended regex To Vim regex.
Replace each extended-regex in [range] with vim-style-regex.
*:M*
:M/eregex[/{offset} [iISCDMm]]
Match
:M/<span class="foo">.*?<\/span>/Im
==> /\C<span class="foo">\_.\{-}<\/span>
*:S*
:[range]S/{eregex}/{string}/[&cegpriISCDMm]
Substitute
:'<,'>S/(\d{1,3})(?=(\d\d\d)+($|\D))/\1,/g
==> :'<,'>s/\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=/\1,/g
*:G* *:G!*
:[range]G/{eregex}/{command}
:[range]G!/{eregex}/{command}
Global
:G/<<-(["'])?EOD\1/,/^\s*EOD\>/:left 8
==> :g/<<-\(["']\)\=EOD\1/,/^\s*EOD\>/:left 8
*:V*
:[range]V/{eregex}/{command}
Vglobal
==============================================================================
5. Usage *eregex-examples*
(1) :E2v command
Change the regexp notation style of the cursor line.
(\d{1,3})(?=(\d\d\d)+($|\D))
Move cursor to this line and execute :E2v command will change this line to
the following result.
\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=
(2) :M command
>
:M/<Items\s+attr="media">.+?<\/Items>/Im
<
:normal! /\C<Items[ \t\r\n^L]\+attr="media">\_.\{-1,}<\/Items>
<Items attr="media">
<item name="cdrom" price="90" />
<item name="cdrw" price="500" />
<item name="dvd" price="1000" />
</Items>
(3) :S command
>
:'<,'>S/(\d{1,3})(?=(\d\d\d)+($|\D))/\1,/g
<
:'<,'>s/\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=/\1,/g
1 --> 1
12 --> 12
123 --> 123
1234 --> 1,234
12345 --> 12,345
123456 --> 123,456
1234567 --> 1,234,567
12345678 --> 12,345,678
123456789 --> 123,456,789
(4) :G command
>
:G/^begin$/+1;/^end$/-1:S/\l+/\U&/g
<
:g/^begin$/+1;/^end$/-1:s/\l\+/\U&/g
begin
hello world.
hello world wide web.
hello The Internet.
end
|begin
| HELLO WORLD.
| HELLO WORLD WIDE WEB.
| HELLO THE INTERNET.
|end
(5) :V command
Skipped.
==============================================================================
6. keymap *eregex-keymappings*
You can add the following keymap to use / instead of type :/M
nnoremap / :M/
nnoremap ? :M?
nnoremap ,/ /
nnoremap ,? /
"/" will use :M/ to search. ",/" will use the original "/".
--------------------
Add the following line to ~/.vimrc
let eregex_replacement=3
will make :S have the following rules.
:S/pattern/\r,\n,\&,&,\~,~/
:s/pattern/\n,\r,&,\&,~,\~/
+--------------------+-----------------------------+
| eregex_replacement | :S/pattern/\n,\r,&,\&,~,\~/ |
+--------------------+-----------------------------+
| 0 | :s/pattern/\n,\r,&,\&,~,\~/ |
| 1 | :s/pattern/\r,\n,&,\&,~,\~/ |
| 2 | :s/pattern/\n,\r,\&,&,\~,~/ |
| 3 | :s/pattern/\r,\n,\&,&,\~,~/ |
+--------------------+-----------------------------+
==============================================================================
7. Principle *eregex-principle*
eregex.vim adopts the way of extended regex about "alternation",
"repetition" and "grouping".
==============================================================================
8. Convert Table *eregex-table*
Perl style on left side. Vim style ('magic') on right side.
Alternation
--------------------
:M/a|b /a\|b
Repetition
--------------------
:M/a* /a*
:M/a+ /a\+
:M/a? /a\=
:M/a*? /a\{-}
:M/a+? /a\{-1,}
:M/a?? /a\{-,1}
:M/a{3,5} /a\{3,5}
:M/a{3,} /a\{3,}
:M/a{,5} /a\{,5}
:M/a{3,5}? /a\{-3,5}
:M/a{3,}? /a\{-3,}
:M/a{,5}? /a\{-,5}
Grouping
--------------------
:M/(abc) /\(abc\)
:M/(?:abc) /\%(abc\)
:M/(?<=abc) /\%(abc\)\@<=
:M/(?<!abc) /\%(abc\)\@<!
:M/(?=abc) /\%(abc\)\@=
:M/(?!abc) /\%(abc\)\@!
:M/(?>abc) /\%(abc\)\@>
Special Characters
--------------------
:M/\\,\|,\(,\),\{,\},\?,\+,\*,\[,\] /\\,|,(,),{,},?,+,\*,\[,\]
:M/\^,\$ /\^,\$
Not support
--------------------
\A, \b, \B, \G, \Z, \z
Vim doesn't support these features.
(?i:a) and (?-i) neither.
Unusable Vim regexp notation
--------------------
\%(re\) and square rackets
~ matches the last given substitute string
\m 'magic' on for the following chars in the pattern
\M 'magic' off for the following chars in the pattern
\v the following chars in the pattern are "very magic"
\V the following chars in the pattern are "very nomagic"
\x hex digit: [0-9A-Fa-f]
\\x[0-9A-Fa-f]{1,2} will change to character.
\x82\xa0 => '' ( shift-jis, cp932 )
But 0x00 and 0x0a and 0x08 will not change.
Usable Vim regexp notations
--------------------
\d, \D, \w, \W, \s, \S, \a, \A, \u, \U, \b, ...
\<, \>, \zs, \ze
\_[a-z], \%[abc], [[:alpha:]], \_., \_^, \_$
\%23l, \%23c, \%23v, \%#
==============================================================================
9. Special Option and Atom *eregex-options*
Note: "^L" is \x0c
eregex.vim Vim
---------------------------------------
:M/a/i /\ca/
:M/\ca/ /\ca/
:M/a/I /\Ca/
:M/\Ca/ /\Ca/
:M/\s/S /[ \t\r\n^L]
:M/\S/S /[^ \t\r^L]
:M/[^az]/C /\_[^az]/
:M/\W/C /\_W/
:M/./D /\_./
:M/\s[^az]./M /[ \t\r\n^L]\_[^az]./
:M/\s[^az].\M/ Same as above.
:M/\s[^az]./m /[ \t\r\n^L]\_[^az]\_./
:M/\s[^az].\m/ Same as above.
+--------+------+--------------------------------------------------------+
| OPTION | ATOM | NOTE |
+--------+------+--------------------------------------------------------+
| /i | \c | Case insensitive |
| /I | \C | Case sensitive |
+--------+------+--------------------------------------------------------+
| /S | | \s and \S becomes [ \t\r\n^L] and [^ \t\r^L] |
| /C | | [] brackets will also match line break. |
| /D | | Dot will match line break |
+--------+------+--------------------------------------------------------+
| /M | \M | Use /S and /C . Partial multiline support |
| /m | \m | Use /S, /C and /D . All support multiline |
+--------+------+--------------------------------------------------------+
Note:
(A) Option /iImM
(B) \c, \C, \m, \M
(C) (?i), (?I), (?m), (?M)
If you use these at the same time. The priority will follow the order.
If you use (?M) and (?m), \s in bracket will not work.
==============================================================================
10. Multiline *eregex-multiline*
+-----+----------------------------------------------+--------------------+
| Num | eregex.vim => vim regex | ruby regex |
+-----+----------------------------------------------+--------------------+
| (1) | :M/a\s[^az].z/ => /a\s[^az].z/ | /a[ \t][^az\n].z/ |
+-----+----------------------------------------------+--------------------+
| | :M/a\s[^az].z/S => /a[ \t\r\n^L][^az].z/ | /a\s[^az\n].z/ |
| | :M/a\s[^az].z/C => /a\s\_[^az].z/ | /a[ \t][^az].z/ |
| | :M/a\s[^az].z/D => /a\s[^az]\_.z/ | /a[ \t][^az\n].z/m |
+-----+----------------------------------------------+--------------------+
| (2) | :M/a\s[^az].z/M => /a[ \t\r\n^L]\_[^az].z/ | /a\s[^az].z/ |
| (3) | :M/a\s[^az].z/m => /a[ \t\r\n^L]\_[^az]\_.z/ | /a\s[^az].z/m |
+-----+----------------------------------------------+--------------------+
(1) is Vim style character class.
(2) is Ruby style character class.
(3) is Ruby style multiline.
Note:
In Vim style regexp, /[^az]/ will not match break line.
But it is incorrect to to write /[^az\n]/ to point this out.
/[^az\n]/ will match breakline.
So we might use /[^ \t\r^L]/ instead of /[^ \t\r\n^L]/ .
Just remember not write \n in [^...] .
==============================================================================
11. Limitation of Delimiter *eregex-limitation-of-delimiter*
:M only support / and ? .
:S, :G and :V supports /, #, @ .
Usage and limitation are the same as :s, :g and :v
Delimiter use @ will have some more limitation.
For example:
To replace "foo@bar.baz.co.jp" with "foo@hoge.co.jp"
>
:%s@\<foo\@bar\.baz\.co\.jp\>@foo\@hoge.co.jp@Ig
<
Will fail.
\@ have special meaning in Vim regular expression .
==============================================================================
12. About Vim Regular Expression *eregex-about-vimregex*
The following samples are all in a line with content "111,222,333".
And use :S to execute replace.
(1)Regular submatch
111,222,333
>
:S/(\d+),(\d+),(\d+)/\=submatch(1) + submatch(2) + submatch(3)
<
666
(2)Vim special feature
Match data($&, &, matchdata) and submatch can be seperated.
Use \zs and \ze . See :h /\zs for more information.
111,222,333
>
:S/(\d+),\zs\d+\ze,(\d+)/\=submatch(1) + submatch(0) + submatch(2)
<
111,666,333
(3)
One more example
111,222,333
>
:S/(\d+),\zs(\d+)\ze,(\d+)/\=submatch(1) + submatch(2) + submatch(3)
<
111,666,333
Use \zs and \ze to control matchdata and submatch.
(4) \_x
\u is [A-Z]
\_u is [A-Z\n]
\_[A-Z] is [A-Z\n]
Not uppercase characters and line break.
\_U == \_[^A-Z]
\_. is any character including line break.
(5) Difference between ^ and \_^ or $ and \_$
Take $ for example
$ is used in the following position
(1) The last of regexp.
(2) Just before ) .
(3) Just before | .
\_$ can be used anywhere to present as a line break.
111,222,333
>
:S/(\d+),(\d+),(\d+)\zs\_$\ze/\=',' . (submatch(1) + submatch(2) + submatch(3))
<
111,222,333,666
If use $ instead of \_$ in this example will have different result.
Note:
\_^ and \_$ is totally different from /m option in Perl regexp.
==============================================================================
13. Changes
revision 2.56
(1) Add support for "?"
-- vim:ft=help:
*haskellmode.txt* Haskell Mode Plugins 02/05/2009
Authors:
Claus Reinke <claus.reinke@talk21.com> ~
Homepage:
http://projects.haskell.org/haskellmode-vim
CONTENTS *haskellmode*
1. Overview |haskellmode-overview|
1.1 Runtime Requirements |haskellmode-requirements|
1.2 Quick Reference |haskellmode-quickref|
2. Settings |haskellmode-settings|
2.1 GHC and web browser |haskellmode-settings-main|
2.2 Fine tuning - more configuration options |haskellmode-settings-fine|
3. GHC Compiler Integration |haskellmode-compiler|
4. Haddock Integration |haskellmode-haddock|
4.1 Indexing |haskellmode-indexing|
4.2 Lookup |haskellmode-lookup|
4.3 Editing |haskellmode-editing|
5. Hpaste Integration |haskellmode-hpaste|
6. Additional Resources |haskellmode-resources|
==============================================================================
*haskellmode-overview*
1. Overview ~
The Haskell mode plugins provide advanced support for Haskell development
using GHC/GHCi on Windows and Unix-like systems. The functionality is
based on Haddock-generated library indices, on GHCi's interactive
commands, or on simply activating (some of) Vim's built-in program editing
support in Haskell-relevant fashion. These plugins live side-by-side with
the pre-defined |syntax-highlighting| support for |haskell| sources, and
any other Haskell-related plugins you might want to install (see
|haskellmode-resources|).
The Haskell mode plugins consist of three filetype plugins (haskell.vim,
haskell_doc.vim, haskell_hpaste.vim), which by Vim's |filetype| detection
mechanism will be auto-loaded whenever files with the extension '.hs' are
opened, and one compiler plugin (ghc.vim) which you will need to load from
your vimrc file (see |haskellmode-settings|).
*haskellmode-requirements*
1.1 Runtime Requirements ~
The plugins require a recent installation of GHC/GHCi. The functionality
derived from Haddock-generated library indices also requires a local
installation of the Haddock documentation for GHC's libraries (if there is
no documentation package for your system, you can download a tar-ball from
haskell.org), as well as an HTML browser (see |haddock_browser|). If you
want to use the experimental hpaste interface, you will also need Wget.
* GHC/GHCi ~
Provides core functionality. http://www.haskell.org/ghc
* HTML library documentation files and indices generated by Haddock ~
These usually come with your GHC installation, possibly as a separate
package. If you cannot get them this way, you can download a tar-ball
matching your GHC version from http://www.haskell.org/ghc/docs/
* HTML browser with basic CSS support ~
For browsing Haddock docs.
* Wget ~
For interfacing with http://hpaste.org.
Wget is widely available for modern Unix-like operating systems. Several
ports also exist for Windows, including:
- Official GNU Wget (natively compiled for Win32)
http://www.gnu.org/software/wget/#downloading
- UnxUtils Wget (natively compiled for Win32, bundled with other ported
Unix utilities)
http://sourceforge.net/projects/unxutils/
- Cygwin Wget (emulated POSIX in Win32, must be run under Cygwin)
http://cygwin.com/packages/wget/
*haskellmode-quickref*
1.2 Quick Reference ~
|:make| load into GHCi, show errors (|quickfix| |:copen|)
|_ct| create |tags| file
|_si| show info for id under cursor
|_t| show type for id under cursor
|_T| insert type declaration for id under cursor
|balloon| show type for id under mouse pointer
|_?| browse Haddock entry for id under cursor
|_?1| search Hoogle for id under cursor
|_?2| search Hayoo! for id under cursor
|:IDoc| {identifier} browse Haddock entry for unqualified {identifier}
|:MDoc| {module} browse Haddock entry for {module}
|:FlagReference| {s} browse Users Guide Flag Reference for section {s}
|_.| qualify unqualified id under cursor
|_i| add 'import <module>(<identifier>)' for id under cursor
|_im| add 'import <module>' for id under cursor
|_iq| add 'import qualified <module>(<identifier>)' for id under cursor
|_iqm| add 'import qualified <module>' for id under cursor
|_ie| make imports explit for import statement under cursor
|_opt| add OPTIONS_GHC pragma
|_lang| add LANGUAGE pragma
|i_CTRL-X_CTRL-O| insert-mode completion based on imported ids (|haskellmode-XO|)
|i_CTRL-X_CTRL-U| insert-mode completion based on documented ids (|haskellmode-XU|)
|i_CTRL-N| insert-mode completion based on imported sources
|:GHCi|{command/expr} run GHCi command/expr in current module
|:GHCStaticOptions| edit static GHC options for this buffer
|:DocSettings| show current Haddock-files-related plugin settings
|:DocIndex| populate Haddock index
|:ExportDocIndex| cache current Haddock index to a file
|:HpasteIndex| Read index of most recent entries from hpaste.org
|:HpastePostNew| Submit current buffer as a new hpaste
==============================================================================
*haskellmode-settings*
2. Settings ~
The plugins try to find their dependencies in standard locations, so if
you're lucky, you will only need to set |compiler| to ghc, and configure
the location of your favourite web browser. You will also want to make
sure that |filetype| detection and |syntax| highlighting are on. Given the
variety of things to guess, however, some dependencies might not be found
correctly, or the defaults might not be to your liking, in which case you
can do some more fine tuning. All of this configuration should happen in
your |vimrc|.
>
" enable syntax highlighting
syntax on
" enable filetype detection and plugin loading
filetype plugin on
<
*haskellmode-settings-main*
2.1 GHC and web browser ~
*compiler-ghc* *ghc-compiler*
To use the features provided by the GHC |compiler| plugin, use the
following |autocommand| in your vimrc:
>
au BufEnter *.hs compiler ghc
<
*g:ghc*
If the compiler plugin can't locate your GHC binary, or if you have
several versions of GHC installed and have a preference as to which binary
is used, set |g:ghc|:
>
:let g:ghc="/usr/bin/ghc-6.6.1"
<
*g:haddock_browser*
The preferred HTML browser for viewing Haddock documentation can be set as
follows:
>
:let g:haddock_browser="/usr/bin/firefox"
<
*haskellmode-settings-fine*
2.2 Fine tuning - more configuration options ~
Most of the fine tuning is likely to happen for the haskellmode_doc.vim
plugin, so you can check the current settings for this plugin via the
command |:DocSettings|. If all the settings reported there are to your
liking, you probably won't need to do any fine tuning.
*g:haddock_browser_callformat*
By default, the web browser|g:haddock_browser| will be started
asynchronously (in the background) on Windows or when vim is running in a
GUI, and synchronously (in the foreground) otherwise. These settings seem
to work fine if you are using a console mode browser (eg, when editing in
a remote session), or if you are starting a GUI browser that will launch
itself in the background. But if these settings do not work for you, you
can change the default browser launching behavior.
This is controlled by |g:haddock_browser_callformat|. It specifies a
format string which uses two '%s' parameters, the first representing the
path of the browser to launch, and the second is the documentation URL
(minus the protocol specifier, i.e. file://) passed to it by the Haddock
plugin. For instance, to launch a GUI browser on Unix-like systems and
force it to the background (see also |shellredir|):
>
:let g:haddock_browser_callformat = '%s file://%s '.printf(&shellredir,'/dev/null').' &'
<
*g:haddock_docdir*
Your system's installed Haddock documentation for GHC and its libraries
should be automatically detected. If the plugin can't locate them, you
must point |g:haddock_docdir| to the path containing the master index.html
file for the subdirectories 'libraries', 'Cabal', 'users_guide', etc.:
>
:let g:haddock_docdir="/usr/local/share/doc/ghc/html/"
<
*g:haddock_indexfiledir*
The information gathered from Haddock's index files will be stored in a
file called 'haddock_index.vim' in a directory derived from the Haddock
location, or in $HOME. To configure another directory for the index file,
use:
>
:let g:haddock_indexfiledir="~/.vim/"
<
*g:wget*
If you also want to try the experimental hpaste functionality, you might
you need to set |g:wget| before the |hpaste| plugin is loaded (unless wget
is in your PATH):
>
:let g:wget="C:\Program Files\wget\wget.exe"
<
Finally, the mappings actually use|<LocalLeader>|behind the scenes, so if
you have to, you can redefine|maplocalleader|to something other than '_'.
Just remember that the docs still refer to mappings starting with '_', to
avoid confusing the majority of users!-)
==============================================================================
*haskellmode-compiler* *ghc*
3. GHC Compiler Integration ~
The GHC |compiler| plugin sets the basic |errorformat| and |makeprg| to
enable |quickfix| mode using GHCi, and provides functionality for show
info (|_si|), show type (|_t| or mouse |balloon|), add type declaration
(|_T|), create tag file (|_ct|), and insert-mode completion
(|i_CTRL-X_CTRL-O|) based on GHCi browsing of the current and imported
modules.
To avoid frequent calls to GHCi, type information is cached in Vim. The
cache will be populated the first time a command depends on it, and will
be refreshed every time a |:make| goes through without generating errors
(if the |:make| does not succeed, the old types will remain available in
Vim). You can also unconditionally force reloading of type info using
|:GHCReload| (if GHCi cannot load your file, the type info will be empty).
In addition to the standard|quickfix| commands, the GHC compiler plugin
provides:
*:GHCReload*
:GHCReload Reload modules and unconditionally refresh cache of
type info. Usually, |:make| is prefered, as that will
refresh the cache only if GHCi reports no errors, and
show the errors otherwise.
*:GHCStaticOptions*
:GHCStaticOptions Edit the static GHC options (more generally, options
that cannot be set by in-file OPTIONS_GHC pragmas)
for the current buffer. Useful for adding hidden
packages (-package ghc), or additional import paths
(-isrc; you will then also want to augment |path|).
If you have static options you want to set as
defaults, you could use b:ghc_staticoptions, eg:
>
au FileType haskell let b:ghc_staticoptions = '-isrc'
au FileType haskell setlocal path += src
<
*:GHCi*
:GHCi {command/expr} Run GHCi commands/expressions in the current module.
*_ct*
_ct Create |tags| file for the current Haskell source
file. This uses GHCi's :ctags command, so it will work
recursively, but will only list tags for exported
entities.
*_opt*
_opt Shows a menu of frequently used GHC compiler options
(selecting an entry adds the option as a pragma to the
start of the file). Uses popup menu (GUI) or :emenu
and command-line completion (CLI).
*_lang*
_lang Shows a menu of the LANGUAGE options supported by GHC
(selecting an entry adds the language as a pragma to
the start of the file). Uses popup menu (GUI) or
:emenu and command-line completion (CLI).
*_si*
_si Show extended information for the name under the
cursor. Uses GHCi's :info command. Output appears in
|preview-window| (when done, close with |:pclose|).
*_t*
_t Show type for the name under the cursor. Uses cached
info from GHCi's :browse command.
*_T*
_T Insert type declaration for the name under the cursor.
Uses cached info from GHCi's :browse command.
*haskellmode-XO* *haskellmode-omni-completion*
CTRL-X CTRL-O Standard insert-mode omni-completion based on the
cached type info from GHCi browsing current and
imported modules. Only names from the current and from
imported modules are included (the completion menu
also show the type of each identifier).
==============================================================================
*haskellmode-haddock* *haddock*
4. Haddock Integration ~
Haskell mode integrates with Haddock-generated HTML documentation,
providing features such as navigating to the Haddock entry for the
identifier under the cursor (|_?|), completion for the identifier under
the cursor (|i_CTRL-X_CTRL-U|), and adding import statements (|_i| |_im|
|_iq| |_iqm|) or module qualifier (|_.|) for the identifier under the
cursor.
These commands operate on an internal Haddock index built from the
platform's installed Haddock documentation for GHC's libraries. Since
populating this index takes several seconds, it should be stored as a
file called 'haddock_index.vim' in the directory specified by
|g:haddock_indexfiledir|.
Some commands present a different interface (popup menu or command-line
completion) according to whether the current Vim instance is graphical or
console-based (actually: whether or not the GUI is running). Such
differences are marked below with the annotations (GUI) and (CLI),
respectively.
|:DocSettings| shows the settings for this plugin. If you are happy with
them, you can call |:ExportDocIndex| to populate and write out the
documentation index (should be called once for every new version of GHC).
*:DocSettings*
:DocSettings Show current Haddock-files-related plugin settings.
*haskellmode-indexing*
4.1 Indexing ~
*:DocIndex*
:DocIndex Populate the Haddock index from the GHC library
documentation.
*:ExportDocIndex*
:ExportDocIndex Cache the current Haddock index to a file (populate
index first, if empty).
*haskellmode-lookup*
4.2 Lookup ~
*_?*
_? Open the Haddock entry (in |haddock_browser|) for an
identifier under the cursor, selecting full
qualifications from a popup menu (GUI) or via
command-line completion (CLI), if the identifier is
not qualified.
*_?1*
_?1 Search Hoogle (using |haddock_browser|) for an
identifier under the cursor.
*_?2*
_?2 Search Hayoo! (using |haddock_browser|) for an
identifier under the cursor.
*:IDoc*
:IDoc {identifier} Open the Haddock entry for the unqualified
{identifier} in |haddock_browser|, suggesting possible
full qualifications.
*:MDoc*
:MDoc {module} Open the Haddock entry for {module} in
|haddock_browser| (with command-line completion for
the fully qualified module name).
*:FlagReference*
:FlagReference {s} Browse Users Guide Flag Reference for section {s}
(with command-line completion for section headers).
*haskellmode-editing*
4.3 Editing ~
*_.*
_. Fully qualify the unqualified name under the cursor
selecting full qualifications from a popup menu (GUI)
or via command-line completion (CLI).
*_iq* *_i*
_i _iq Add 'import [qualified] <module>(<identifier>)'
statement for the identifier under the cursor,
selecting fully qualified modules from a popup menu
(GUI) or via command-line completion (CLI), if the
identifier is not qualified. This currently adds one
import statement per call instead of merging into
existing import statements.
*_iqm* *_im*
_im Add 'import [qualified] <module>' statement for the
identifier under the cursor, selecting fully qualified
modules from a popup menu (GUI) or via command-line
completion (CLI), if the identifier is not qualified.
This currently adds one import statement per call
instead of merging into existing import statements.
*_ie*
_ie On an 'import <module>' line, in a correctly loadable
module, temporarily comment out import and use :make
'not in scope' errors to explicitly list imported
identifiers.
*haskellmode-XU* *haskellmode-user-completion*
CTRL-X CTRL-U User-defined insert mode name completion based on all
names known to the Haddock index, including package
names. Completions are presented in a popup menu which
also displays the fully qualified module from which
each entry may be imported.
CamelCode shortcuts are supported, meaning that
lower-case letters can be elided, using only
upper-case letters and module qualifier separators (.)
for disambiguation:
pSL -> putStrLn
C.E.t -> Control.Exception.t
C.M.MP -> Control.Monad.MonadPlus
To reduce unwanted matches, the first letter of such
shortcuts and the first letter after each '.' have to
match directly.
==============================================================================
*haskellmode-hpaste* *hpaste*
5. Hpaste Integration ~
This experimental feature allows browsing and posting to
http://hpaste.org, a Web-based pastebin tailored for Haskell code.
*:HpasteIndex*
:HpasteIndex Read the most recent entries from hpaste.org. Show an
index of the entries in a new buffer, where ',r' will
open the current highlighted entry [and ',p' will
annotate it with the current buffer].
*:HpastePostNew*
:HpastePostNew Submit current buffer as a new hpaste entry.
[This, and ',p' above, are temporarily disabled,
needs update to new hpaste.org layout]
==============================================================================
*haskellmode-resources*
6. Additional Resources ~
An quick screencast tour through of these plugins is available at:
http://projects.haskell.org/haskellmode-vim/screencasts.html
Other Haskell-related Vim plugins can be found here:
http://www.haskell.org/haskellwiki/Libraries_and_tools/Program_development#Vim
Make sure to read about Vim's other program-editing features in its online
|user-manual|. Also have a look at Vim tips and plugins at www.vim.org -
two other plugins I tend to use when editing Haskell are AlignPlugin.vim
(to line up regexps for definitions, keywords, comments, etc. in
consecutive lines) and surround.vim (to surround text with quotes,
brackets, parentheses, comments, etc.).
==============================================================================
vim:tw=78:ts=8:ft=help:
*supertab.txt*
Author: Eric Van Dewoestine <ervandew@gmail.com>
Original concept and versions up to 0.32 written by
Gergely Kontra <kgergely@mcl.hu>
This plugin is licensed under the terms of the BSD License. Please see
supertab.vim for the license in its entirety.
==============================================================================
Supertab *supertab*
1. Introduction |supertab-intro|
2. Supertab Usage |supertab-usage|
3. Supertab Options |supertab-options|
Default completion type |supertab-defaultcompletion|
Secondary default completion type |supertab-contextdefault|
Completion contexts |supertab-completioncontexts|
Context text |supertab-contexttext|
Context Discover |supertab-contextdiscover|
Example |supertab-contextexample|
Completion Duration |supertab-duration|
Preventing Completion After/Before... |supertab-preventcomplete|
Changing default mapping |supertab-forwardbackward|
Inserting true tabs |supertab-mappingtabliteral|
Enhanced longest match support |supertab-longestenhanced|
Preselecting the first entry |supertab-longesthighlight|
Mapping <cr> to end completion |supertab-crmapping|
Auto close the preview window |supertab-closepreviewonpopupclose|
Completion Chaining |supertab-completionchaining|
==============================================================================
1. Introduction *supertab-intro*
Supertab is a plugin which allows you to perform all your insert completion
(|ins-completion|) using the tab key.
Supertab requires Vim version 7.0 or above.
==============================================================================
2. Supertab usage *supertab-usage*
Using Supertab is as easy as hitting <Tab> or <S-Tab> (shift+tab) while in
insert mode, with at least one non whitespace character before the cursor, to
start the completion and then <Tab> or <S-Tab> again to cycle forwards or
backwards through the available completions.
Example ('|' denotes the cursor location):
bar
baz
b|<Tab> Hitting <Tab> here will start the completion, allowing you to
then cycle through the suggested words ('bar' and 'baz').
==============================================================================
3. Supertab Options *supertab-options*
Supertab is configured via several global variables that you can set in your
|vimrc| file according to your needs. Below is a comprehensive list of
the variables available.
Default Completion Type *supertab-defaultcompletion*
*g:SuperTabDefaultCompletionType*
g:SuperTabDefaultCompletionType (default value: "<c-p>")
Used to set the default completion type. There is no need to escape this
value as that will be done for you when the type is set.
Example: setting the default completion to 'user' completion:
let g:SuperTabDefaultCompletionType = "<c-x><c-u>"
Note: a special value of 'context' is supported which will result in
super tab attempting to use the text preceding the cursor to decide which
type of completion to attempt. Currently super tab can recognize method
calls or attribute references via '.', '::' or '->', and file path
references containing '/'.
let g:SuperTabDefaultCompletionType = "context"
/usr/l<tab> # will use filename completion
myvar.t<tab> # will use user completion if completefunc set,
# or omni completion if omnifunc set.
myvar-><tab> # same as above
When using context completion, super tab will fall back to a secondary default
completion type set by |g:SuperTabContextDefaultCompletionType|.
Note: once the buffer has been initialized, changing the value of this setting
will not change the default complete type used. If you want to change the
default completion type for the current buffer after it has been set, perhaps
in an ftplugin, you'll need to call SuperTabSetDefaultCompletionType like so,
supplying the completion type you wish to switch to:
call SuperTabSetDefaultCompletionType("<c-x><c-u>")
Secondary default completion type *supertab-contextdefault*
*g:SuperTabContextDefaultCompletionType*
g:SuperTabContextDefaultCompletionType (default value: "<c-p>")
Sets the default completion type used when g:SuperTabDefaultCompletionType is
set to 'context' and no completion type is returned by any of the configured
contexts.
Completion contexts *supertab-completioncontexts*
*g:SuperTabCompletionContexts*
g:SuperTabCompletionContexts (default value: ['s:ContextText'])
Sets the list of contexts used for context completion. This value should
be a list of function names which provide the context implementation.
When supertab starts the default completion, each of these contexts will be
consulted, in the order they were supplied, to determine the completion type
to use. If a context returns a completion type, that type will be used,
otherwise the next context in the list will be consulted. If after executing
all the context functions, no completion type has been determined, then the
value of g:SuperTabContextDefaultCompletionType will be used.
Built in completion contexts:
s:ContextText *supertab-contexttext*
The text context will examine the text near the cursor to decide which type
of completion to attempt. Currently the text context can recognize method
calls or attribute references via '.', '::' or '->', and file path
references containing '/'.
/usr/l<tab> # will use filename completion
myvar.t<tab> # will use user completion if completefunc set, or
# omni completion if omnifunc set.
myvar-><tab> # same as above
Supported configuration attributes:
g:SuperTabContextTextFileTypeExclusions
List of file types for which the text context will be skipped.
g:SuperTabContextTextOmniPrecedence
List of omni completion option names in the order of precedence that they
should be used if available. By default, user completion will be given
precedence over omni completion, but you can use this variable to give
omni completion higher precedence by placing it first in the list.
s:ContextDiscover *supertab-contextdiscover*
This context will use the 'g:SuperTabContextDiscoverDiscovery' variable to
determine the completion type to use. It will evaluate each value, in the
order they were defined, until a variable evaluates to a non-zero or
non-empty value, then the associated completion type is used.
Supported configuration properties:
g:SuperTabContextDiscoverDiscovery
List of variable:completionType mappings.
Example context configuration: *supertab-contextexample*
let g:SuperTabCompletionContexts = ['s:ContextText', 's:ContextDiscover']
let g:SuperTabContextTextOmniPrecedence = ['&omnifunc', '&completefunc']
let g:SuperTabContextDiscoverDiscovery =
\ ["&completefunc:<c-x><c-u>", "&omnifunc:<c-x><c-o>"]
In addition to the default completion contexts, you can plug in your own
implementation by creating a globally accessible function that returns
the completion type to use (eg. "\<c-x>\<c-u>").
function MyTagContext()
if filereadable(expand('%:p:h') . '/tags')
return "\<c-x>\<c-]>"
endif
" no return will result in the evaluation of the next
" configured context
endfunction
let g:SuperTabCompletionContexts =
\ ['MyTagContext', 's:ContextText', 's:ContextDiscover']
Note: supertab also supports the b:SuperTabCompletionContexts variable
allowing you to set the list of contexts separately for the current buffer,
like from an ftplugin for example.
Completion Duration *supertab-duration*
*g:SuperTabRetainCompletionDuration*
g:SuperTabRetainCompletionDuration (default value: 'insert')
Determines if, and for how long, the current completion type is retained.
The possible values include:
'completion' - The current completion type is only retained for the
current completion. Once you have chosen a completion
result or exited the completion mode, the default
completion type is restored.
'insert' - The current completion type is saved until you exit insert
mode (via ESC). Once you exit insert mode the default
completion type is restored. (supertab default)
'session' - The current completion type is saved for the duration of
your vim session or until you enter a different completion
mode.
Preventing completion after... *supertab-preventcomplete*
*g:SuperTabNoCompleteBefore*
*g:SuperTabNoCompleteAfter*
g:SuperTabNoCompleteBefore (default value: [])
g:SuperTabNoCompleteAfter (default value: ['^', '\s'])
These two variables are used to control when supertab will attempt completion
or instead fall back to inserting a literal <tab>. There are two possible ways
to define these variables:
1) by specifying a list of patterns which are tested against the text before
and after the current cursor position that when matched, prevent completion.
So if you don't want supertab to start completion at the start of a line,
after a comma, or after a space, you can set g:SuperTabNoCompleteAfter
to ['^', ',', '\s'].
2) by specifying a funcref to a global accessible function which expects
as parameter the text to be inspected (before or after) and, based on that (or
other factors), it returns 1 if completion must be prevented, 0 otherwise.
Note: That a buffer local version of these variables
(b:SuperTabNoCompleteBefore, b:SuperTabNoCompleteAfter) is also supported
should you wish to have different values depending on the file type for
instance.
Changing the default mapping *supertab-forwardbackward*
*g:SuperTabMappingForward*
*g:SuperTabMappingBackward*
g:SuperTabMappingForward (default value: '<tab>')
g:SuperTabMappingBackward (default value: '<s-tab>')
These two variables allow you to set the keys used to kick off the current
completion. By default this is <tab> and <s-tab>. To change to something
like <c-space> and <s-c-space>, you can add the following to your |vimrc|.
let g:SuperTabMappingForward = '<c-space>'
let g:SuperTabMappingBackward = '<s-c-space>'
Note: if the above does not have the desired effect (which may happen in
console version of vim), you can try the following mappings. Although the
backwards mapping still doesn't seem to work in the console for me, your
milage may vary.
let g:SuperTabMappingForward = '<nul>'
let g:SuperTabMappingBackward = '<s-nul>'
Inserting true tabs *supertab-mappingtabliteral*
*g:SuperTabMappingTabLiteral*
g:SuperTabMappingTabLiteral (default value: '<c-tab>')
Sets the key mapping used to insert a literal tab where supertab would
otherwise attempt to kick off insert completion. The default is '<c-tab>'
(ctrl-tab) which unfortunately might not work at the console. So if you are
using a console vim and want this functionality, you may have to change it to
something that is supported. Alternatively, you can escape the <tab> with
<c-v> (see |i_CTRL-V| for more infos).
Enhanced longest match support *supertab-longestenhanced*
*g:SuperTabLongestEnhanced*
g:SuperTabLongestEnhanced (default value: 0)
When enabled and 'longest' is in your |completeopt| setting, supertab will
provide an enhanced longest match support where typing one or more letters and
hitting tab again while in a completion mode will complete the longest common
match using the new text in the buffer.
For example, say you have a buffer with the following contents:
FooBarFoo
FooBar
Foo
FooBarBaz
And you then type F<tab>. Vim's builtin longest support will complete the
longest common text 'Foo' and offer 'FooBarFoo', 'FooBar', 'Foo', and
'FooBarBaz' as possible completions. With supertab's longest match
enhancement disabled, typing B<tab> while still in the completion mode will
end up completing 'FooBarBaz' or 'FooBarFoo' depending your settings, instead
of the next longest common match of 'FooBar'. With supertab's enhanced
longest match feature enabled, the typing of B<tab> will result in the next
longest text being completed.
Preselecting the first entry *supertab-longesthighlight*
*g:SuperTabLongestHighlight*
g:SuperTabLongestHighlight (default value: 0)
Sets whether or not to pre-highlight the first match when completeopt has the
popup menu enabled and the 'longest' option as well. When enabled, <tab> will
kick off completion and pre-select the first entry in the popup menu, allowing
you to simply hit <enter> to use it.
Mapping <cr> to end completion *supertab-crmapping*
*g:SuperTabCrMapping*
g:SuperTabCrMapping (default value: 1)
When enabled, <cr> will cancel completion mode preserving the current text.
Compatibility with other plugins:
- endwise: compatible
- delimitMate: not compatible (disabled if the delimitMate <cr> mapping is
detected.)
Note: if you have an insert expression mapping with a <cr> in it or an insert
abbreviation containing a <cr>, then supertab will not create a <cr> mapping
which could potentially cause problems with those.
Auto close the preview window *supertab-closepreviewonpopupclose*
*g:SuperTabClosePreviewOnPopupClose*
g:SuperTabClosePreviewOnPopupClose (default value: 0)
When enabled, supertab will attempt to close vim's completion preview window
when the completion popup closes (completion is finished or canceled).
Completion Chaining *supertab-completionchaining*
SuperTab provides the ability to chain one of the completion functions
(|completefunc| or |omnifunc|) together with a one of the default vim
completion key sequences (|ins-completion|), giving you the ability to attempt
completion with the first, and upon no results, fall back to the second.
To utilize this feature you need to call the SuperTabChain function where
the first argument is the name of a vim compatible |complete-function| and the
second is one of vim's insert completion (|ins-completion|) key bindings
(<c-p>, <c-n>, <c-x><c-]>, etc). Calling this function will set the current
buffer's |completefunc| option to a supertab provided implementation which
utilizes the supplied arguments to perform the completion. Since the
|completefunc| option is being set, this feature works best when also
setting |g:SuperTabDefaultCompletionType| to either "context" or "<c-x><c-u>".
Here is an example that can be added to your .vimrc which will setup the
supertab chaining for any filetype that has a provided |omnifunc| to first
try that, then fall back to supertab's default, <c-p>, completion:
autocmd FileType *
\ if &omnifunc != '' |
\ call SuperTabChain(&omnifunc, "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
\ endif
Note: This feature does not support chaining any other combination of
completions (2 or more completion functions, 2 or more key bindings, etc.). It
can only support 1 completion function followed by 1 key binding. This is due
to limitations imposed by vim's code completion implementation.
Note: If the |completefunc| or |omnifunc| use vim's |complete_add()| instead
of returning completion results as a list, then Supertab's completion chaining
won't work properly with it since Supertab uses the function result to
determine if it should fallback to the next completion type.
vim:tw=78:ts=8:ft=help:norl:
:Align Align.txt /*:Align*
:AlignCtrl Align.txt /*:AlignCtrl*
:AlignMapsClean Align.txt /*:AlignMapsClean*
:DocIndex haskellmode.txt /*:DocIndex*
:DocSettings haskellmode.txt /*:DocSettings*
:ExportDocIndex haskellmode.txt /*:ExportDocIndex*
:FlagReference haskellmode.txt /*:FlagReference*
:GHCReload haskellmode.txt /*:GHCReload*
:GHCStaticOptions haskellmode.txt /*:GHCStaticOptions*
:GHCi haskellmode.txt /*:GHCi*
:HpasteIndex haskellmode.txt /*:HpasteIndex*
:HpastePostNew haskellmode.txt /*:HpastePostNew*
:IDoc haskellmode.txt /*:IDoc*
:MDoc haskellmode.txt /*:MDoc*
Align-copyright Align.txt /*Align-copyright*
_. haskellmode.txt /*_.*
_? haskellmode.txt /*_?*
_?1 haskellmode.txt /*_?1*
_?2 haskellmode.txt /*_?2*
_T haskellmode.txt /*_T*
_ct haskellmode.txt /*_ct*
_i haskellmode.txt /*_i*
_ie haskellmode.txt /*_ie*
_im haskellmode.txt /*_im*
_iq haskellmode.txt /*_iq*
_iqm haskellmode.txt /*_iqm*
_lang haskellmode.txt /*_lang*
_opt haskellmode.txt /*_opt*
_si haskellmode.txt /*_si*
_t haskellmode.txt /*_t*
align Align.txt /*align*
align-align Align.txt /*align-align*
align-codepoint Align.txt /*align-codepoint*
align-command Align.txt /*align-command*
align-commands Align.txt /*align-commands*
align-concept Align.txt /*align-concept*
align-concepts Align.txt /*align-concepts*
align-contents Align.txt /*align-contents*
align-control Align.txt /*align-control*
align-history Align.txt /*align-history*
align-manual Align.txt /*align-manual*
align-maps Align.txt /*align-maps*
align-multibyte Align.txt /*align-multibyte*
align-option Align.txt /*align-option*
align-options Align.txt /*align-options*
align-strlen Align.txt /*align-strlen*
align-usage Align.txt /*align-usage*
align-userguide Align.txt /*align-userguide*
align-utf Align.txt /*align-utf*
align-utf8 Align.txt /*align-utf8*
align-xstrlen Align.txt /*align-xstrlen*
align.txt Align.txt /*align.txt*
alignctrl Align.txt /*alignctrl*
alignctrl- Align.txt /*alignctrl-*
alignctrl-+ Align.txt /*alignctrl-+*
alignctrl-- Align.txt /*alignctrl--*
alignctrl-: Align.txt /*alignctrl-:*
alignctrl-< Align.txt /*alignctrl-<*
alignctrl-= Align.txt /*alignctrl-=*
alignctrl-> Align.txt /*alignctrl->*
alignctrl-C Align.txt /*alignctrl-C*
alignctrl-I Align.txt /*alignctrl-I*
alignctrl-P Align.txt /*alignctrl-P*
alignctrl-W Align.txt /*alignctrl-W*
alignctrl-alignskip Align.txt /*alignctrl-alignskip*
alignctrl-c Align.txt /*alignctrl-c*
alignctrl-g Align.txt /*alignctrl-g*
alignctrl-init Align.txt /*alignctrl-init*
alignctrl-initialization Align.txt /*alignctrl-initialization*
alignctrl-l Align.txt /*alignctrl-l*
alignctrl-m Align.txt /*alignctrl-m*
alignctrl-no-option Align.txt /*alignctrl-no-option*
alignctrl-p Align.txt /*alignctrl-p*
alignctrl-r Align.txt /*alignctrl-r*
alignctrl-separators Align.txt /*alignctrl-separators*
alignctrl-settings Align.txt /*alignctrl-settings*
alignctrl-star Align.txt /*alignctrl-star*
alignctrl-v Align.txt /*alignctrl-v*
alignctrl-w Align.txt /*alignctrl-w*
alignman Align.txt /*alignman*
alignmanual Align.txt /*alignmanual*
alignmap-Htd Align.txt /*alignmap-Htd*
alignmap-T= Align.txt /*alignmap-T=*
alignmap-Tsp Align.txt /*alignmap-Tsp*
alignmap-a( Align.txt /*alignmap-a(*
alignmap-a, Align.txt /*alignmap-a,*
alignmap-a< Align.txt /*alignmap-a<*
alignmap-a= Align.txt /*alignmap-a=*
alignmap-a? Align.txt /*alignmap-a?*
alignmap-abox Align.txt /*alignmap-abox*
alignmap-acom Align.txt /*alignmap-acom*
alignmap-adcom Align.txt /*alignmap-adcom*
alignmap-adec Align.txt /*alignmap-adec*
alignmap-adef Align.txt /*alignmap-adef*
alignmap-afnc Align.txt /*alignmap-afnc*
alignmap-anum Align.txt /*alignmap-anum*
alignmap-aocom Align.txt /*alignmap-aocom*
alignmap-ascom Align.txt /*alignmap-ascom*
alignmap-history Align.txt /*alignmap-history*
alignmap-m= Align.txt /*alignmap-m=*
alignmap-t# Align.txt /*alignmap-t#*
alignmap-t, Align.txt /*alignmap-t,*
alignmap-t: Align.txt /*alignmap-t:*
alignmap-t; Align.txt /*alignmap-t;*
alignmap-t< Align.txt /*alignmap-t<*
alignmap-t= Align.txt /*alignmap-t=*
alignmap-t? Align.txt /*alignmap-t?*
alignmap-tab Align.txt /*alignmap-tab*
alignmap-tml Align.txt /*alignmap-tml*
alignmap-ts, Align.txt /*alignmap-ts,*
alignmap-ts: Align.txt /*alignmap-ts:*
alignmap-ts< Align.txt /*alignmap-ts<*
alignmap-ts= Align.txt /*alignmap-ts=*
alignmap-tsp Align.txt /*alignmap-tsp*
alignmap-tsq Align.txt /*alignmap-tsq*
alignmap-tt Align.txt /*alignmap-tt*
alignmap-t~ Align.txt /*alignmap-t~*
alignmaps Align.txt /*alignmaps*
alignusage Align.txt /*alignusage*
autoalign AutoAlign.txt /*autoalign*
autoalign-contents AutoAlign.txt /*autoalign-contents*
autoalign-copyright AutoAlign.txt /*autoalign-copyright*
autoalign-history AutoAlign.txt /*autoalign-history*
autoalign-install AutoAlign.txt /*autoalign-install*
autoalign-internals AutoAlign.txt /*autoalign-internals*
autoalign-man AutoAlign.txt /*autoalign-man*
autoalign.txt AutoAlign.txt /*autoalign.txt*
compiler-ghc haskellmode.txt /*compiler-ghc*
g:AlignSkip Align.txt /*g:AlignSkip*
g:SuperTabClosePreviewOnPopupClose supertab.txt /*g:SuperTabClosePreviewOnPopupClose*
g:SuperTabCompletionContexts supertab.txt /*g:SuperTabCompletionContexts*
g:SuperTabContextDefaultCompletionType supertab.txt /*g:SuperTabContextDefaultCompletionType*
g:SuperTabCrMapping supertab.txt /*g:SuperTabCrMapping*
g:SuperTabDefaultCompletionType supertab.txt /*g:SuperTabDefaultCompletionType*
g:SuperTabLongestEnhanced supertab.txt /*g:SuperTabLongestEnhanced*
g:SuperTabLongestHighlight supertab.txt /*g:SuperTabLongestHighlight*
g:SuperTabMappingBackward supertab.txt /*g:SuperTabMappingBackward*
g:SuperTabMappingForward supertab.txt /*g:SuperTabMappingForward*
g:SuperTabMappingTabLiteral supertab.txt /*g:SuperTabMappingTabLiteral*
g:SuperTabNoCompleteAfter supertab.txt /*g:SuperTabNoCompleteAfter*
g:SuperTabNoCompleteBefore supertab.txt /*g:SuperTabNoCompleteBefore*
g:SuperTabRetainCompletionDuration supertab.txt /*g:SuperTabRetainCompletionDuration*
g:alignmaps_euronumber Align.txt /*g:alignmaps_euronumber*
g:alignmaps_usanumber Align.txt /*g:alignmaps_usanumber*
g:ghc haskellmode.txt /*g:ghc*
g:haddock_browser haskellmode.txt /*g:haddock_browser*
g:haddock_browser_callformat haskellmode.txt /*g:haddock_browser_callformat*
g:haddock_docdir haskellmode.txt /*g:haddock_docdir*
g:haddock_indexfiledir haskellmode.txt /*g:haddock_indexfiledir*
g:wget haskellmode.txt /*g:wget*
ghc haskellmode.txt /*ghc*
ghc-compiler haskellmode.txt /*ghc-compiler*
haddock haskellmode.txt /*haddock*
haskellmode haskellmode.txt /*haskellmode*
haskellmode-XO haskellmode.txt /*haskellmode-XO*
haskellmode-XU haskellmode.txt /*haskellmode-XU*
haskellmode-compiler haskellmode.txt /*haskellmode-compiler*
haskellmode-editing haskellmode.txt /*haskellmode-editing*
haskellmode-haddock haskellmode.txt /*haskellmode-haddock*
haskellmode-hpaste haskellmode.txt /*haskellmode-hpaste*
haskellmode-indexing haskellmode.txt /*haskellmode-indexing*
haskellmode-lookup haskellmode.txt /*haskellmode-lookup*
haskellmode-omni-completion haskellmode.txt /*haskellmode-omni-completion*
haskellmode-overview haskellmode.txt /*haskellmode-overview*
haskellmode-quickref haskellmode.txt /*haskellmode-quickref*
haskellmode-requirements haskellmode.txt /*haskellmode-requirements*
haskellmode-resources haskellmode.txt /*haskellmode-resources*
haskellmode-settings haskellmode.txt /*haskellmode-settings*
haskellmode-settings-fine haskellmode.txt /*haskellmode-settings-fine*
haskellmode-settings-main haskellmode.txt /*haskellmode-settings-main*
haskellmode-user-completion haskellmode.txt /*haskellmode-user-completion*
haskellmode.txt haskellmode.txt /*haskellmode.txt*
hpaste haskellmode.txt /*hpaste*
supertab supertab.txt /*supertab*
supertab-closepreviewonpopupclose supertab.txt /*supertab-closepreviewonpopupclose*
supertab-completionchaining supertab.txt /*supertab-completionchaining*
supertab-completioncontexts supertab.txt /*supertab-completioncontexts*
supertab-contextdefault supertab.txt /*supertab-contextdefault*
supertab-contextdiscover supertab.txt /*supertab-contextdiscover*
supertab-contextexample supertab.txt /*supertab-contextexample*
supertab-contexttext supertab.txt /*supertab-contexttext*
supertab-crmapping supertab.txt /*supertab-crmapping*
supertab-defaultcompletion supertab.txt /*supertab-defaultcompletion*
supertab-duration supertab.txt /*supertab-duration*
supertab-forwardbackward supertab.txt /*supertab-forwardbackward*
supertab-intro supertab.txt /*supertab-intro*
supertab-longestenhanced supertab.txt /*supertab-longestenhanced*
supertab-longesthighlight supertab.txt /*supertab-longesthighlight*
supertab-mappingtabliteral supertab.txt /*supertab-mappingtabliteral*
supertab-options supertab.txt /*supertab-options*
supertab-preventcomplete supertab.txt /*supertab-preventcomplete*
supertab-usage supertab.txt /*supertab-usage*
supertab.txt supertab.txt /*supertab.txt*
"
" general Haskell source settings
" (shared functions are in autoload/haskellmode.vim)
"
" (Claus Reinke, last modified: 28/04/2009)
"
" part of haskell plugins: http://projects.haskell.org/haskellmode-vim
" please send patches to <claus.reinke@talk21.com>
" try gf on import line, or ctrl-x ctrl-i, or [I, [i, ..
setlocal include=^import\\s*\\(qualified\\)\\?\\s*
setlocal includeexpr=substitute(v:fname,'\\.','/','g').'.'
setlocal suffixesadd=hs,lhs,hsc
" Haskell Cuteness for Vim.
" Inspired by emacs-haskell-cuteness.
" Based on unilatex.vim by Jos van den Oever <oever@fenk.wau.nl>
"
" Changelog
" 0.1.3 - added more mappings and fixed bug in HaskellSrcToUTF8, thanks
" to edwardkmett at Reddit
" 0.1.2 - added syntax highlighting as suggested by sfvisser at Reddit
" 0.1.1 - fixed stupid bug with haskell lambda expression
" 0.1 - initial release
"
" Version: 0.1.2
" Last Changed: 7 April 2009
" Maintainer: Andrey Popp <andrey.popp@braintrace.ru>
" Map to unicode symbols
imap <buffer> \ λ
imap <buffer> <-
imap <buffer> ->
imap <buffer> <=
imap <buffer> >=
imap <buffer> ==
imap <buffer> /=
imap <buffer> =>
imap <buffer> >> »
imap <buffer> .<space><space>
imap <buffer> forall<space>
" Turn syntax highlight on for new symbols
syn match hsVarSym "(\|λ\|←\|→\|≲\|≳\|≡\|≠\| )"
if exists("s:loaded_unihaskell")
finish
endif
let s:loaded_unihaskell = 1
augroup HaskellC
autocmd BufReadPost *.hs cal s:HaskellSrcToUTF8()
autocmd BufWritePre *.hs cal s:UTF8ToHaskellSrc()
autocmd BufWritePost *.hs cal s:HaskellSrcToUTF8()
augroup END
" function to convert ''fancy haskell source'' to haskell source
function s:UTF8ToHaskellSrc()
let s:line = line(".")
let s:column = col(".")
silent %s/λ/\\/eg
silent %s/←/<-/eg
silent %s/→/->/eg
silent %s/≲/<=/eg
silent %s/≳/>=/eg
silent %s/≡/==/eg
silent %s/≠/\/=/eg
silent %s/⇒/=>/eg
silent %s/»/>>/eg
silent %s/∙ /. /eg
silent %s/∀/forall /eg
let &l:fileencoding = s:oldencoding
call cursor(s:line,s:column)
endfunction
" function to convert haskell source to ''fancy haskell source''
function s:HaskellSrcToUTF8()
let s:line = line(".")
let s:column = col(".")
let s:oldencoding = &l:fileencoding
set fileencoding=utf-8
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=\\\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/λ\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=->\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/→\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=<-\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/←\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=<=\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/≲\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=>=\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/≳\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<===\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/≡\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=\/=\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/≠\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<==>\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/⇒\1/eg
silent %s/[^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>?@\^|~.]\@<=>>\([^λ←→≲≳≡≠⇒»∙∀\\\-!#$%&*+/<=>\?@\^|~.]\)/»\1/eg
silent %s/forall /∀/eg
silent %s/ \@<=\. /∙ /eg
let &l:fileencoding = s:oldencoding
call cursor(s:line,s:column)
endfunction
do HaskellC BufRead
"
" use haddock docs and index files
" show documentation, complete & qualify identifiers
"
" (Claus Reinke; last modified: 17/06/2009)
"
" part of haskell plugins: http://projects.haskell.org/haskellmode-vim
" please send patches to <claus.reinke@talk21.com>
" :Doc <name> and :IDoc <name> open haddocks for <name> in opera
"
" :Doc needs qualified name (default Prelude) and package (default base)
" :IDoc needs unqualified name, looks up possible links in g:haddock_index
"
" :DocIndex populates g:haddock_index from haddock's index files
" :ExportDocIndex saves g:haddock_index to cache file
" :ImportDocIndex reloads g:haddock_index from cache file
"
" all the following use the haddock index (g:haddock_index)
"
" _? opens haddocks for unqualified name under cursor,
" suggesting alternative full qualifications in popup menu
"
" _. fully qualifies unqualified name under cursor,
" suggesting alternative full qualifications in popup menu
"
" _i add import <module>(<name>) statement for unqualified <name> under cursor,
" _im add import <module> statement for unqualified <name> under cursor,
" suggesting alternative full qualifications in popup menu
" (this currently adds one statement per call, instead of
" merging into existing import statements, but it's a start;-)
"
" CTRL-X CTRL-U (user-defined insert mode completion)
" suggests completions of unqualified names in popup menu
let s:scriptname = "haskell_doc.vim"
" script parameters
" g:haddock_browser *mandatory* which browser to call
" g:haddock_browser_callformat [optional] how to call browser
" g:haddock_indexfiledir [optional] where to put 'haddock_index.vim'
" g:haddock_docdir [optional] where to find html docs
" g:ghc [optional] which ghc to call
" g:ghc_pkg [optional] which ghc_pkg to call
" been here before?
if exists("g:haddock_index")
finish
endif
" initialise nested dictionary, to be populated
" - from haddock index files via :DocIndex
" - from previous cached version via :ImportDocIndex
let g:haddock_index = {}
" initialise dictionary, mapping modules with haddocks to their packages,
" populated via MkHaddockModuleIndex() or HaveModuleIndex()
let g:haddock_moduleindex = {}
" program to open urls, please set this in your vimrc
"examples (for windows):
"let g:haddock_browser = "C:/Program Files/Opera/Opera.exe"
"let g:haddock_browser = "C:/Program Files/Mozilla Firefox/firefox.exe"
"let g:haddock_browser = "C:/Program Files/Internet Explorer/IEXPLORE.exe"
if !exists("g:haddock_browser")
echoerr s:scriptname." WARNING: please set g:haddock_browser!"
endif
if !haskellmode#GHC() | finish | endif
if (!exists("g:ghc_pkg") || !executable(g:ghc_pkg))
let g:ghc_pkg = substitute(g:ghc,'\(.*\)ghc','\1ghc-pkg','')
endif
if exists("g:haddock_docdir") && isdirectory(g:haddock_docdir)
let s:docdir = g:haddock_docdir
elseif executable(g:ghc_pkg)
" try to figure out location of html docs
" first choice: where the base docs are (from the first base listed)
let [field;x] = split(system(g:ghc_pkg . ' field base haddock-html'),'\n')
" path changes in ghc-6.12.*
" let field = substitute(field,'haddock-html: \(.*\)libraries.base','\1','')
let field = substitute(field,'haddock-html: \(.*\)lib\(raries\)\?.base.*$','\1','')
let field = substitute(field,'\\','/','g')
" let alternate = substitute(field,'html','doc/html','')
" changes for ghc-6.12.*: check for doc/html/ first
let alternate = field.'doc/html/'
if isdirectory(alternate)
let s:docdir = alternate
elseif isdirectory(field)
let s:docdir = field
endif
else
echoerr s:scriptname." can't find ghc-pkg (set g:ghc_pkg ?)."
endif
" second choice: try some known suspects for windows/unix
if !exists('s:docdir') || !isdirectory(s:docdir)
let s:ghc_libdir = substitute(system(g:ghc . ' --print-libdir'),'\n','','')
let location1a = s:ghc_libdir . '/doc/html/'
let location1b = s:ghc_libdir . '/doc/'
let location2 = '/usr/share/doc/ghc-' . haskellmode#GHC_Version() . '/html/'
if isdirectory(location1a)
let s:docdir = location1a
elseif isdirectory(location1b)
let s:docdir = location1b
elseif isdirectory(location2)
let s:docdir = location2
else " give up
echoerr s:scriptname." can't find locaton of html documentation (set g:haddock_docdir)."
finish
endif
endif
" todo: can we turn s:docdir into a list of paths, and
" include docs for third-party libs as well?
let s:libraries = s:docdir . 'libraries/'
let s:guide = s:docdir . 'users_guide/'
let s:index = 'index.html'
if exists("g:haddock_indexfiledir") && filewritable(g:haddock_indexfiledir)
let s:haddock_indexfiledir = g:haddock_indexfiledir
elseif filewritable(s:libraries)
let s:haddock_indexfiledir = s:libraries
elseif filewritable($HOME)
let s:haddock_indexfiledir = $HOME.'/'
else "give up
echoerr s:scriptname." can't locate index file. please set g:haddock_indexfiledir"
finish
endif
let s:haddock_indexfile = s:haddock_indexfiledir . 'haddock_index.vim'
" different browser setups require different call formats;
" you might want to call the browser synchronously or
" asynchronously, and the latter is os-dependent;
"
" by default, the browser is started in the background when on
" windows or if running in a gui, and in the foreground otherwise
" (eg, console-mode for remote sessions, with text-mode browsers).
"
" you can override these defaults in your vimrc, via a format
" string including 2 %s parameters (the first being the browser
" to call, the second being the url).
if !exists("g:haddock_browser_callformat")
if has("win32") || has("win64")
let g:haddock_browser_callformat = 'start %s "%s"'
else
if has("gui_running")
let g:haddock_browser_callformat = '%s %s '.printf(&shellredir,'/dev/null').' &'
else
let g:haddock_browser_callformat = '%s %s'
endif
endif
endif
" allow map leader override
if !exists("maplocalleader")
let maplocalleader='_'
endif
command! DocSettings call DocSettings()
function! DocSettings()
for v in ["g:haddock_browser","g:haddock_browser_callformat","g:haddock_docdir","g:haddock_indexfiledir","s:ghc_libdir","g:ghc_version","s:docdir","s:libraries","s:guide","s:haddock_indexfile"]
if exists(v)
echo v '=' eval(v)
else
echo v '='
endif
endfor
endfunction
function! DocBrowser(url)
"echomsg "DocBrowser(".url.")"
if (!exists("g:haddock_browser") || !executable(g:haddock_browser))
echoerr s:scriptname." can't find documentation browser. please set g:haddock_browser"
return
endif
" start browser to open url, according to specified format
let url = a:url=~'^\(file://\|http://\)' ? a:url : 'file://'.a:url
silent exe '!'.printf(g:haddock_browser_callformat,g:haddock_browser,escape(url,'#%'))
endfunction
"Doc/Doct are an old interface for documentation lookup
"(that is the reason they are not documented!-)
"
"These uses are still fine at the moment, and are the reason
"that this command still exists at all
"
" :Doc -top
" :Doc -libs
" :Doc -guide
"
"These uses may or may not work, and shouldn't be relied on anymore
"(usually, you want _?/_?1/_?2 or :MDoc; there is also :IDoc)
"
" :Doc length
" :Doc Control.Monad.when
" :Doc Data.List.
" :Doc Control.Monad.State.runState mtl
command! -nargs=+ Doc call Doc('v',<f-args>)
command! -nargs=+ Doct call Doc('t',<f-args>)
function! Doc(kind,qualname,...)
let suffix = '.html'
let relative = '#'.a:kind.'%3A'
if a:qualname=="-top"
call DocBrowser(s:docdir . s:index)
return
elseif a:qualname=="-libs"
call DocBrowser(s:libraries . s:index)
return
elseif a:qualname=="-guide"
call DocBrowser(s:guide . s:index)
return
endif
if a:0==0 " no package specified
let package = 'base/'
else
let package = a:1 . '/'
endif
if match(a:qualname,'\.')==-1 " unqualified name
let [qual,name] = [['Prelude'],a:qualname]
let file = join(qual,'-') . suffix . relative . name
elseif a:qualname[-1:]=='.' " module qualifier only
let parts = split(a:qualname,'\.')
let quallen = len(parts)-1
let [qual,name] = [parts[0:quallen],parts[-1]]
let file = join(qual,'-') . suffix
else " qualified name
let parts = split(a:qualname,'\.')
let quallen = len(parts)-2
let [qual,name] = [parts[0:quallen],parts[-1]]
let file = join(qual,'-') . suffix . relative . name
endif
let path = s:libraries . package . file
call DocBrowser(path)
endfunction
" TODO: add commandline completion for :IDoc
" switch to :emenu instead of inputlist?
" indexed variant of Doc, looking up links in g:haddock_index
" usage:
" 1. :IDoc length
" 2. click on one of the choices, or select by number (starting from 0)
command! -nargs=+ IDoc call IDoc(<f-args>)
function! IDoc(name,...)
let choices = HaddockIndexLookup(a:name)
if choices=={} | return | endif
if a:0==0
let keylist = map(deepcopy(keys(choices)),'substitute(v:val,"\\[.\\]","","")')
let choice = inputlist(keylist)
else
let choice = a:1
endif
let path = values(choices)[choice] " assumes same order for keys/values..
call DocBrowser(path)
endfunction
let s:flagref = s:guide . 'flag-reference.html'
if filereadable(s:flagref)
" extract the generated fragment ids for the
" flag reference sections
let s:headerPat = '.\{-}<h3 class="title"><a name="\([^"]*\)"><\/a>\([^<]*\)<\/h3>\(.*\)'
let s:flagheaders = []
let s:flagheaderids = {}
let s:contents = join(readfile(s:flagref))
let s:ml = matchlist(s:contents,s:headerPat)
while s:ml!=[]
let [_,s:id,s:title,s:r;s:x] = s:ml
let s:flagheaders = add(s:flagheaders, s:title)
let s:flagheaderids[s:title] = s:id
let s:ml = matchlist(s:r,s:headerPat)
endwhile
command! -nargs=1 -complete=customlist,CompleteFlagHeaders FlagReference call FlagReference(<f-args>)
function! FlagReference(section)
let relativeUrl = a:section==""||!exists("s:flagheaderids['".a:section."']") ?
\ "" : "#".s:flagheaderids[a:section]
call DocBrowser(s:flagref.relativeUrl)
endfunction
function! CompleteFlagHeaders(al,cl,cp)
let s:choices = s:flagheaders
return CompleteAux(a:al,a:cl,a:cp)
endfunction
endif
command! -nargs=1 -complete=customlist,CompleteHaddockModules MDoc call MDoc(<f-args>)
function! MDoc(module)
let suffix = '.html'
call HaveModuleIndex()
if !has_key(g:haddock_moduleindex,a:module)
echoerr a:module 'not found in haddock module index'
return
endif
let package = g:haddock_moduleindex[a:module]['package']
let file = substitute(a:module,'\.','-','g') . suffix
" let path = s:libraries . package . '/' . file
let path = g:haddock_moduleindex[a:module]['html']
call DocBrowser(path)
endfunction
function! CompleteHaddockModules(al,cl,cp)
call HaveModuleIndex()
let s:choices = keys(g:haddock_moduleindex)
return CompleteAux(a:al,a:cl,a:cp)
endfunction
" create a dictionary g:haddock_index, containing the haddoc index
command! DocIndex call DocIndex()
function! DocIndex()
let files = split(globpath(s:libraries,'doc-index*.html'),'\n')
let g:haddock_index = {}
if haskellmode#GHC_VersionGE([7,0,0])
call ProcessHaddockIndexes3(s:libraries,files)
else
call ProcessHaddockIndexes2(s:libraries,files)
endif
if haskellmode#GHC_VersionGE([6,8,2])
if &shell =~ 'sh' " unix-type shell
let s:addon_libraries = split(system(g:ghc_pkg . ' field \* haddock-html'),'\n')
else " windows cmd.exe and the like
let s:addon_libraries = split(system(g:ghc_pkg . ' field * haddock-html'),'\n')
endif
for addon in s:addon_libraries
let ml = matchlist(addon,'haddock-html: \("\)\?\(file:///\)\?\([^"]*\)\("\)\?')
if ml!=[]
let [_,quote,file,addon_path;x] = ml
let addon_path = substitute(addon_path,'\(\\\\\|\\\)','/','g')
let addon_files = split(globpath(addon_path,'doc-index*.html'),'\n')
if haskellmode#GHC_VersionGE([7,0,0])
call ProcessHaddockIndexes3(addon_path,addon_files)
else
call ProcessHaddockIndexes2(addon_path,addon_files)
endif
endif
endfor
endif
return 1
endfunction
function! ProcessHaddockIndexes(location,files)
let entryPat= '.\{-}"indexentry"[^>]*>\([^<]*\)<\(\%([^=]\{-}TD CLASS="\%(indexentry\)\@!.\{-}</TD\)*\)[^=]\{-}\(\%(="indexentry\|TABLE\).*\)'
let linkPat = '.\{-}HREF="\([^"]*\)".>\([^<]*\)<\(.*\)'
redraw
echo 'populating g:haddock_index from haddock index files in ' a:location
for f in a:files
echo f[len(a:location):]
let contents = join(readfile(f))
let ml = matchlist(contents,entryPat)
while ml!=[]
let [_,entry,links,r;x] = ml
"echo entry links
let ml2 = matchlist(links,linkPat)
let link = {}
while ml2!=[]
let [_,l,m,links;x] = ml2
"echo l m
let link[m] = a:location . '/' . l
let ml2 = matchlist(links,linkPat)
endwhile
let g:haddock_index[DeHTML(entry)] = deepcopy(link)
"echo entry g:haddock_index[entry]
let ml = matchlist(r,entryPat)
endwhile
endfor
endfunction
" concatenating all lines is too slow for a big file, process lines directly
function! ProcessHaddockIndexes2(location,files)
let entryPat= '^>\([^<]*\)</'
let linkPat = '.\{-}A HREF="\([^"]*\)"'
let kindPat = '#\(.\)'
" redraw
echo 'populating g:haddock_index from haddock index files in ' a:location
for f in a:files
echo f[len(a:location):]
let isEntry = 0
let isLink = ''
let link = {}
let entry = ''
for line in readfile(f)
if line=~'CLASS="indexentry'
if (link!={}) && (entry!='')
if has_key(g:haddock_index,DeHTML(entry))
let dict = extend(g:haddock_index[DeHTML(entry)],deepcopy(link))
else
let dict = deepcopy(link)
endif
let g:haddock_index[DeHTML(entry)] = dict
let link = {}
let entry = ''
endif
let isEntry=1
continue
endif
if isEntry==1
let ml = matchlist(line,entryPat)
if ml!=[] | let [_,entry;x] = ml | let isEntry=0 | continue | endif
endif
if entry!=''
let ml = matchlist(line,linkPat)
if ml!=[] | let [_,isLink;x]=ml | continue | endif
endif
if isLink!=''
let ml = matchlist(line,entryPat)
if ml!=[]
let [_,module;x] = ml
let [_,kind;x] = matchlist(isLink,kindPat)
let last = a:location[strlen(a:location)-1]
let link[module."[".kind."]"] = a:location . (last=='/'?'':'/') . isLink
let isLink=''
continue
endif
endif
endfor
if link!={}
if has_key(g:haddock_index,DeHTML(entry))
let dict = extend(g:haddock_index[DeHTML(entry)],deepcopy(link))
else
let dict = deepcopy(link)
endif
let g:haddock_index[DeHTML(entry)] = dict
endif
endfor
endfunction
function! ProcessHaddockIndexes3(location,files)
let entryPat= '>\(.*\)$'
let linkPat = '<a href="\([^"]*\)"'
let kindPat = '#\(.\)'
" redraw
echo 'populating g:haddock_index from haddock index files in ' a:location
for f in a:files
echo f[len(a:location):]
let isLink = ''
let link = {}
let entry = ''
let lines = split(join(readfile(f,'b')),'\ze<')
for line in lines
if (line=~'class="src') || (line=~'/table')
if (link!={}) && (entry!='')
if has_key(g:haddock_index,DeHTML(entry))
let dict = extend(g:haddock_index[DeHTML(entry)],deepcopy(link))
else
let dict = deepcopy(link)
endif
let g:haddock_index[DeHTML(entry)] = dict
let link = {}
let entry = ''
endif
let ml = matchlist(line,entryPat)
if ml!=[] | let [_,entry;x] = ml | continue | endif
continue
endif
if entry!=''
let ml = matchlist(line,linkPat)
if ml!=[]
let [_,isLink;x]=ml
let ml = matchlist(line,entryPat)
if ml!=[]
let [_,module;x] = ml
let [_,kind;x] = matchlist(isLink,kindPat)
let last = a:location[strlen(a:location)-1]
let link[module."[".kind."]"] = a:location . (last=='/'?'':'/') . isLink
let isLink=''
endif
continue
endif
endif
endfor
if link!={}
if has_key(g:haddock_index,DeHTML(entry))
let dict = extend(g:haddock_index[DeHTML(entry)],deepcopy(link))
else
let dict = deepcopy(link)
endif
let g:haddock_index[DeHTML(entry)] = dict
endif
endfor
endfunction
command! ExportDocIndex call ExportDocIndex()
function! ExportDocIndex()
call HaveIndex()
let entries = []
for key in keys(g:haddock_index)
let entries += [key,string(g:haddock_index[key])]
endfor
call writefile(entries,s:haddock_indexfile)
redir end
endfunction
command! ImportDocIndex call ImportDocIndex()
function! ImportDocIndex()
if filereadable(s:haddock_indexfile)
let lines = readfile(s:haddock_indexfile)
let i=0
while i<len(lines)
let [key,dict] = [lines[i],lines[i+1]]
sandbox let g:haddock_index[key] = eval(dict)
let i+=2
endwhile
return 1
else
return 0
endif
endfunction
function! HaveIndex()
return (g:haddock_index!={} || ImportDocIndex() || DocIndex() )
endfunction
function! MkHaddockModuleIndex()
let g:haddock_moduleindex = {}
call HaveIndex()
for key in keys(g:haddock_index)
let dict = g:haddock_index[key]
for module in keys(dict)
let html = dict[module]
let html = substitute(html ,'#.*$','','')
let module = substitute(module,'\[.\]','','')
let ml = matchlist(html,'libraries/\([^\/]*\)[\/]')
if ml!=[]
let [_,package;x] = ml
let g:haddock_moduleindex[module] = {'package':package,'html':html}
endif
let ml = matchlist(html,'/\([^\/]*\)\/html/[A-Z]')
if ml!=[]
let [_,package;x] = ml
let g:haddock_moduleindex[module] = {'package':package,'html':html}
endif
endfor
endfor
endfunction
function! HaveModuleIndex()
return (g:haddock_moduleindex!={} || MkHaddockModuleIndex() )
endfunction
" decode HTML symbol encodings (are these all we need?)
function! DeHTML(entry)
let res = a:entry
let decode = { '&lt;': '<', '&gt;': '>', '&amp;': '\\&' }
for enc in keys(decode)
exe 'let res = substitute(res,"'.enc.'","'.decode[enc].'","g")'
endfor
return res
endfunction
" find haddocks for word under cursor
" also lists possible definition sites
" - needs to work for both qualified and unqualified items
" - for 'import qualified M as A', consider M.item as source of A.item
" - offer sources from both type [t] and value [v] namespaces
" - for unqualified items, list all possible sites
" - for qualified items, list imported sites only
" keep track of keys with and without namespace tags:
" the former are needed for lookup, the latter for matching against source
map <LocalLeader>? :call Haddock()<cr>
function! Haddock()
amenu ]Popup.- :echo '-'<cr>
aunmenu ]Popup
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [start,symb,qual,unqual] = namsym
let imports = haskellmode#GatherImports()
let asm = has_key(imports[1],qual) ? imports[1][qual]['modules'] : []
let name = unqual
let dict = HaddockIndexLookup(name)
if dict=={} | return | endif
" for qualified items, narrow results to possible imports that provide qualifier
let filteredKeys = filter(copy(keys(dict))
\ ,'match(asm,substitute(v:val,''\[.\]'','''',''''))!=-1')
let keys = (qual!='') ? filteredKeys : keys(dict)
if (keys==[]) && (qual!='')
echoerr qual.'.'.unqual.' not found in imports'
return 0
endif
" use 'setlocal completeopt+=menuone' if you always want to see menus before
" anything happens (I do, but many users don't..)
if len(keys)==1 && (&completeopt!~'menuone')
call DocBrowser(dict[keys[0]])
elseif has("gui_running")
for key in keys
exe 'amenu ]Popup.'.escape(key,'\.').' :call DocBrowser('''.dict[key].''')<cr>'
endfor
popup ]Popup
else
let s:choices = keys
let key = input('browse docs for '.name.' in: ','','customlist,CompleteAux')
if key!=''
call DocBrowser(dict[key])
endif
endif
endfunction
if !exists("g:haskell_search_engines")
let g:haskell_search_engines =
\ {'hoogle':'http://www.haskell.org/hoogle/?hoogle=%s'
\ ,'hayoo!':'http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=%s'
\ }
endif
map <LocalLeader>?? :let es=g:haskell_search_engines
\ \|echo "g:haskell_search_engines"
\ \|for e in keys(es)
\ \|echo e.' : '.es[e]
\ \|endfor<cr>
map <LocalLeader>?1 :call HaskellSearchEngine('hoogle')<cr>
map <LocalLeader>?2 :call HaskellSearchEngine('hayoo!')<cr>
" query one of the Haskell search engines for the thing under cursor
" - unqualified symbols need to be url-escaped
" - qualified ids need to be fed as separate qualifier and id for
" both hoogle (doesn't handle qualified symbols) and hayoo! (no qualified
" ids at all)
" - qualified ids referring to import-qualified-as qualifiers need to be
" translated to the multi-module searches over the list of original modules
function! HaskellSearchEngine(engine)
amenu ]Popup.- :echo '-'<cr>
aunmenu ]Popup
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [start,symb,qual,unqual] = namsym
let imports = haskellmode#GatherImports()
let asm = has_key(imports[1],qual) ? imports[1][qual]['modules'] : []
let unqual = haskellmode#UrlEncode(unqual)
if a:engine=='hoogle'
let name = asm!=[] ? unqual.'+'.join(map(copy(asm),'"%2B".v:val'),'+')
\ : qual!='' ? unqual.'+'.haskellmode#UrlEncode('+').qual
\ : unqual
elseif a:engine=='hayoo!'
let name = asm!=[] ? unqual.'+module:('.join(copy(asm),' OR ').')'
\ : qual!='' ? unqual.'+module:'.qual
\ : unqual
else
let name = qual=="" ? unqual : qual.".".unqual
endif
if has_key(g:haskell_search_engines,a:engine)
call DocBrowser(printf(g:haskell_search_engines[a:engine],name))
else
echoerr "unknown search engine: ".a:engine
endif
endfunction
" used to pass on choices to CompleteAux
let s:choices=[]
" if there's no gui, use commandline completion instead of :popup
" completion function CompleteAux suggests completions for a:al, wrt to s:choices
function! CompleteAux(al,cl,cp)
"echomsg '|'.a:al.'|'.a:cl.'|'.a:cp.'|'
let res = []
let l = len(a:al)-1
for r in s:choices
if l==-1 || r[0 : l]==a:al
let res += [r]
endif
endfor
return res
endfunction
" CamelCase shorthand matching:
" favour upper-case letters and module qualifier separators (.) for disambiguation
function! CamelCase(shorthand,string)
let s1 = a:shorthand
let s2 = a:string
let notFirst = 0 " don't elide before first pattern letter
while ((s1!="")&&(s2!=""))
let head1 = s1[0]
let head2 = s2[0]
let elide = notFirst && ( ((head1=~'[A-Z]') && (head2!~'[A-Z.]'))
\ ||((head1=='.') && (head2!='.')) )
if elide
let s2=s2[1:]
elseif (head1==head2)
let s1=s1[1:]
let s2=s2[1:]
else
return 0
endif
let notFirst = (head1!='.')||(head2!='.') " treat separators as new beginnings
endwhile
return (s1=="")
endfunction
" use haddock name index for insert mode completion (CTRL-X CTRL-U)
function! CompleteHaddock(findstart, base)
if a:findstart
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),-1) " insert-mode: we're 1 beyond the text
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return -1
endif
let [start,symb,qual,unqual] = namsym
return (start-1)
else " find keys matching with "a:base"
let res = []
let l = len(a:base)-1
let qual = a:base =~ '^[A-Z][a-zA-Z0-9_'']*\(\.[A-Z][a-zA-Z0-9_'']*\)*\(\.[a-zA-Z0-9_'']*\)\?$'
call HaveIndex()
for key in keys(g:haddock_index)
let keylist = map(deepcopy(keys(g:haddock_index[key])),'substitute(v:val,"\\[.\\]","","")')
if (key[0 : l]==a:base)
for m in keylist
let res += [{"word":key,"menu":m,"dup":1}]
endfor
elseif qual " this tends to be slower
for m in keylist
let word = m . '.' . key
if word[0 : l]==a:base
let res += [{"word":word,"menu":m,"dup":1}]
endif
endfor
endif
endfor
if res==[] " no prefix matches, try CamelCase shortcuts
for key in keys(g:haddock_index)
let keylist = map(deepcopy(keys(g:haddock_index[key])),'substitute(v:val,"\\[.\\]","","")')
if CamelCase(a:base,key)
for m in keylist
let res += [{"word":key,"menu":m,"dup":1}]
endfor
elseif qual " this tends to be slower
for m in keylist
let word = m . '.' . key
if CamelCase(a:base,word)
let res += [{"word":word,"menu":m,"dup":1}]
endif
endfor
endif
endfor
endif
return res
endif
endfunction
setlocal completefunc=CompleteHaddock
"
" Vim's default completeopt is menu,preview
" you probably want at least menu, or you won't see alternatives listed
" setlocal completeopt+=menu
" menuone is useful, but other haskellmode menus will try to follow your choice here in future
" setlocal completeopt+=menuone
" longest sounds useful, but doesn't seem to do what it says, and interferes with CTRL-E
" setlocal completeopt-=longest
" fully qualify an unqualified name
" TODO: - standardise commandline versions of menus
map <LocalLeader>. :call Qualify()<cr>
function! Qualify()
amenu ]Popup.- :echo '-'<cr>
aunmenu ]Popup
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [start,symb,qual,unqual] = namsym
if qual!='' " TODO: should we support re-qualification?
redraw
echo 'already qualified'
return 0
endif
let name = unqual
let line = line('.')
let prefix = (start<=1 ? '' : getline(line)[0:start-2] )
let dict = HaddockIndexLookup(name)
if dict=={} | return | endif
let keylist = map(deepcopy(keys(dict)),'substitute(v:val,"\\[.\\]","","")')
let imports = haskellmode#GatherImports()
let qualifiedImports = []
for qualifiedImport in keys(imports[1])
let c=0
for module in imports[1][qualifiedImport]['modules']
if haskellmode#ListElem(keylist,module) | let c+=1 | endif
endfor
if c>0 | let qualifiedImports=[qualifiedImport]+qualifiedImports | endif
endfor
"let asm = has_key(imports[1],qual) ? imports[1][qual]['modules'] : []
let keylist = filter(copy(keylist),'index(qualifiedImports,v:val)==-1')
if has("gui_running")
" amenu ]Popup.-imported- :
for key in qualifiedImports
let lhs=escape(prefix.name,'/.|\')
let rhs=escape(prefix.key.'.'.name,'/&|\')
exe 'amenu ]Popup.'.escape(key,'\.').' :'.line.'s/'.lhs.'/'.rhs.'/<cr>:noh<cr>'
endfor
amenu ]Popup.-not\ imported- :
for key in keylist
let lhs=escape(prefix.name,'/.|\')
let rhs=escape(prefix.key.'.'.name,'/&|\')
exe 'amenu ]Popup.'.escape(key,'\.').' :'.line.'s/'.lhs.'/'.rhs.'/<cr>:noh<cr>'
endfor
popup ]Popup
else
let s:choices = qualifiedImports+keylist
let key = input('qualify '.name.' with: ','','customlist,CompleteAux')
if key!=''
let lhs=escape(prefix.name,'/.\')
let rhs=escape(prefix.key.'.'.name,'/&\')
exe line.'s/'.lhs.'/'.rhs.'/'
noh
endif
endif
endfunction
" create (qualified) import for a (qualified) name
" TODO: refine search patterns, to avoid misinterpretation of
" oddities like import'Neither or not'module
map <LocalLeader>i :call Import(0,0)<cr>
map <LocalLeader>im :call Import(1,0)<cr>
map <LocalLeader>iq :call Import(0,1)<cr>
map <LocalLeader>iqm :call Import(1,1)<cr>
function! Import(module,qualified)
amenu ]Popup.- :echo '-'<cr>
aunmenu ]Popup
let namsym = haskellmode#GetNameSymbol(getline('.'),col('.'),0)
if namsym==[]
redraw
echo 'no name/symbol under cursor!'
return 0
endif
let [start,symb,qual,unqual] = namsym
let name = unqual
let pname = ( symb ? '('.name.')' : name )
let importlist = a:module ? '' : '('.pname.')'
let qualified = a:qualified ? 'qualified ' : ''
if qual!=''
exe 'call append(search(''\%1c\(\<import\>\|\<module\>\|{-# OPTIONS\|{-# LANGUAGE\)'',''nb''),''import '.qualified.qual.importlist.''')'
return
endif
let line = line('.')
let prefix = getline(line)[0:start-1]
let dict = HaddockIndexLookup(name)
if dict=={} | return | endif
let keylist = map(deepcopy(keys(dict)),'substitute(v:val,"\\[.\\]","","")')
if has("gui_running")
for key in keylist
" exe 'amenu ]Popup.'.escape(key,'\.').' :call append(search("\\%1c\\(import\\\\|module\\\\|{-# OPTIONS\\)","nb"),"import '.key.importlist.'")<cr>'
exe 'amenu ]Popup.'.escape(key,'\.').' :call append(search(''\%1c\(\<import\>\\|\<module\>\\|{-# OPTIONS\\|{-# LANGUAGE\)'',''nb''),''import '.qualified.key.escape(importlist,'|').''')<cr>'
endfor
popup ]Popup
else
let s:choices = keylist
let key = input('import '.name.' from: ','','customlist,CompleteAux')
if key!=''
exe 'call append(search(''\%1c\(\<import\>\|\<module\>\|{-# OPTIONS\|{-# LANGUAGE\)'',''nb''),''import '.qualified.key.importlist.''')'
endif
endif
endfunction
function! HaddockIndexLookup(name)
call HaveIndex()
if !has_key(g:haddock_index,a:name)
echoerr a:name 'not found in haddock index'
return {}
endif
return g:haddock_index[a:name]
endfunction
" rudimentary hpaste support for vim
" (using netrw for reading, wget for posting/annotating)
"
" claus reinke, last modified: 07/04/2009
"
" part of haskell plugins: http://projects.haskell.org/haskellmode-vim
" unless wget is in your PATH, you need to set g:wget
" before loading this script. windows users are out of
" luck, unless they have wget installed (such as the
" cygwin one looked for here), or adapt this script to
" whatever alternative they have at hand (perhaps using
" vim's perl/python bindings?)
if !exists("g:wget")
if executable("wget")
let g:wget = "!wget -q"
else
let g:wget = "!c:\\cygwin\\bin\\wget -q"
endif
endif
" read (recent) hpaste files
" show index in new buffer, where ,r will open current entry
" and ,p will annotate current entry with current buffer
command! HpasteIndex call HpasteIndex()
function! HpasteIndex()
new
read http://hpaste.org
%s/\_$\_.//g
%s/<tr[^>]*>//g
%s/<\/tr>/ /g
g/<\/table>/d
g/DOCTYPE/d
%s/<td>\([^<]*\)<\/td><td><a href="\/fastcgi\/hpaste\.fcgi\/view?id=\([0-9]*\)">\([^<]*\)<\/a><\/td><td>\([^<]*\)<\/td><td>\([^<]*\)<\/td><td>\([^<]*\)<\/td>/\2 [\1] "\3" \4 \5 \6/
map <buffer> ,r 0yE:noh<cr>:call HpasteEditEntry('"')<cr>
endfunction
" load an existing entry for editing
command! -nargs=1 HpasteEditEntry call HpasteEditEntry(<f-args>)
function! HpasteEditEntry(entry)
new
exe 'Nread http://hpaste.org/fastcgi/hpaste.fcgi/raw?id='.a:entry
"exe 'map <buffer> ,p :call HpasteAnnotate('''.a:entry.''')<cr>'
endfunction
" " posting temporarily disabled -- needs someone to look into new
" " hpaste.org structure
" " annotate existing entry (only to be called via ,p in HpasteIndex)
" function! HpasteAnnotate(entry)
" let nick = input("nick? ")
" let title = input("title? ")
" if nick=='' || title==''
" echo "nick or title missing. aborting annotation"
" return
" endif
" call HpastePost('annotate/'.a:entry,nick,title)
" endfunction
"
" " post new hpaste entry
" " using 'wget --post-data' and url-encoded content
" command! HpastePostNew call HpastePost('new',<args>)
" function! HpastePost(mode,nick,title,...)
" let lines = getbufline("%",1,"$")
" let pat = '\([^[:alnum:]]\)'
" let code = '\=printf("%%%02X",char2nr(submatch(1)))'
" let lines = map(lines,'substitute(v:val."\r\n",'''.pat.''','''.code.''',''g'')')
"
" let url = 'http://hpaste.org/' . a:mode
" let nick = substitute(a:nick,pat,code,'g')
" let title = substitute(a:title,pat,code,'g')
" if a:0==0
" let announce = 'false'
" else
" let announce = a:1
" endif
" let cmd = g:wget.' --post-data="content='.join(lines,'').'&nick='.nick.'&title='.title.'&announce='.announce.'" '.url
" exe escape(cmd,'%')
" endfunction
-- 7.6.3
AlternativeLayoutRule
AlternativeLayoutRuleTransitional
Arrows
BangPatterns
CApiFFI
CPP
ConstrainedClassMethods
ConstraintKinds
DataKinds
DatatypeContexts
DefaultSignatures
DeriveDataTypeable
DeriveFoldable
DeriveFunctor
DeriveGeneric
DeriveTraversable
DisambiguateRecordFields
DoAndIfThenElse
DoRec
EmptyDataDecls
ExistentialQuantification
ExplicitForAll
ExplicitNamespaces
ExtendedDefaultRules
FlexibleContexts
FlexibleInstances
ForeignFunctionInterface
FunctionalDependencies
GADTSyntax
GADTs
GHCForeignImportPrim
GeneralizedNewtypeDeriving
Haskell2010
Haskell98
ImplicitParams
ImplicitPrelude
ImpredicativeTypes
IncoherentInstances
InstanceSigs
InterruptibleFFI
KindSignatures
LambdaCase
LiberalTypeSynonyms
MagicHash
MonadComprehensions
MonoLocalBinds
MonoPatBinds
MonomorphismRestriction
MultiParamTypeClasses
MultiWayIf
NPlusKPatterns
NamedFieldPuns
NoAlternativeLayoutRule
NoAlternativeLayoutRuleTransitional
NoArrows
NoBangPatterns
NoCApiFFI
NoCPP
NoConstrainedClassMethods
NoConstraintKinds
NoDataKinds
NoDatatypeContexts
NoDefaultSignatures
NoDeriveDataTypeable
NoDeriveFoldable
NoDeriveFunctor
NoDeriveGeneric
NoDeriveTraversable
NoDisambiguateRecordFields
NoDoAndIfThenElse
NoDoRec
NoEmptyDataDecls
NoExistentialQuantification
NoExplicitForAll
NoExplicitNamespaces
NoExtendedDefaultRules
NoFlexibleContexts
NoFlexibleInstances
NoForeignFunctionInterface
NoFunctionalDependencies
NoGADTSyntax
NoGADTs
NoGHCForeignImportPrim
NoGeneralizedNewtypeDeriving
NoImplicitParams
NoImplicitPrelude
NoImpredicativeTypes
NoIncoherentInstances
NoInstanceSigs
NoInterruptibleFFI
NoKindSignatures
NoLambdaCase
NoLiberalTypeSynonyms
NoMagicHash
NoMonadComprehensions
NoMonoLocalBinds
NoMonoPatBinds
NoMonomorphismRestriction
NoMultiParamTypeClasses
NoMultiWayIf
NoNPlusKPatterns
NoNamedFieldPuns
NoNondecreasingIndentation
NoOverlappingInstances
NoOverloadedStrings
NoPackageImports
NoParallelArrays
NoParallelListComp
NoPatternGuards
NoPatternSignatures
NoPolyKinds
NoPolymorphicComponents
NoPostfixOperators
NoQuasiQuotes
NoRank2Types
NoRankNTypes
NoRebindableSyntax
NoRecordPuns
NoRecordWildCards
NoRecursiveDo
NoRelaxedLayout
NoRelaxedPolyRec
NoScopedTypeVariables
NoStandaloneDeriving
NoTemplateHaskell
NoTraditionalRecordSyntax
NoTransformListComp
NoTupleSections
NoTypeFamilies
NoTypeOperators
NoTypeSynonymInstances
NoUnboxedTuples
NoUndecidableInstances
NoUnicodeSyntax
NoUnliftedFFITypes
NoViewPatterns
NondecreasingIndentation
OverlappingInstances
OverloadedStrings
PackageImports
ParallelArrays
ParallelListComp
PatternGuards
PatternSignatures
PolyKinds
PolymorphicComponents
PostfixOperators
QuasiQuotes
Rank2Types
RankNTypes
RebindableSyntax
RecordPuns
RecordWildCards
RecursiveDo
RelaxedLayout
RelaxedPolyRec
Safe
ScopedTypeVariables
StandaloneDeriving
TemplateHaskell
TraditionalRecordSyntax
TransformListComp
Trustworthy
TupleSections
TypeFamilies
TypeOperators
TypeSynonymInstances
UnboxedTuples
UndecidableInstances
UnicodeSyntax
UnliftedFFITypes
Unsafe
ViewPatterns
--
-fimplicit-import-qualified
" cecutil.vim : save/restore window position
" save/restore mark position
" save/restore selected user maps
" Author: Charles E. Campbell, Jr.
" Version: 16
" Date: Feb 12, 2007
"
" Saving Restoring Destroying Marks: {{{1
" call SaveMark(markname) let savemark= SaveMark(markname)
" call RestoreMark(markname) call RestoreMark(savemark)
" call DestroyMark(markname)
" commands: SM RM DM
"
" Saving Restoring Destroying Window Position: {{{1
" call SaveWinPosn() let winposn= SaveWinPosn()
" call RestoreWinPosn() call RestoreWinPosn(winposn)
" \swp : save current window/buffer's position
" \rwp : restore current window/buffer's previous position
" commands: SWP RWP
"
" Saving And Restoring User Maps: {{{1
" call SaveUserMaps(mapmode,maplead,mapchx,suffix)
" call RestoreUserMaps(suffix)
"
" GetLatestVimScripts: 1066 1 :AutoInstall: cecutil.vim
"
" You believe that God is one. You do well. The demons also {{{1
" believe, and shudder. But do you want to know, vain man, that
" faith apart from works is dead? (James 2:19,20 WEB)
" Load Once: {{{1
if &cp || exists("g:loaded_cecutil")
finish
endif
let g:loaded_cecutil = "v16"
let s:keepcpo = &cpo
set cpo&vim
"DechoVarOn
" -----------------------
" Public Interface: {{{1
" -----------------------
" Map Interface: {{{2
if !hasmapto('<Plug>SaveWinPosn')
map <unique> <Leader>swp <Plug>SaveWinPosn
endif
if !hasmapto('<Plug>RestoreWinPosn')
map <unique> <Leader>rwp <Plug>RestoreWinPosn
endif
nmap <silent> <Plug>SaveWinPosn :call SaveWinPosn()<CR>
nmap <silent> <Plug>RestoreWinPosn :call RestoreWinPosn()<CR>
" Command Interface: {{{2
com! -bar -nargs=0 SWP call SaveWinPosn()
com! -bar -nargs=0 RWP call RestoreWinPosn()
com! -bar -nargs=1 SM call SaveMark(<q-args>)
com! -bar -nargs=1 RM call RestoreMark(<q-args>)
com! -bar -nargs=1 DM call DestroyMark(<q-args>)
if v:version < 630
let s:modifier= "sil "
else
let s:modifier= "sil keepj "
endif
" ---------------------------------------------------------------------
" SaveWinPosn: {{{1
" let winposn= SaveWinPosn() will save window position in winposn variable
" call SaveWinPosn() will save window position in b:cecutil_winposn{b:cecutil_iwinposn}
" let winposn= SaveWinPosn(0) will *only* save window position in winposn variable (no stacking done)
fun! SaveWinPosn(...)
" call Dfunc("SaveWinPosn() a:0=".a:0)
if line(".") == 1 && getline(1) == ""
" call Dfunc("SaveWinPosn : empty buffer")
return ""
endif
let so_keep = &so
let siso_keep = &siso
let ss_keep = &ss
set so=0 siso=0 ss=0
let swline = line(".")
let swcol = col(".")
let swwline = winline() - 1
let swwcol = virtcol(".") - wincol()
let savedposn = "call GoWinbufnr(".winbufnr(0).")|silent ".swline
let savedposn = savedposn."|".s:modifier."norm! 0z\<cr>"
if swwline > 0
let savedposn= savedposn.":".s:modifier."norm! ".swwline."\<c-y>\<cr>"
endif
if swwcol > 0
let savedposn= savedposn.":".s:modifier."norm! 0".swwcol."zl\<cr>"
endif
let savedposn = savedposn.":".s:modifier."call cursor(".swline.",".swcol.")\<cr>"
" save window position in
" b:cecutil_winposn_{iwinposn} (stack)
" only when SaveWinPosn() is used
if a:0 == 0
if !exists("b:cecutil_iwinposn")
let b:cecutil_iwinposn= 1
else
let b:cecutil_iwinposn= b:cecutil_iwinposn + 1
endif
" call Decho("saving posn to SWP stack")
let b:cecutil_winposn{b:cecutil_iwinposn}= savedposn
endif
let &so = so_keep
let &siso = siso_keep
let &ss = ss_keep
" if exists("b:cecutil_iwinposn") " Decho
" call Decho("b:cecutil_winpos{".b:cecutil_iwinposn."}[".b:cecutil_winposn{b:cecutil_iwinposn}."]")
" else " Decho
" call Decho("b:cecutil_iwinposn doesn't exist")
" endif " Decho
" call Dret("SaveWinPosn [".savedposn."]")
return savedposn
endfun
" ---------------------------------------------------------------------
" RestoreWinPosn: {{{1
fun! RestoreWinPosn(...)
" call Dfunc("RestoreWinPosn() a:0=".a:0)
" call Decho("getline(1)<".getline(1).">")
" call Decho("line(.)=".line("."))
if line(".") == 1 && getline(1) == ""
" call Dfunc("RestoreWinPosn : empty buffer")
return ""
endif
let so_keep = &so
let siso_keep = &siso
let ss_keep = &ss
set so=0 siso=0 ss=0
if a:0 == 0 || a:1 == ""
" use saved window position in b:cecutil_winposn{b:cecutil_iwinposn} if it exists
if exists("b:cecutil_iwinposn") && exists("b:cecutil_winposn{b:cecutil_iwinposn}")
" call Decho("using stack b:cecutil_winposn{".b:cecutil_iwinposn."}<".b:cecutil_winposn{b:cecutil_iwinposn}.">")
try
exe "silent! ".b:cecutil_winposn{b:cecutil_iwinposn}
catch /^Vim\%((\a\+)\)\=:E749/
" ignore empty buffer error messages
endtry
" normally drop top-of-stack by one
" but while new top-of-stack doesn't exist
" drop top-of-stack index by one again
if b:cecutil_iwinposn >= 1
unlet b:cecutil_winposn{b:cecutil_iwinposn}
let b:cecutil_iwinposn= b:cecutil_iwinposn - 1
while b:cecutil_iwinposn >= 1 && !exists("b:cecutil_winposn{b:cecutil_iwinposn}")
let b:cecutil_iwinposn= b:cecutil_iwinposn - 1
endwhile
if b:cecutil_iwinposn < 1
unlet b:cecutil_iwinposn
endif
endif
else
echohl WarningMsg
echomsg "***warning*** need to SaveWinPosn first!"
echohl None
endif
else " handle input argument
" call Decho("using input a:1<".a:1.">")
" use window position passed to this function
exe "silent ".a:1
" remove a:1 pattern from b:cecutil_winposn{b:cecutil_iwinposn} stack
if exists("b:cecutil_iwinposn")
let jwinposn= b:cecutil_iwinposn
while jwinposn >= 1 " search for a:1 in iwinposn..1
if exists("b:cecutil_winposn{jwinposn}") " if it exists
if a:1 == b:cecutil_winposn{jwinposn} " and the pattern matches
unlet b:cecutil_winposn{jwinposn} " unlet it
if jwinposn == b:cecutil_iwinposn " if at top-of-stack
let b:cecutil_iwinposn= b:cecutil_iwinposn - 1 " drop stacktop by one
endif
endif
endif
let jwinposn= jwinposn - 1
endwhile
endif
endif
" seems to be something odd: vertical motions after RWP
" cause jump to first column. Following fixes that
if wincol() > 1
silent norm! hl
elseif virtcol(".") < virtcol("$")
silent norm! lh
endif
let &so = so_keep
let &siso = siso_keep
let &ss = ss_keep
" call Dret("RestoreWinPosn")
endfun
" ---------------------------------------------------------------------
" GoWinbufnr: go to window holding given buffer (by number) {{{1
" Prefers current window; if its buffer number doesn't match,
" then will try from topleft to bottom right
fun! GoWinbufnr(bufnum)
" call Dfunc("GoWinbufnr(".a:bufnum.")")
if winbufnr(0) == a:bufnum
" call Dret("GoWinbufnr : winbufnr(0)==a:bufnum")
return
endif
winc t
let first=1
while winbufnr(0) != a:bufnum && (first || winnr() != 1)
winc w
let first= 0
endwhile
" call Dret("GoWinbufnr")
endfun
" ---------------------------------------------------------------------
" SaveMark: sets up a string saving a mark position. {{{1
" For example, SaveMark("a")
" Also sets up a global variable, g:savemark_{markname}
fun! SaveMark(markname)
" call Dfunc("SaveMark(markname<".a:markname.">)")
let markname= a:markname
if strpart(markname,0,1) !~ '\a'
let markname= strpart(markname,1,1)
endif
" call Decho("markname=".markname)
let lzkeep = &lz
set lz
if 1 <= line("'".markname) && line("'".markname) <= line("$")
let winposn = SaveWinPosn(0)
exe s:modifier."norm! `".markname
let savemark = SaveWinPosn(0)
let g:savemark_{markname} = savemark
let savemark = markname.savemark
call RestoreWinPosn(winposn)
else
let g:savemark_{markname} = ""
let savemark = ""
endif
let &lz= lzkeep
" call Dret("SaveMark : savemark<".savemark.">")
return savemark
endfun
" ---------------------------------------------------------------------
" RestoreMark: {{{1
" call RestoreMark("a") -or- call RestoreMark(savemark)
fun! RestoreMark(markname)
" call Dfunc("RestoreMark(markname<".a:markname.">)")
if strlen(a:markname) <= 0
" call Dret("RestoreMark : no such mark")
return
endif
let markname= strpart(a:markname,0,1)
if markname !~ '\a'
" handles 'a -> a styles
let markname= strpart(a:markname,1,1)
endif
" call Decho("markname=".markname." strlen(a:markname)=".strlen(a:markname))
let lzkeep = &lz
set lz
let winposn = SaveWinPosn(0)
if strlen(a:markname) <= 2
if exists("g:savemark_{markname}") && strlen(g:savemark_{markname}) != 0
" use global variable g:savemark_{markname}
" call Decho("use savemark list")
call RestoreWinPosn(g:savemark_{markname})
exe "norm! m".markname
endif
else
" markname is a savemark command (string)
" call Decho("use savemark command")
let markcmd= strpart(a:markname,1)
call RestoreWinPosn(markcmd)
exe "norm! m".markname
endif
call RestoreWinPosn(winposn)
let &lz = lzkeep
" call Dret("RestoreMark")
endfun
" ---------------------------------------------------------------------
" DestroyMark: {{{1
" call DestroyMark("a") -- destroys mark
fun! DestroyMark(markname)
" call Dfunc("DestroyMark(markname<".a:markname.">)")
" save options and set to standard values
let reportkeep= &report
let lzkeep = &lz
set lz report=10000
let markname= strpart(a:markname,0,1)
if markname !~ '\a'
" handles 'a -> a styles
let markname= strpart(a:markname,1,1)
endif
" call Decho("markname=".markname)
let curmod = &mod
let winposn = SaveWinPosn(0)
1
let lineone = getline(".")
exe "k".markname
d
put! =lineone
let &mod = curmod
call RestoreWinPosn(winposn)
" restore options to user settings
let &report = reportkeep
let &lz = lzkeep
" call Dret("DestroyMark")
endfun
" ---------------------------------------------------------------------
" ListWinPosn:
"fun! ListWinPosn() " Decho
" if !exists("b:cecutil_iwinposn") || b:cecutil_iwinposn == 0 " Decho
" call Decho("nothing on SWP stack") " Decho
" else " Decho
" let jwinposn= b:cecutil_iwinposn " Decho
" while jwinposn >= 1 " Decho
" if exists("b:cecutil_winposn{jwinposn}") " Decho
" call Decho("winposn{".jwinposn."}<".b:cecutil_winposn{jwinposn}.">") " Decho
" else " Decho
" call Decho("winposn{".jwinposn."} -- doesn't exist") " Decho
" endif " Decho
" let jwinposn= jwinposn - 1 " Decho
" endwhile " Decho
" endif " Decho
"endfun " Decho
"com! -nargs=0 LWP call ListWinPosn() " Decho
" ---------------------------------------------------------------------
" SaveUserMaps: this function sets up a script-variable (s:restoremap) {{{1
" which can be used to restore user maps later with
" call RestoreUserMaps()
"
" mapmode - see :help maparg for its list
" ex. "n" = Normal
" If the first letter is u, then unmapping will be done
" ex. "un" = Normal + unmapping
" maplead - see mapchx
" mapchx - "<something>" handled as a single map item.
" ex. "<left>"
" - "string" a string of single letters which are actually
" multiple two-letter maps (using the maplead:
" maplead . each_character_in_string)
" ex. maplead="\" and mapchx="abc" saves user mappings for
" \a, \b, and \c
" Of course, if maplead is "", then for mapchx="abc",
" mappings for a, b, and c are saved.
" - :something handled as a single map item, w/o the ":"
" ex. mapchx= ":abc" will save a mapping for "abc"
" suffix - a string unique to your plugin
" ex. suffix= "DrawIt"
fun! SaveUserMaps(mapmode,maplead,mapchx,suffix)
" call Dfunc("SaveUserMaps(mapmode<".a:mapmode."> maplead<".a:maplead."> mapchx<".a:mapchx."> suffix<".a:suffix.">)")
if !exists("s:restoremap_{a:suffix}")
" initialize restoremap_suffix to null string
let s:restoremap_{a:suffix}= ""
endif
" set up dounmap: if 1, then save and unmap (a:mapmode leads with a "u")
" if 0, save only
if a:mapmode =~ '^u'
let dounmap= 1
let mapmode= strpart(a:mapmode,1)
else
let dounmap= 0
let mapmode= a:mapmode
endif
" save single map :...something...
if strpart(a:mapchx,0,1) == ':'
let amap= strpart(a:mapchx,1)
if amap == "|" || amap == "\<c-v>"
let amap= "\<c-v>".amap
endif
let amap = a:maplead.amap
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|:silent! ".mapmode."unmap ".amap
if maparg(amap,mapmode) != ""
let maprhs = substitute(maparg(amap,mapmode),'|','<bar>','ge')
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|:".mapmode."map ".amap." ".maprhs
endif
if dounmap
exe "silent! ".mapmode."unmap ".amap
endif
" save single map <something>
elseif strpart(a:mapchx,0,1) == '<'
let amap = a:mapchx
if amap == "|" || amap == "\<c-v>"
let amap= "\<c-v>".amap
endif
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|silent! ".mapmode."unmap ".amap
if maparg(a:mapchx,mapmode) != ""
let maprhs = substitute(maparg(amap,mapmode),'|','<bar>','ge')
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|".mapmode."map ".amap." ".maprhs
endif
if dounmap
exe "silent! ".mapmode."unmap ".amap
endif
" save multiple maps
else
let i= 1
while i <= strlen(a:mapchx)
let amap= a:maplead.strpart(a:mapchx,i-1,1)
if amap == "|" || amap == "\<c-v>"
let amap= "\<c-v>".amap
endif
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|silent! ".mapmode."unmap ".amap
if maparg(amap,mapmode) != ""
let maprhs = substitute(maparg(amap,mapmode),'|','<bar>','ge')
let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|".mapmode."map ".amap." ".maprhs
endif
if dounmap
exe "silent! ".mapmode."unmap ".amap
endif
let i= i + 1
endwhile
endif
" call Dret("SaveUserMaps : restoremap_".a:suffix.": ".s:restoremap_{a:suffix})
endfun
" ---------------------------------------------------------------------
" RestoreUserMaps: {{{1
" Used to restore user maps saved by SaveUserMaps()
fun! RestoreUserMaps(suffix)
" call Dfunc("RestoreUserMaps(suffix<".a:suffix.">)")
if exists("s:restoremap_{a:suffix}")
let s:restoremap_{a:suffix}= substitute(s:restoremap_{a:suffix},'|\s*$','','e')
if s:restoremap_{a:suffix} != ""
" call Decho("exe ".s:restoremap_{a:suffix})
exe "silent! ".s:restoremap_{a:suffix}
endif
unlet s:restoremap_{a:suffix}
endif
" call Dret("RestoreUserMaps")
endfun
" ---------------------------------------------------------------------
" Restore: {{{1
let &cpo= s:keepcpo
unlet s:keepcpo
" ---------------------------------------------------------------------
" Modelines: {{{1
" vim: ts=4 fdm=marker
" debPlugin.vim -- a Vim plugin for browsing debian packages
" copyright (C) 2007, arno renevier <arenevier@fdn.fr>
" Distributed under the GNU General Public License (version 2 or above)
" Last Change: 2007 December 07
"
" This file only sets the autocommands. Functions are in autoload/deb.vim.
"
" Latest version of that file can be found at
" http://www.fdn.fr/~arenevier/vim/plugin/debPlugin.vim
" It should also be available at
" http://www.vim.org/scripts/script.php?script_id=1970
"
if &cp || exists("g:loaded_debPlugin") || !has("unix") || v:version < 700
finish
endif
let g:loaded_debPlugin = 1
autocmd BufReadCmd *.deb call deb#browse(expand("<amatch>"))
"=============================================================================
" File: eregex.vim and eregex_e.vim
" Author: AKUTSU toshiyuki <locrian@mbd.ocn.ne.jp>
" Maintainer: Kao, Wei-Ko <othree@gmail.com>
" Requirements: Vim version 6.1 and later.
" Description: eregex.vim is a converter from extended regex to vim regex
" eregex_e.vim is an evaluater for command of eregex.vim
" The meaning of extended regex is pseudo ruby/perl-style regex.
" Previous $Id: eregex.vim,v 2.56 2010-10-18 11:59:41+08 ta Exp $
" $Id: eregex.vim,v 2.60 2013-02-22 14:38:41+08 ta Exp $
" Note: English isn't my mother tongue.
"=============================================================================
" Principle:
" eregex.vim adopts the way of extended regex about "alternation",
" "repetition" and "grouping".
" As for those things, the way of Vim regex is adopted.
" You can use '\_^', '\zs', '\<', '\%<23c', '\_u', etc in extended regex.
"=============================================================================
" Functions:
"
" E2v({extended_regex} [, {iISCDMm}])
" The result is a String, which is vim style regex.
"
" :let vimregex = E2v('(?<=abc),\d+,(?=xzy)','i')
" :echo vimregex
" \c\%(abc\)\@<=,\d\+,\%(xzy\)\@=
"
" E2v('','V')
" The result is a Number, which is eregex.vim version.
"
" :echo E2v('','V')
" 238
"
" E2v({replacement} ,{R1,R2,R3})
" The result is a String, which is used for the "to" part of :S/from/to/
"
" E2v('\r,\n,\&,&,\~,~', 'R1') => \n,\r,\&,&,\~,~
" E2v('\r,\n,\&,&,\~,~', 'R2') => \r,\n,&,\&,~,\~
" E2v('\r,\n,\&,&,\~,~', 'R3') => \n,\r,&,\&,~,\~
"
"=============================================================================
" Commands:
"
" :[range]E2v [iISCDMm]
" Extended regex To Vim regex.
" Replace each extended-regex in [range] with vim-style-regex.
"
" :M/eregex/[offset][iISCDMm]
" Match.
" :M/<span class="foo">.*?<\/span>/Im
" => /\C<span class="foo">\_.\{-}<\/span>
"
" :[range]S/eregex/replacement/[&cegpriISCDMm]
" Substitute.
" :'<,'>S/(\d{1,3})(?=(\d\d\d)+($|\D))/\1,/g
" => :'<,'>s/\(\d\{1,3}\)\%(\(\d\d\d\)\+\($\|\D\)\)\@=/\1,/g
"
" :[range]G/eregex/command
" Global.
" :G/<<-(["'])?EOD\1/,/^\s*EOD\>/:left 8
" => :g/<<-\(["']\)\=EOD\1/,/^\s*EOD\>/:left 8
"
" :[range]V/eregex/command
" Vglobal
"
"=============================================================================
" Tips And Configuration:
"
" Put the following commands in your ~/.vimrc to replace normal / with :M/
"
" nnoremap / :M/
" nnoremap ,/ /
"
" v238, v243
" If you put 'let eregex_replacement=3' in your ~/.vimrc,
"
" :S/pattern/\r,\n,\&,&,\~,~/ will be converted to :s/pattern/\n,\r,&,\&,~,\~/
"
" +--------------------+-----------------------------+
" | eregex_replacement | :S/pattern/\n,\r,&,\&,~,\~/ |
" +--------------------+-----------------------------+
" | 0 | :s/pattern/\n,\r,&,\&,~,\~/ |
" | 1 | :s/pattern/\r,\n,&,\&,~,\~/ |
" | 2 | :s/pattern/\n,\r,\&,&,\~,~/ |
" | 3 | :s/pattern/\r,\n,\&,&,\~,~/ |
" +--------------------+-----------------------------+
" See :h sub-replace-special
"
"=============================================================================
" Options:
" Note: "^L" is "\x0c".
"
" "i" ignorecase
" "I" noignorecase
" "S" convert "\s" to "[ \t\r\n^L]" and also convert "\S" to "[^ \t\r^L]"
" Mnemonic: extended spaces
" "C" convert "[^az]" to "\_[^az]" and also convert "\W" to "\_W".
" Mnemonic: extended complement
" Vim's "[^az]" matches anything but "a", "z", and a newline.
" "D" convert "." to "\_."
" Mnemonic: extended dot
" Normally, "." matches any character except a newline.
" "M" partial multiline; do both "S" and "C".
" In other words, It is not "multiline" in ruby way.
" "m" full multiline; do all the above conversions "S", "C" and "D".
" In other words, It is just "multiline" in ruby way.
"
"+-----+----------------------------------------------+--------------------+
"| Num | eregex.vim => vim regex | ruby regex |
"+-----+----------------------------------------------+--------------------+
"| (1) | :M/a\s[^az].z/ => /a\s[^az].z/ | /a[ \t][^az\n].z/ |
"+-----+----------------------------------------------+--------------------+
"| | :M/a\s[^az].z/S => /a[ \t\r\n^L][^az].z/ | /a\s[^az\n].z/ |
"| | :M/a\s[^az].z/C => /a\s\_[^az].z/ | /a[ \t][^az].z/ |
"| | :M/a\s[^az].z/D => /a\s[^az]\_.z/ | /a[ \t][^az\n].z/m |
"+-----+----------------------------------------------+--------------------+
"| (2) | :M/a\s[^az].z/M => /a[ \t\r\n^L]\_[^az].z/ | /a\s[^az].z/ |
"| (3) | :M/a\s[^az].z/m => /a[ \t\r\n^L]\_[^az]\_.z/ | /a\s[^az].z/m |
"+-----+----------------------------------------------+--------------------+
"
" Note:
" As for "\s", "[^az]" and ".", "M" and "m" options make
" eregex.vim-regexen compatible with ruby/perl-style-regexen.
" Note:
" Vim's "[^az]" doesn't match a newline.
" Contrary to the intention, "[^az\n]" matches a newline.
" The countermeasure is to convert "[^\s]" to "[^ \t\r^L]" with
" multiline.
"
"=============================================================================
" pseudo ruby/perl-style regexen.
"
" available extended regexen:
" alternation:
" "a|b"
" repetition:
" "a+", "a*", "a?", "a+?", "a*?", "a??,"
" "a{3,5}", "a{3,}", "a{,5}", "a{3,5}?", "a{3,}?", "a{,5}?"
" grouping:
" "(foo)", "(?:foo)", "(?=foo)", "(?!foo)", "(?<=foo)",
" "(?<!foo)", "(?>foo)"
" modifiers:
" "(?I)", "(?i)", "(?M)", "(?m)", "(?#comment)"
"
" Note:
" The use of "\M" or "\m" is preferable to the use of "(?M)" or "(?m)".
" "(?M)" and "(?m)" can't expand "\s" in brackets to " \t\r\n^L".
"
" not available extended regexen:
" "\A", "\b", "\B", "\G", "\Z", "\z",
" "(?i:a)", "(?-i)", "(?m:.)",
" There are no equivalents in vim-style regexen.
"
" special atoms:
" "\C" noignorecase
" "\c" ignorecase
" "\M" partial multiline
" "\m" full multiline
"
" For example:
" :M/a\s[^az].z/M => /a[ \t\r\n^L]\_[^az].z/
" :M/a\s[^az].z\M/ => /a[ \t\r\n^L]\_[^az].z/
" :M/a\s[^az].z/m => /a[ \t\r\n^L]\_[^az]\_.z/
" :M/a\s[^az].z\m/ => /a[ \t\r\n^L]\_[^az]\_.z/
" The order of priority:
" [A] /IiMm, [B] \C, \c, \M, \m, [C] (?I), (?i), (?M), (?m)
"
" many other vim-style regexen available:
" "\d", "\D", "\w", "\W", "\s", "\S", "\a", "\A",
" "\u", "\U", "\b"
" "\<", "\>"
" "\zs", "\ze"
" "\_[a-z]", "\%[abc]", "[[:alpha:]]"
" "\_.", "\_^", "\_$"
" "\%23l", "\%23c", "\%23v", "\%#"
" and so on. See :h /ordinary-atom
"
" misc:
" Convert "\xnn" to char except "\x00", "\x0a" and "\x08".
" "\x41\x42\x43" => "ABC"
" "\x2a\x5b\x5c" => "\*\[\\"
" Expand atoms in brackets.
" "[#$\w]" => "[#$0-9A-Za-z_]"
"
" "\f" in brackets is converted to "\x0c".
" but "\f" out of brackets is a class of filename characters.
"
" eregex.vim expansion of atoms and its meaning.
" +-------+----------------------+----------------------+
" | atom | out of brackets | in brackets |
" +-------+----------------------+----------------------+
" | \a | alphabetic char | alphabetic char |
" | \b | \x08 | \x08 |
" | \e | \x1b | \x1b |
" | \f | filename char | \x0c |
" | \n | \x0a | \x0a |
" | \r | \x0d | \x0d |
" | \s | [ \t] or [ \t\r\n\f] | " \t" or " \t\r\n\f" |
" | \t | \x09 | \x09 |
" | \v | \x0b | \x0b |
" | \xnn | hex nn | hex nn |
" +-------+----------------------+----------------------+
"
"=============================================================================
if version < 601 | finish | endif
if exists("loaded_eregex")
finish
endif
let loaded_eregex=1
"=============================================================================
"Commands And Mappings:
command! -nargs=? -range E2v :<line1>,<line2>call <SID>ExtendedRegex2VimRegexLineWise(<q-args>)
command! -nargs=? -count=1 M :let s:eregex_tmp_hlsearch = &hlsearch | let v:searchforward = <SID>Ematch(<count>, <q-args>) | if s:eregex_tmp_hlsearch == 1 | set hlsearch | endif
"command! -nargs=? -range S :<line1>,<line2>call <SID>Esubstitute(<q-args>)
command! -nargs=? -range S :<line1>,<line2>call <SID>Esubstitute(<q-args>) <Bar> :noh
command! -nargs=? -range=% -bang G :<line1>,<line2>call <SID>Eglobal(<q-bang>, <q-args>)
command! -nargs=? -range=% V :<line1>,<line2>call <SID>Evglobal(<q-args>)
"=============================================================================
"Script Variables:
let s:eglobal_working=0
"--------------------
let s:ch_with_backslash=0
let s:ch_posix_charclass=1
let s:ch_brackets=2
let s:ch_braces=3
let s:ch_parentheses_option=4
let s:ch_parentheses=5
let s:re_factor{0}='\\\%([^x_]\|x\x\{0,2}\|_[.$^]\=\)'
let s:re_factor{1}= '\[:\%(alnum\|alpha\|blank\|cntrl\|digit\|graph\|lower\|print\|punct\|' .
\ 'space\|upper\|xdigit\|return\|tab\|escape\|backspace\):\]'
let s:re_factor{2}='\[\%([^^][^]]*\|\^.[^]]*\)\]'
let s:re_factor{3}='{[0-9,]\+}?\='
"v141
"let s:re_factor{4}='(?[iISCDMm]\{1,7})'
let s:re_factor{4}='(?[iImM]\{1,2})'
let s:re_factor{5}='(\(?:\|?=\|?!\|?<=\|?<!\|?>\|?[-#ixm]\)\=[^()]*)'
let s:re_factor_size=6
"--------------------
let s:mark_left="\<Esc>" . strftime("%X") . ":" . strftime("%d") . "\<C-f>"
let s:mark_right="\<C-l>" . strftime("%X") . ":" . strftime("%d") . "\<Esc>"
let s:stack_size=0
let s:invert=0
let s:multiline=0
let s:ignorecase=0
"v220
let s:re_unescaped='\%(\\\)\@<!\%(\\\\\)*\zs'
let s:re_escaped='\%(\\\)\@<!\%(\\\\\)*\zs\\'
let s:bakregex=''
let s:mark_complements=s:mark_left . 'cOmPLemEnTs' . s:mark_right
"v141, 210
let s:extended_spaces=0
let s:extended_complements=0
let s:extended_dots=0
let s:str_modifiers='iISCDMm'
let s:meta_chars='$*.[\]^~'
"v217
"Why does "[^abc\n]" match a newline ???
let s:countermeasure=1
":M/(?:v21[5-9]|why)/i
"v238
let s:eregex_replacement=0
if exists('eregex_replacement')
let s:eregex_replacement=eregex_replacement
endif
"v240
let s:tmp=matchstr("$Revision: 2.60 $", '[0-9.]\+')
let s:maj=matchstr(s:tmp, '\d\+') * 100
let s:min=matchstr(s:tmp, '\.\zs\d\+') + 0
let s:version = s:maj + s:min
unlet s:tmp s:maj s:min
"v260
if !exists('g:eregex_forward_delim')
let g:eregex_forward_delim = '/'
endif
if !exists('g:eregex_backward_delim')
let g:eregex_backward_delim = '?'
endif
let s:enable = 0
function! eregex#toggle(...)
let silent = 0
if exists('a:1') && a:1
let silent = 1
endif
if s:enable == 0
exec 'nnoremap <expr> '.g:eregex_forward_delim.' ":<C-U>".v:count1."M/"'
exec 'nnoremap <expr> '.g:eregex_backward_delim.' ":<C-U>".v:count1."M?"'
if silent != 1
echo "eregx.vim key mapping enabled"
endif
else
exec 'nunmap '.g:eregex_forward_delim
exec 'nunmap '.g:eregex_backward_delim
if silent != 1
echo "eregx.vim key mapping disabled"
endif
endif
let s:enable = 1 - s:enable
endfun
if !(exists('g:eregex_default_enable') && g:eregex_default_enable == 0)
call eregex#toggle(1)
endif
"=============================================================================
"Functions:
function! s:Push(fct, kind)
let fct = a:fct
if (a:kind==s:ch_with_backslash) && (fct =~# '^\\x\x\{1,2}$')
" \x41
exec 'let code=0 + 0x' . matchstr(fct, '\x\{1,2}$')
if code!=0x0a && code!=0 && code!=0x08
let fct = nr2char(code)
"v141
if stridx(s:meta_chars, fct)!=-1
let fct = "\\" . fct
endif
endif
elseif a:kind == s:ch_with_backslash
" \. \_x
let chr = fct[1]
if chr =~# '[+?{}|()=]'
let fct = chr
elseif chr =~# '[Vv]'
if chr ==# 'v'
let fct=nr2char(0x0b)
else
let fct='V'
endif
"[IiMm]
endif
elseif a:kind == s:ch_posix_charclass
" [:alpha:] pass through
elseif a:kind == s:ch_brackets
"[ ]
let fct = s:ExpandAtomsInBrackets(fct)
elseif a:kind == s:ch_braces
"{ }
let fct = '\' . fct
" minimal match, not greedy
if fct =~# '?$'
if fct =~# '\d\+,\d\+'
let fct = substitute(fct, '{\(\d\+\),\(\d\+\)}?', '{-\1,\2}', '')
elseif fct =~# ',}'
let fct = substitute(fct, '{\(\d\+\),}?', '{-\1,}', '')
elseif fct =~# '{,'
let fct = substitute(fct, '{,\(\d\+\)}?', '{-,\1}', '')
else
let fct = strpart(fct, 1)
endif
endif
elseif a:kind==s:ch_parentheses_option
"( )
"v223
call s:SetModifiers(fct)
let fct = ''
elseif (a:kind==s:ch_parentheses) && (fct =~# '(?[-#ixm]')
"( )
if fct =~# '(?-\=[ixm]\{1,3})' || fct =~# '(?#'
let fct = ''
else
let fct = substitute(fct, '(?-\=[ixm]\{1,3}:\([^()]*\))', '\1', "")
let fct = s:ReplaceRemainFactorWithVimRegexFactor(fct)
endif
elseif a:kind==s:ch_parentheses
"( )
let kakko = matchstr(fct, '(\(?:\|?=\|?!\|?<=\|?<!\|?>\)\=')
let fct = substitute(fct, '(\(?:\|?=\|?!\|?<=\|?<!\|?>\)\=', "", "")
let fct = strpart(fct, 0, strlen(fct)-1)
let fct = s:ReplaceRemainFactorWithVimRegexFactor(fct)
if kakko ==# '('
let fct = '\(' . fct . '\)'
elseif kakko ==# '(?:'
let fct = '\%(' . fct . '\)'
elseif kakko ==# '(?='
let fct = '\%(' . fct . '\)\@='
elseif kakko ==# '(?!'
let fct = '\%(' . fct . '\)\@!'
elseif kakko ==# '(?<='
let fct = '\%(' . fct . '\)\@<='
elseif kakko ==# '(?<!'
let fct = '\%(' . fct . '\)\@<!'
elseif kakko ==# '(?>'
let fct = '\%(' . fct . '\)\@>'
else
let fct = ":BUG:"
endif
endif
let s:stack{s:stack_size} = fct
let s:stack_size = s:stack_size + 1
endfunction
"end s:Push()
"-----------------------------------------------------------------------------
function! s:ExpandAtomsInBrackets(bracket)
let bracket = a:bracket
let re_mark = s:mark_left . '\d\+' . s:mark_right
let re_snum = s:mark_left . '\(\d\+\)' . s:mark_right
"v120
let has_newline=0
"v216,v249
let complement=(bracket =~# '^\[^')
let searchstart = 0
let mtop = match(bracket, re_mark, searchstart)
while mtop >= 0
let mstr = matchstr(bracket, re_mark, searchstart)
let snum = substitute(mstr, re_snum, '\1', "") + 0
"v222
let fct = s:stack{snum}
"exclude, \e=0x1b, \b=0x08, \r=0x0d, \t=0x09
if fct =~# '^\\[adfhlosuwx]$'
let chr = fct[1]
if chr ==# 'a'
let fct='A-Za-z'
elseif chr ==# 'd'
let fct='0-9'
elseif chr ==# 'f'
"let fct=nr2char(0x0c)
let fct="\x0c"
elseif chr ==# 'h'
let fct='A-Za-z_'
elseif chr ==# 'l'
let fct='a-z'
elseif chr ==# 'o'
let fct='0-7'
elseif chr ==# 's'
"v141
if s:extended_spaces==1
"v217
if (s:countermeasure==1) && (complement==1)
let fct=" \\t\\r\x0c"
else
let fct=" \\t\\r\\n\x0c"
endif
let has_newline=1
else
let fct=' \t'
endif
elseif chr ==# 'u'
let fct='A-Z'
elseif chr ==# 'w'
let fct='0-9A-Za-z_'
elseif chr ==# 'x'
let fct='0-9A-Fa-f'
endif
let s:stack{snum}=fct
else
"v120
if fct ==# '\n'
"If there is only "\n" of inside of the brackets.
"It becomes the same as "\_.".
let has_newline=1
"v219
elseif fct ==# '-'
" '-' converted from \xnn
"If there is '-' in the beginning of the brackets and the end.
"Unnecessary '\' is stuck.
let s:stack{snum}='\-'
"v237
elseif fct ==# '\['
" '\[' converted from \xnn
let s:stack{snum}='['
endif
endif
let searchstart = mtop + strlen(mstr)
let mtop = match(bracket, re_mark, searchstart)
endwhile
"v120
if (complement==1) && (has_newline==0)
let bracket = s:mark_complements . bracket
endif
return bracket
endfunction
"end ExpandAtomsInBrackets()
"-----------------------------------------------------------------------------
function! s:Pop()
if s:stack_size <= 0 | return "" | endif
let s:stack_size = s:stack_size - 1
return s:stack{s:stack_size}
endfunction
"-----------------------------------------------------------------------------
" Debug:
function! s:UnletStack()
let i = 0
while exists("s:stack" . i)
exec "unlet s:stack" . i
let i = i + 1
endwhile
let s:stack_size = 0
endfunction
" Debug:
"function! EachStack()
" let lineno = line(".")
" let i = 0
" while exists("s:stack" . i)
" call append(lineno + i, i . " -> " . s:stack{i})
" let i = i + 1
" endwhile
"endfunction
"-----------------------------------------------------------------------------
function! s:ReplaceExtendedRegexFactorWithNumberFactor(extendedregex)
let halfway = a:extendedregex
let s:stack_size = 0
let i=0
let id_num=0
while i < s:re_factor_size
"CASESENSE:
let regex = '\C' . s:re_factor{i}
let mtop = match(halfway, regex)
while mtop >= 0
let factor = matchstr(halfway, regex)
let pre_match = strpart(halfway, 0, mtop)
let post_match= strpart(halfway, mtop + strlen(factor))
let halfway = pre_match . s:mark_left . id_num . s:mark_right . post_match
"END:
call s:Push( factor, i )
let id_num = id_num + 1
let mtop = match(halfway, regex)
endwhile
let i = i + 1
endwhile
return halfway
endfunction
"end s:ReplaceExtendedRegexFactorWithNumberFactor()
"-----------------------------------------------------------------------------
function! s:ReplaceRemainFactorWithVimRegexFactor(halfway)
let halfway = a:halfway
" minimal match, not greedy
let halfway = substitute(halfway, '+?', '\\{-1,}', 'g')
let halfway = substitute(halfway, '\*?', '\\{-}', 'g')
let halfway = substitute(halfway, '??', '\\{-,1}', 'g')
"--------------------
let halfway = substitute(halfway, '+', '\\+', 'g')
let halfway = substitute(halfway, '?', '\\=', 'g')
"--------------------
let halfway = substitute(halfway, '|', '\\|', 'g')
"--------------------
let halfway = substitute(halfway, '\~', '\\&', 'g')
"--------------------
"v141
if s:extended_dots==1
let halfway = substitute(halfway, '\.', '\\_.', 'g')
endif
return halfway
endfunction
"end s:ReplaceRemainFactorWithVimRegexFactor()
"-----------------------------------------------------------------------------
function! s:ReplaceNumberFactorWithVimRegexFactor(halfway)
let vimregex = a:halfway
let i = s:stack_size
while i > 0
let i = i - 1
let factor = s:Pop()
let str_mark = s:mark_left . i . s:mark_right
let vimregex = s:ReplaceAsStr(vimregex, str_mark, factor)
endwhile
"Debug:
call s:UnletStack()
"v221
"v120
if stridx(vimregex, s:mark_complements)!=-1
"v141
if s:extended_complements==1
"there isn't \_ before [^...].
" [^...] doesn't contain \n.
let re='\C\%(\%(\\\)\@<!\(\\\\\)*\\_\)\@<!\zs' . s:mark_complements
let vimregex = substitute(vimregex, re, '\\_', "g")
endif
let vimregex = substitute(vimregex, '\C' . s:mark_complements, '', "g")
endif
"v220
if s:extended_complements==1
let re='\C' . s:re_escaped . '\([ADHLOUWX]\)'
let vimregex = substitute(vimregex, re, '\\_\1', "g")
endif
"v141
if s:extended_spaces==1
" | atom | normal | extended spaces
" | \s | [ \t] | [ \t\r\n\f]
" | \S | [^ \t] | [^ \t\r\n\f]
" | \_s | \_[ \t] | [ \t\r\n\f]
" | \_S | \_[^ \t] | [^ \t\r\n\f] *
let ff=nr2char(0x0c)
let re='\C' . s:re_escaped . '_\=s'
let vimregex=substitute(vimregex, re, '[ \\t\\r\\n' . ff . ']', "g")
let re='\C' . s:re_escaped . '_\=S'
if s:countermeasure==1
"v216
let vimregex=substitute(vimregex, re, '[^ \\t\\r' . ff . ']', "g")
else
let vimregex=substitute(vimregex, re, '[^ \\t\\r\\n' . ff . ']', "g")
endif
endif
if s:ignorecase > 0
let tmp = (s:ignorecase==1) ? '\c' : '\C'
let vimregex = tmp . vimregex
endif
"if &magic==0
" let vimregex = '\m' . vimregex
"endif
return vimregex
endfunction
"end s:ReplaceNumberFactorWithVimRegexFactor()
"=============================================================================
"Main:
function! s:ExtendedRegex2VimRegex(extendedregex, ...)
"v141
let s:ignorecase=0
let s:multiline=0
let s:extended_spaces=0
let s:extended_complements=0
let s:extended_dots=0
if a:0==1
"v238,v243
if a:1 =~# 'R[0-3]'
return s:ExchangeReplaceSpecials(a:extendedregex, matchstr(a:1, 'R\zs[0-3]'))
"v240
elseif a:1 ==# 'V'
return s:version
endif
call s:SetModifiers(a:1)
endif
"v240 moved here
if strlen(a:extendedregex)==0
return ""
endif
"v141
let eregex=a:extendedregex
"v221
let mods = matchstr(eregex, '\C' . s:re_escaped . '[Mm]')
let mods = mods . matchstr(eregex, '\C' . s:re_escaped . '[Cc]')
if mods !=# ''
let mods = substitute(mods, '\CC', 'I',"g")
let mods = substitute(mods, '\Cc', 'i',"g")
call s:SetModifiers(mods)
let re='\C' . s:re_escaped . '[MmCc]'
let eregex=substitute(eregex, re, '', "g")
endif
"--------------------
let halfway = s:ReplaceExtendedRegexFactorWithNumberFactor(eregex)
let halfway = s:ReplaceRemainFactorWithVimRegexFactor(halfway)
let vimregex = s:ReplaceNumberFactorWithVimRegexFactor(halfway)
"v221
return vimregex
endfunction
"end s:ExtendedRegex2VimRegex()
"-----------------------------------------------------------------------------
function! s:ExtendedRegex2VimRegexLineWise(...) range
if a:1 ==# '--version'
echo "$Id: eregex.vim,v 2.56 2003-09-19 17:39:41+09 ta Exp $"
return
endif
let modifiers= a:1
let i = a:firstline
while i <= a:lastline
call setline(i, s:ExtendedRegex2VimRegex(getline(i), modifiers))
let i = i + 1
endwhile
endfunction
"end s:ExtendedRegex2VimRegexLineWise()
"-----------------------------------------------------------------------------
"Public:
function! E2v(extendedregex, ...)
if a:0==0
return s:ExtendedRegex2VimRegex(a:extendedregex)
endif
return s:ExtendedRegex2VimRegex(a:extendedregex, a:1)
endfunction
"end E2v()
"-----------------------------------------------------------------------------
function! s:Ematch(...)
if strlen(a:2) <= 1 | return | endif
let ccount = a:1
let string = a:2
let delim=string[0]
if delim !=# '/' && delim !=# '?'
let v:errmsg= "The delimiter `" . delim . "' isn't available, use `/' ."
echo v:errmsg
return
endif
let rxp ='^delim\([^delim\\]*\%(\\.[^delim\\]*\)*\)' .
\ '\(delim.*\)\=$'
let rxp=substitute(rxp, 'delim', delim, "g")
let regex = substitute(string, rxp, '\1',"")
let offset= substitute(string, rxp, '\2', "")
"--------------------
let modifiers=''
"v141
if offset =~# '[' . s:str_modifiers . ']'
let modifiers = substitute(offset, '\C[^' . s:str_modifiers . ']\+', "", "g")
let offset = substitute(offset, '\C[' . s:str_modifiers . ']\+', "", "g")
endif
if &ignorecase
let modifiers .= 'i'
endif
let regex = s:ExtendedRegex2VimRegex(regex, modifiers)
"v130
"set s:bakregex
let regex = s:EscapeAndUnescape(regex, delim)
"--------------------
if offset==# ''
let offset = delim
endif
let cmd = 'normal! ' . ccount . delim . regex . offset . "\<CR>"
let v:errmsg=''
set nohlsearch
silent! exec cmd
if (v:errmsg !~# '^E\d\+:') || (v:errmsg =~# '^E486:')
"v130
if s:bakregex !=# ''
let @/ = s:bakregex
endif
endif
if v:errmsg ==# ''
redraw!
else
echo 'M' . a:2
echo v:errmsg
endif
if delim == '?'
return 0
else
return 1
endif
endfunction
"end s:Ematch()
"-----------------------------------------------------------------------------
function! s:Esubstitute(...) range
if strlen(a:1) <= 1 | return | endif
let string = a:1
let delim = s:GetDelim(string[0])
if delim==# '' | return | endif
let rxp ='^delim\([^delim\\]*\%(\\.[^delim\\]*\)*\)delim\([^delim\\]*\%(\\.[^delim\\]*\)*\)' .
\ '\(delim.*\)\=$'
let rxp=substitute(rxp, 'delim', delim, "g")
if string !~# rxp
if s:eglobal_working==0
echo 'Invalid arguments S' . a:1
endif
return
endif
let regex = substitute(string, rxp, '\1',"")
let replacement = substitute(string, rxp, '\2', "")
let options = substitute(string, rxp, '\3',"")
"--------------------
"v141
let modifiers=''
if options =~# '[' . s:str_modifiers . ']'
let modifiers = substitute(options, '\C[^' . s:str_modifiers . ']\+', "", "g")
let options = substitute(options, '\C[SCDmM]', "", "g")
endif
if &ignorecase
let modifiers .= 'i'
endif
let regex = s:ExtendedRegex2VimRegex(regex, modifiers)
"v130
"set s:bakregex
let regex = s:EscapeAndUnescape(regex, delim)
"v238, v243
if (s:eregex_replacement > 0) && (strlen(replacement) > 1)
let replacement = s:ExchangeReplaceSpecials(replacement, s:eregex_replacement)
endif
"--------------------
if options ==# ''
let options = delim
endif
let cmd = a:firstline . ',' . a:lastline . 's' . delim . regex . delim . replacement . options
"Evaluater:
let g:eregex_evaluater_how_exe = s:eglobal_working
if g:eregex_evaluater_how_exe==0
let v:statusmsg=''
let v:errmsg=''
endif
let confirmoption = (options =~# 'c')
if confirmoption==1
"with confirm option.
let g:eregex_evaluater_how_exe=1
endif
let g:eregex_evaluater_cmd = cmd
runtime plugin/eregex_e.vim
if g:eregex_evaluater_how_exe==0 || confirmoption==1
unlet! g:eregex_evaluater_cmd
"v130
if s:bakregex !=# ''
let @/ = s:bakregex
endif
if confirmoption==0
if v:errmsg==# ''
if v:statusmsg !=# ''
echo v:statusmsg
endif
else
echo v:errmsg
endif
endif
endif
endfunction
"end s:Esubstitute()
"-----------------------------------------------------------------------------
function! s:Eglobal(bang, ...) range
if strlen(a:1)<=1 | return | endif
let string=a:1
let delim = s:GetDelim(string[0])
if delim==#'' | return | endif
"--------------------
let re_pattern = substitute('[^delim\\]*\%(\\.[^delim\\]*\)*', 'delim', delim,"g")
let re_offset = '\%([-+0-9]\d*\|\.[-+]\=\d*\)'
let re_sep = '[,;]'
let re_command = '[^,;].*'
let re_command_less = '\_$'
let re_end = '\%(' . re_sep . '\|' . re_command . '\|' . re_command_less . '\)'
"--------------------
let toprxp0 = '^' . delim . '\(' . re_pattern . '\)\(' . delim . re_offset . re_sep . '\)'
let toprxp1 = '^' . delim . '\(' . re_pattern . '\)\(' . delim . re_sep . '\)'
let toprxp2 = '^'
let endrxp0 = delim . '\(' . re_pattern . '\)\(' . delim . re_offset . re_end . '\)'
let endrxp1 = delim . '\(' . re_pattern . '\)\(' . delim . re_end . '\)'
let endrxp2 = delim . '\(' . re_pattern . '\)' . re_command_less
"--------------------
let mtop = -1
let j = 0
while j < 3
let i = 0
while i < 3
let regexp = toprxp{j} . endrxp{i}
let mtop = match(string, regexp)
if mtop>=0 | break | endif
let i = i + 1
endwhile
if mtop>=0 | break | endif
let j = j + 1
endwhile
if mtop<0 | return | endif
"--------------------
if a:bang==# '!'
let s:invert=1
endif
let cmd = (s:invert==0) ? 'g' : 'v'
let s:invert=0
let cmd = a:firstline . ',' . a:lastline . cmd
let globalcmd = ''
if j == 2
let pattern1 = substitute(string, regexp, '\1', "")
let strright = delim
if i < 2
let strright = substitute(string, regexp, '\2', "")
endif
let pattern1 = s:ExtendedRegex2VimRegex(pattern1)
"v130
let pattern1 = s:EscapeAndUnescape(pattern1, delim)
let globalcmd = cmd . delim . pattern1 . strright
else
let pattern1 = substitute(string, regexp, '\1', "")
let strmid = substitute(string, regexp, '\2',"")
let pattern2 = substitute(string, regexp, '\3', "")
let strright = delim
if i < 2
let strright = substitute(string, regexp, '\4', "")
endif
let pattern1 = s:ExtendedRegex2VimRegex(pattern1)
let pattern2 = s:ExtendedRegex2VimRegex(pattern2)
"v130
let pattern1 = s:EscapeAndUnescape(pattern1, delim)
let pattern2 = s:EscapeAndUnescape(pattern2, delim)
let globalcmd = cmd . delim . pattern1 . strmid . delim . pattern2 . strright
endif
"--------------------
"Evaluater:
let s:eglobal_working=1
let g:eregex_evaluater_how_exe=2
let g:eregex_evaluater_cmd = globalcmd
runtime plugin/eregex_e.vim
let s:eglobal_working=0
"let g:eregex_evaluater_how_exe=0
unlet! g:eregex_evaluater_cmd
endfunction
"end s:Eglobal()
"-----------------------------------------------------------------------------
function! s:Evglobal(...) range
let s:invert=1
let cmd = a:firstline . ',' . a:lastline . 'G' . a:1
exec cmd
endfunction
"end s:Evglobal()
"-----------------------------------------------------------------------------
function! s:GetDelim(str)
let valid = '[/@#]'
let delim = a:str[0]
if delim =~# valid
return delim
endif
let v:errmsg = "The delimiter `" . delim . "' isn't available, use " . valid
echo v:errmsg
return ''
endfunction
"end s:GetDelim()
"=============================================================================
"v130
"called from Ematch(), Esubstitute(), Eglobal()
"use s:re_unescaped, s:re_escaped, s:bakregex
function! s:EscapeAndUnescape(vimregex, delim)
let vimregex = a:vimregex
let s:bakregex= a:vimregex
if a:delim ==# '@'
return vimregex
endif
if s:bakregex =~# s:re_escaped . a:delim
" \/ or \# exists
let s:bakregex = substitute(vimregex, s:re_escaped . a:delim, a:delim, "g")
endif
if vimregex =~# s:re_unescaped . a:delim
" / or # exists
let vimregex = substitute(vimregex, s:re_unescaped . a:delim, '\\' . a:delim, "g")
endif
return vimregex
endfunction
"end s:EscapeAndUnescape()
"=============================================================================
"v141
"called from only s:ExtendedRegex2VimRegex()
function! s:SetModifiers(mods)
"v221
if s:ignorecase==0
if a:mods =~# 'i'
let s:ignorecase=1
elseif a:mods =~# 'I'
let s:ignorecase=2
endif
endif
"v221
if s:multiline==0
if a:mods =~? 'm'
let s:extended_spaces=1
let s:extended_complements=1
if a:mods =~# 'M'
"partial multiline
let s:multiline=1
else
"full multiline
let s:extended_dots=1
let s:multiline=2
endif
endif
endif
if a:mods =~# 'S'
let s:extended_spaces=1
endif
if a:mods =~# 'C'
let s:extended_complements=1
endif
if a:mods =~# 'D'
let s:extended_dots=1
endif
endfunction
"End: s:SetModifiers(mods)
"=============================================================================
"v238,
function! s:ExchangeReplaceSpecials(replacement, sort)
let rs=a:replacement
"v243,v246
if (rs !~# '[&~]\|\\[rnx]') || (rs =~# '^\\=')
return rs
endif
if (a:sort % 2)==1
let rs=substitute(rs, '\C' . s:re_escaped . 'r', '\\R', "g")
let rs=substitute(rs, '\C' . s:re_escaped . 'n', '\\r', "g")
let rs=substitute(rs, '\C' . s:re_escaped . 'R', '\\n', "g")
endif
if a:sort >= 2
let rs=substitute(rs, '\C' . s:re_escaped . '&', '\\R', "g")
let rs=substitute(rs, '\C' . s:re_escaped . '\~', '\\N', "g")
let rs=substitute(rs, '\C' . s:re_unescaped . '[&~]', '\\&', "g")
let rs=substitute(rs, '\C' . s:re_escaped . 'R', '\&', "g")
let rs=substitute(rs, '\C' . s:re_escaped . 'N', '\~', "g")
endif
return rs
endfunction
"End: s:ExchangeReplaceSpecials()
"=============================================================================
"=============================================================================
"Import: macros/locrian.vim
function! s:ReplaceAsStr(str, search, replacement, ...)
let gsub = a:0
if a:0 > 0
let gsub = (a:1=~? 'g') ? 1 : 0
endif
let oldstr = a:str
let newstr = ""
let len = strlen(a:search)
let i = stridx(oldstr, a:search)
while i >= 0
let newstr = newstr . strpart(oldstr, 0, i) . a:replacement
let oldstr = strpart(oldstr, i + len)
if gsub==0
break
endif
let i = stridx(oldstr, a:search)
endwhile
if strlen(oldstr)!=0
let newstr = newstr . oldstr
endif
return newstr
endfunction
"end s:ReplaceAsStr()
"=============================================================================
" $Id: eregex_e.vim,v 1.40 2003-06-03 18:25:59+09 ta Exp ta $
" An evaluater for eregex.vim
if exists('g:eregex_evaluater_cmd') && exists('g:eregex_evaluater_how_exe')
if g:eregex_evaluater_how_exe==0
" :s silently exec, handle errmsg
silent! exec g:eregex_evaluater_cmd
elseif g:eregex_evaluater_how_exe==1
" :s invoked by :g and
" :s with confirm option
exec g:eregex_evaluater_cmd
elseif g:eregex_evaluater_how_exe==2
":g
redraw
exec g:eregex_evaluater_cmd
endif
endif
{'version': 0.3, 'files': [{'file': '/home/bro3886/.vim/doc/eregex.jax', 'checksum': ''}, {'file': '/home/bro3886/.vim/doc/eregex.txt', 'checksum': ''}, {'file': '/home/bro3886/.vim/plugin/eregex.vim', 'checksum': ''}, {'file': '/home/bro3886/.vim/plugin/eregex_e.vim', 'checksum': ''}], 'install_type': 'makefile', 'script_version': '2.61', 'package': 'eregex.vim', 'generated_by': 'Vim-Makefile'}
" Vim syntax file for browsing debian package.
" copyright (C) 2007, arno renevier <arenevier@fdn.fr>
" Distributed under the GNU General Public License (version 2 or above)
" Last Change: 2007 December 07
"
" Latest version of that file can be found at
" http://www.fdn.fr/~arenevier/vim/syntax/deb.vim
" It should also be available at
" http://www.vim.org/scripts/script.php?script_id=1970
if exists("b:current_syntax")
finish
endif
syn match debComment '^".*'
syn match debInfoFilename '^\* \.\/.*'
syn match debDataFilename '^\.\/.*[^/]$'
syn match debDirname '^\..*\/$'
syn match debSymlink '^\.\/.* -> .*$' contains=debSymlinkTarget,debSymlinkArrow,debSymlinkName
syn match debSymlinkName '^\S*' contained
syn match debSymlinkTarget '\S*$' contained
syn match debSymlinkArrow '->' contained
hi def link debComment Comment
hi def link debInfoFilename Type
hi def link debDataFilename PreProc
hi def link debSymlinkName Identifier
hi def link debSymlinkTarget PreProc
" Vim Syntax File
"
" Language: Prolog
" Maintainers: Aleksandar Dimitrov <aleks.dimitrov@googlemail.com>
" Created: Jul 31st, 2008
" Changed: Fri Aug 1 2008
" Remark: This file mostly follows
" http://www.sics.se/sicstus/docs/3.7.1/html/sicstus_45.html
" but also features some SWI-specific enhancements.
" The BNF cannot be followed strictly, but I tried to do my best.
"
" TODO: - Difference Lists
" - Constraint logic programming
if version < 600
syn clear
elseif exists("b:current_syntax")
finish
endif
syntax case match
syntax keyword prologISOBuiltIn var nonvar integer float number atom string
\atomic compound unify_with_occurs_check fail false true repeat call once
\catch throw abolish retract asserta assertz current_predicate clause open
\close stream_property set_stream_position set_input set_output current_ouput
\nl put_byte put_char put_code flush_output get_byte get_code get_char
\peek_byte peek_code peek_char at_end_of_stream write_term write_canonical
\write writeq read read_term functor arg copy_term atom_codes atom_chars
\char_code number_chars number_codes atom_length sub_atom op current_op
\char_conversion current_char_conversion is mod rem div round float
\float_fractional_part float_integer_part truncate floor ceiling sqrt sin cos
\atan log findall bagof setof sub_atom
syntax keyword prologSWIBuiltIn rational callable ground cyclic_term subsumes subsumes_chk
\unifiable use_module compare apply not ignore call_with_depth_limit call_cleanup
\print_message print_message_lines message_hook on_signal current_signal block exit
\term_hash redefine_system_predicate retractall assert recorda recordz recorded
\erase flag compile_predicates index current_atom
\current_blob current_functor current_flag current_key dwim_predicate nth_clause
\predicate_property open_null_stream current_stream is_stream stream_position_data
\seek set_stream see tell append seeing telling seen set_prolog_IO told
\wait_for_input byte_count character_count line_count line_position read_clause
\put tab ttyflush get0 get skip get_single_char copy_stream_data print portray
\read_history prompt setarg nb_setarg nb_linkarg duplicate_term numbervars
\term_variables atom_number name term_to_atom atom_to_term atom_concat
\concat_atom atom_prefix normalize_space collation_key char_type string_to_list
\code_type downcase_atom upcase_atom collation_key locale_sort string_to_atom
\string_length string_concat sub_string between succ plus rdiv max min random
\integer rationalize ceil xor tan asin acos pi e cputime eval msb lsb popcount
\powm arithmetic_function current_arithmetic_function is_list memberchk length
\sort msort keysort predsort merge merge_set maplist forall writeln writef
\swritef format format_predicate current_format_predicate tty_get_capability
\tty_goto tty_put set_tty tty_size shell win_exec win_shell win_folder
\win_registry_get_value getenv setenv unsetenv setlocale unix date time
\get_time stamp_date_time date_time_stamp date_time_value format_time
\parse_time window_title win_window_pos win_has_menu win_insert_menu
\win_insert_menu_item access_file exists_file file_directory_name file_base_name
\same_file exists_directory delete_file rename_file size_file time_file
\absolute_file_name is_absolute_file_name file_name_extension expand_file_name
\prolog_to_os_filename read_link tmp_file make_directory working_directory chdir
\garbage_collect garbage_collect_atoms trim_stacks stack_parameter dwim_match
\wildcard_match sleep qcompile portray_clause acyclic_term clause_property
\setup_and_call_cleanup message_to_string phrase hash with_output_to fileerrors
\read_pending_input prompt1 same_term sub_string merge_set
syntax cluster prologBuiltIn contains=prologSWIBuiltIn,prologISOBuiltIn
syntax match prologArithmetic /\*\*\?\|+\|\/\/\?\|\/\\\|<<\|>>\|\\\/\?\|\^/
\contained containedin=prologBody
syntax match prologRelations /=\.\.\|!\|=:=\|=\?<\|=@=\|=\\=\|>=\?\|@=\?<\|@>=\?\|\\+\|\\\?=\?=\|\\\?=@=\|=/
\contained containedin=prologBody
syntax region prologCComment fold start=/\/\*/ end=/\*\// contains=prologTODO,@Spell
syntax match prologComment /%.*/ contains=prologTODO,@Spell
syntax region prologCommentFold fold start=/^\zs\s*%/ skip=/^\s*%/ end=/^\ze\s*\([^%]\|$\)/ contains=prologComment
syntax keyword prologTODO FIXME TODO fixme todo Fixme FixMe Todo ToDo XXX xxx contained
syntax cluster prologComments contains=prologCComment,prologComment,prologCommentFold
syntax region prologBody fold start=/\(:-\|?-\)/ end=/\./
\contains=@prologAll,prologPredicateWithArity
syntax region prologDCGBody fold start=/-->/ end=/\./
\contains=@prologAll,prologDCGSpecials
syntax match prologNumber /\<\d\+\>/ contained
syntax match prologNumber /\<\d\+\.\d\+\>/ contained
syntax match prologAtom /\<\l\w*\>\ze\([^(]\|$\)/ contained
syntax match prologVariable /\<\(_\|\u\)\w*\>/ contained
syntax match prologChar /\<\0'\(\\\)\?.\>/ contained
syntax match prologHead /\<\l\w*\>/ nextgroup=prologBody,prologDCGBody skipwhite
syntax region prologHeadWithArgs start=/\<\l\w*\>(/ end=/)/ nextgroup=prologBody,prologDCGBody contains=@prologAll
syntax match prologOpStatement /indexed\|discontiguous\|dynamic\|module_transparent\|multifile\|volatile\|initialization/
\containedin=prologBody contained
syntax region prologDCGSpecials start=/{/ end=/}/ contained contains=@prologAll
syntax region prologTuple fold start=/\W\zs(/ end=/)/ contained containedin=prologPredicate,prologBody contains=@prologAll
syntax region prologPredicate start=/\<\l\w*\>\ze(/ end=/)/ contains=@prologAll
syntax match prologPredicateWithArity /\<\l\w*\>\/\d\+/ contains=@prologBuiltIn,prologArity
syntax match prologArity contained /\/\d\+/
syntax cluster prologPredicates contains=prologPredicate,prologPredicateWithArity
syntax region prologList start=/\[/ end=/\]/ contains=prologListDelimiters,@prologAll,prologPredicateWithArity contained
syntax match prologListDelimiters /[,|]/ contained
syntax cluster prologAll contains=prologList,prologPredicate,prologTuple,@prologTerms,@prologComments,prologQuoted,@prologBuiltIn,prologRelations,prologArithmetic,prologDiffList
syntax cluster prologTerms contains=prologVariable,prologAtom,prologList,
\prologNumber,prologErrorTerm,prologChar
syntax match prologQuotedFormat /\~\(\d*[acd\~DeEgfGiknNpqrR@st\|+wW]\|`.t\)/ contained
syntax region prologQuoted start=/'/ end=/'/ contains=prologQuotedFormat,@Spell
syntax match prologErrorVariable /\<\(_\|\u\)\w*\>/
syntax region prologErrorTerm start=/\<\(_\|\u\)\w*\>(/ end=/)/
"""" Highlights
highlight link prologErrorVariable Error
highlight link prologErrorTerm Error
highlight link prologOpStatement Preproc
highlight link prologComment Comment
highlight link prologCComment Comment
highlight link prologTODO TODO
highlight link prologAtom Constant
highlight link prologChar Constant
highlight link prologVariable Identifier
highlight link prologNumber Number
highlight link prologISOBuiltIn Keyword
highlight link prologSWIBuiltIn Keyword
highlight link prologRelations Statement
highlight link prologQuotedFormat Special
highlight link prologQuoted String
highlight link prologPredicate Normal
highlight link prologPredicateWithArity Normal
highlight link prologHead Constant
highlight link prologHeadWithArgs Normal
highlight link prologBody Statement
highlight link prologDCGBody Statement
highlight link prologList Type
highlight link prologListDelimiters Type
highlight link prologArity Type
highlight link prologDCGSpecials Type
highlight link prologTuple Type
highlight link prologDiffList Type
syn sync minlines=20 maxlines=50
let b:current_syntax = "prolog"
" Vim syntax file
" Language: Vala
" Maintainers: Emmanuele Bassi <ebassi@gnome.org>
" Hans Vercammen <hveso3@gmail.com>
" pancake <pancake@nopcode.org>
" Sebastian Reichel <sre@ring0.de>
" Last Change: 2012-02-19
" Filenames: *.vala *.vapi
"
" REFERENCES:
" [1] http://live.gnome.org/Vala
"
" TODO: Possibly when reaching vala 1.0 release
" - validate code attributes
" - better error checking for known errors
" - full support for valadoc
"
" add vala in /usr/share/vim/vim73/scripts.vim below ruby
" to have shebang support
if exists("b:current_syntax")
finish
endif
let s:vala_cpo_save = &cpo
set cpo&vim
" Types
syn keyword valaType bool char double float size_t ssize_t string unichar void
syn keyword valaType int int8 int16 int32 int64 long short
syn keyword valaType uint uint8 uint16 uint32 uint64 ulong ushort
" Storage keywords
syn keyword valaStorage class delegate enum errordomain interface namespace struct
" repeat / condition / label
syn keyword valaRepeat break continue do for foreach return while
syn keyword valaConditional else if switch assert
" User Labels
syn keyword valaLabel case default
" Modifiers
syn keyword valaModifier abstract const dynamic ensures extern inline internal override
syn keyword valaModifier private protected public requires signal static virtual volatile weak
syn keyword valaModifier async owned unowned
" Constants
syn keyword valaConstant false null true
" Exceptions
syn keyword valaException try catch finally throw
" Unspecified Statements
syn keyword valaUnspecifiedStatement as base construct delete get in is lock new out params ref sizeof set this throws typeof using value var yield
" Comments
syn cluster valaCommentGroup contains=valaTodo
syn keyword valaTodo contained TODO FIXME XXX NOTE
" valadoc Comments (ported from javadoc comments in java.vim)
" TODO: need to verify valadoc syntax
if !exists("vala_ignore_valadoc")
syn cluster valaDocCommentGroup contains=valaDocTags,valaDocSeeTag
syn region valaDocTags contained start="{@\(link\|linkplain\|inherit[Dd]oc\|doc[rR]oot\|value\)" end="}"
syn match valaDocTags contained "@\(param\|exception\|throws\|since\)\s\+\S\+" contains=valaDocParam
syn match valaDocParam contained "\s\S\+"
syn match valaDocTags contained "@\(author\|brief\|version\|return\|deprecated\)\>"
syn region valaDocSeeTag contained matchgroup=valaDocTags start="@see\s\+" matchgroup=NONE end="\_."re=e-1 contains=valaDocSeeTagParam
syn match valaDocSeeTagParam contained @"\_[^"]\+"\|<a\s\+\_.\{-}</a>\|\(\k\|\.\)*\(#\k\+\((\_[^)]\+)\)\=\)\=@ extend
endif
" Comment Strings (ported from c.vim)
if exists("vala_comment_strings")
syn match valaCommentSkip contained "^\s*\*\($\|\s\+\)"
syn region valaCommentString contained start=+L\=\\\@<!"+ skip=+\\\\\|\\"+ end=+"+ end=+\*/+me=s-1 contains=valaSpecialChar,valaCommentSkip
syn region valaComment2String contained start=+L\=\\\@<!"+ skip=+\\\\\|\\"+ end=+"+ end="$" contains=valaSpecialChar
syn cluster valaCommentStringGroup contains=valaCommentString,valaCharacter,valaNumber
syn region valaCommentL start="//" end="$" keepend contains=@valaCommentGroup,valaComment2String,valaCharacter,valaNumber,valaSpaceError,@Spell
syn region valaComment matchgroup=valaCommentStart start="/\*" end="\*/" contains=@valaCommentGroup,@valaCommentStringGroup,valaCommentStartError,valaSpaceError,@Spell extend fold
if !exists("vala_ignore_valadoc")
syn region valaDocComment matchgroup=valaCommentStart start="/\*\*" end="\*/" keepend contains=@valaCommentGroup,@valaDocCommentGroup,@valaCommentStringGroup,valaCommentStartError,valaSpaceError,@Spell
endif
else
syn region valaCommentL start="//" end="$" keepend contains=@valaCommentGroup,valaSpaceError,@Spell
syn region valaComment matchgroup=valaCommentStart start="/\*" end="\*/" contains=@valaCommentGroup,valaCommentStartError,valaSpaceError,@Spell
if !exists("vala_ignore_valadoc")
syn region valaDocComment matchgroup=valaCommentStart start="/\*\*" end="\*/" keepend contains=@valaCommentGroup,@valaDocCommentGroup,valaCommentStartError,valaSpaceError,@Spell
endif
endif
syn region valaPreCondit start="^\s*\(%:\|#\)\s*\(if\|ifdef\|ifndef\|elif\)\>" skip="\\$" end="$" end="//"me=s-1
syn match valaPreCondit display "^\s*\(%:\|#\)\s*\(else\|endif\)\>"
" Comment if 0 blocks (ported from c.vim)
if !exists("vala_no_if0")
syn region valaCppOut start="^\s*\(%:\|#\)\s*if\s\+0\+\>" end=".\@=\|$" contains=valaCppOut2 fold
syn region valaCppOut2 contained start="0" end="^\s*\(%:\|#\)\s*\(endif\>\|else\>\|elif\>\)" contains=valaSpaceError,valaCppSkip
syn region valaCppSkip contained start="^\s*\(%:\|#\)\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*\(%:\|#\)\s*endif\>" contains=valaSpaceError,valaCppSkip
endif
" match comment errors
syntax match valaCommentError display "\*/"
syntax match valaCommentStartError display "/\*"me=e-1 contained
" match the special comment /**/
syn match valaComment "/\*\*/"
" Vala Code Attributes
syn region valaAttribute start="^\s*\[" end="\]$" contains=valaComment,valaString keepend
syn region valaAttribute start="\[CCode" end="\]" contains=valaComment,valaString
" Avoid escaped keyword matching
syn match valaUserContent display "@\I*"
" Strings and constants
syn match valaSpecialError contained "\\."
syn match valaSpecialCharError contained "[^']"
syn match valaSpecialChar contained +\\["\\'0abfnrtvx]+
syn region valaString start=+"+ end=+"+ end=+$+ contains=valaSpecialChar,valaSpecialError,valaUnicodeNumber,@Spell
syn region valaVerbatimString start=+"""+ end=+"""+ contains=@Spell
syn match valaUnicodeNumber +\\\(u\x\{4}\|U\x\{8}\)+ contained contains=valaUnicodeSpecifier
syn match valaUnicodeSpecifier +\\[uU]+ contained
syn match valaCharacter "'[^']*'" contains=valaSpecialChar,valaSpecialCharError
syn match valaCharacter "'\\''" contains=valaSpecialChar
syn match valaCharacter "'[^\\]'"
syn match valaNumber display "\<\(0[0-7]*\|0[xX]\x\+\|\d\+\)[lL]\=\>"
syn match valaNumber display "\(\<\d\+\.\d*\|\.\d\+\)\([eE][-+]\=\d\+\)\=[fFdD]\="
syn match valaNumber display "\<\d\+[eE][-+]\=\d\+[fFdD]\=\>"
syn match valaNumber display "\<\d\+\([eE][-+]\=\d\+\)\=[fFdD]\>"
" when wanted, highlight trailing white space
if exists("vala_space_errors")
if !exists("vala_no_trail_space_error")
syn match valaSpaceError display excludenl "\s\+$"
endif
if !exists("vala_no_tab_space_error")
syn match valaSpaceError display " \+\t"me=e-1
endif
endif
" when wanted, set minimum lines for comment syntax syncing
if exists("vala_minlines")
let b:vala_minlines = vala_minlines
else
let b:vala_minlines = 50
endif
exec "syn sync ccomment valaComment minlines=" . b:vala_minlines
" code folding
syn region valaBlock start="{" end="}" transparent fold
" The default highlighting.
hi def link valaType Type
hi def link valaStorage StorageClass
hi def link valaRepeat Repeat
hi def link valaConditional Conditional
hi def link valaLabel Label
hi def link valaModifier StorageClass
hi def link valaConstant Constant
hi def link valaException Exception
hi def link valaUnspecifiedStatement Statement
hi def link valaUnspecifiedKeyword Keyword
hi def link valaContextualStatement Statement
hi def link valaCommentError Error
hi def link valaCommentStartError Error
hi def link valaSpecialError Error
hi def link valaSpecialCharError Error
hi def link valaSpaceError Error
hi def link valaTodo Todo
hi def link valaCommentL valaComment
hi def link valaCommentStart valaComment
hi def link valaCommentSkip valaComment
hi def link valaComment Comment
hi def link valaDocComment Comment
hi def link valaDocTags Special
hi def link valaDocParam Function
hi def link valaDocSeeTagParam Function
hi def link valaAttribute PreCondit
hi def link valaCommentString valaString
hi def link valaComment2String valaString
hi def link valaString String
hi def link valaVerbatimString String
hi def link valaCharacter Character
hi def link valaSpecialChar SpecialChar
hi def link valaNumber Number
hi def link valaUnicodeNumber SpecialChar
hi def link valaUnicodeSpecifier SpecialChar
hi def link valaPreCondit PreCondit
if !exists("vala_no_if0")
hi def link valaCppSkip valaCppOut
hi def link valaCppOut2 valaCppOut
hi def link valaCppOut Comment
endif
let b:current_syntax = "vala"
let &cpo = s:vala_cpo_save
unlet s:vala_cpo_save
" vim: ts=8
execute pathogen#infect()
"let g:haddock_browser="/usr/bin/firefox"
let g:syntastic_cpp_compiler_options=' -std=c++11'
let g:localrc_filename=".lvimrc"
let g:SuperTabDefaultCompletionType="context"
set omnifunc=syntaxcomplete#Complete
set foldmethod=syntax
"let g:SuperTabDefaultCompletionType = \"<C-X><C-O>\"
if has('cscope')
set cscopetag cscopeverbose
if has('quickfix')
set cscopequickfix=s-,c-,d-,i-,t-,e-
endif
cnoreabbrev csa cs add
cnoreabbrev csf cs find
cnoreabbrev csk cs kill
cnoreabbrev csr cs reset
" cnoreabbrev css cs show
cnoreabbrev csh cs help
command -nargs=0 Cscope cs add $VIMSRC/src/cscope.out $VIMSRC/src
endif
set laststatus=2
"python from powerline.vim import setup as powerline_setup
"python powerline_setup()
"python del powerline_setup
if has("gui_running")
if has("gui_gtk2")
set guifont=Ubuntu\ Mono\ 12
endif
endif
let g:syntastic_cpp_compiler_options=' -std=c++11'
autocmd Filetype gitcommit setlocal spell textwidth=72
let g:syntastic_python_python_exec = '/usr/bin/python3'
let g:DiffColors=100
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment