bgneal@0: " =============================================================================
bgneal@0: " File:          autoload/ctrlp.vim
bgneal@0: " Description:   Fuzzy file, buffer, mru and tag finder.
bgneal@0: " Author:        Kien Nguyen <github.com/kien>
bgneal@0: " Version:       1.6.4
bgneal@0: " =============================================================================
bgneal@0: 
bgneal@0: " Static variables {{{1
bgneal@0: fu! s:opts()
bgneal@0: 	let hst = exists('+hi') ? &hi : 20
bgneal@0: 	let opts = {
bgneal@0: 		\ 'g:ctrlp_by_filename':           ['s:byfname', 0],
bgneal@0: 		\ 'g:ctrlp_clear_cache_on_exit':   ['s:clrex', 1],
bgneal@0: 		\ 'g:ctrlp_dont_split':            ['s:nosplit', ''],
bgneal@0: 		\ 'g:ctrlp_dotfiles':              ['s:dotfiles', 1],
bgneal@0: 		\ 'g:ctrlp_extensions':            ['s:extensions', []],
bgneal@0: 		\ 'g:ctrlp_follow_symlinks':       ['s:folsym', 0],
bgneal@0: 		\ 'g:ctrlp_highlight_match':       ['s:mathi', [1, 'Identifier']],
bgneal@0: 		\ 'g:ctrlp_lazy_update':           ['s:lazy', 0],
bgneal@0: 		\ 'g:ctrlp_jump_to_buffer':        ['s:jmptobuf', 1],
bgneal@0: 		\ 'g:ctrlp_match_window_bottom':   ['s:mwbottom', 1],
bgneal@0: 		\ 'g:ctrlp_match_window_reversed': ['s:mwreverse', 1],
bgneal@0: 		\ 'g:ctrlp_max_depth':             ['s:maxdepth', 40],
bgneal@0: 		\ 'g:ctrlp_max_files':             ['s:maxfiles', 20000],
bgneal@0: 		\ 'g:ctrlp_max_height':            ['s:mxheight', 10],
bgneal@0: 		\ 'g:ctrlp_max_history':           ['s:maxhst', hst],
bgneal@0: 		\ 'g:ctrlp_open_multi':            ['s:opmul', '1v'],
bgneal@0: 		\ 'g:ctrlp_open_new_file':         ['s:newfop', 3],
bgneal@0: 		\ 'g:ctrlp_prompt_mappings':       ['s:urprtmaps', 0],
bgneal@0: 		\ 'g:ctrlp_regexp_search':         ['s:regexp', 0],
bgneal@0: 		\ 'g:ctrlp_root_markers':          ['s:rmarkers', []],
bgneal@0: 		\ 'g:ctrlp_split_window':          ['s:splitwin', 0],
bgneal@0: 		\ 'g:ctrlp_use_caching':           ['s:caching', 1],
bgneal@0: 		\ 'g:ctrlp_use_migemo':            ['s:migemo', 0],
bgneal@0: 		\ 'g:ctrlp_user_command':          ['s:usrcmd', ''],
bgneal@0: 		\ 'g:ctrlp_working_path_mode':     ['s:pathmode', 2],
bgneal@0: 		\ }
bgneal@0: 	for [ke, va] in items(opts)
bgneal@0: 		exe 'let' va[0] '=' string(exists(ke) ? eval(ke) : va[1])
bgneal@0: 	endfo
bgneal@0: 	if !exists('g:ctrlp_newcache') | let g:ctrlp_newcache = 0 | en
bgneal@0: 	let s:glob = s:dotfiles ? '.*\|*' : '*'
bgneal@0: 	let s:maxdepth = min([s:maxdepth, 100])
bgneal@0: 	let g:ctrlp_builtins = 2
bgneal@0: 	if !empty(s:extensions) | for each in s:extensions
bgneal@0: 		exe 'ru autoload/ctrlp/'.each.'.vim'
bgneal@0: 	endfo | en
bgneal@0: endf
bgneal@0: cal s:opts()
bgneal@0: 
bgneal@0: let s:lash = ctrlp#utils#lash()
bgneal@0: 
bgneal@0: " Global options
bgneal@0: let s:glbs = { 'magic': 1, 'to': 1, 'tm': 0, 'sb': 1, 'hls': 0, 'im': 0,
bgneal@0: 	\ 'report': 9999, 'sc': 0, 'ss': 0, 'siso': 0, 'mfd': 200, 'mouse': 'n',
bgneal@0: 	\ 'gcr': 'a:block-PmenuSel-blinkon0' }
bgneal@0: 
bgneal@0: if s:lazy
bgneal@0: 	cal extend(s:glbs, { 'ut': ( s:lazy > 1 ? s:lazy : 250 ) })
bgneal@0: en
bgneal@0: 
bgneal@0: " Limiters
bgneal@0: let [s:compare_lim, s:nocache_lim, s:mltipats_lim] = [3000, 4000, 2000]
bgneal@0: " * Open & Close {{{1
bgneal@0: fu! s:Open()
bgneal@0: 	let [s:cwd, s:winres] = [getcwd(), winrestcmd()]
bgneal@0: 	let [s:crfile, s:crfpath] = [expand('%:p', 1), expand('%:p:h', 1)]
bgneal@0: 	let [s:crword, s:crline] = [expand('<cword>'), getline('.')]
bgneal@0: 	let [s:tagfiles, s:crcursor] = [s:tagfiles(), getpos('.')]
bgneal@0: 	let [s:crbufnr, s:crvisual] = [bufnr('%'), s:lastvisual()]
bgneal@0: 	let s:currwin = s:mwbottom ? winnr() : winnr() + has('autocmd')
bgneal@0: 	sil! exe s:mwbottom ? 'bo' : 'to' '1new ControlP'
bgneal@0: 	let [s:bufnr, s:prompt] = [bufnr('%'), ['', '', '']]
bgneal@0: 	abc <buffer>
bgneal@0: 	if !exists('s:hstry')
bgneal@0: 		let hst = filereadable(s:gethistloc()[1]) ? s:gethistdata() : ['']
bgneal@0: 		let s:hstry = empty(hst) || !s:maxhst ? [''] : hst
bgneal@0: 	en
bgneal@0: 	for [ke, va] in items(s:glbs)
bgneal@0: 		sil! exe 'let s:glb_'.ke.' = &'.ke.' | let &'.ke.' = '.string(va)
bgneal@0: 	endfo
bgneal@0: 	if s:opmul && has('signs')
bgneal@0: 		sign define ctrlpmark text=+> texthl=Search
bgneal@0: 	en
bgneal@0: 	cal s:setupblank()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:Close()
bgneal@0: 	try | bun! | cat | clo! | endt
bgneal@0: 	cal s:unmarksigns()
bgneal@0: 	for key in keys(s:glbs)
bgneal@0: 		sil! exe 'let &'.key.' = s:glb_'.key
bgneal@0: 	endfo
bgneal@0: 	if exists('s:glb_acd') | let &acd = s:glb_acd | en
bgneal@0: 	let [g:ctrlp_lines, g:ctrlp_allfiles] = [[], []]
bgneal@0: 	exe s:winres
bgneal@0: 	unl! s:focus s:hisidx s:hstgot s:marked s:statypes s:cline s:init s:savestr
bgneal@0: 		\ s:crfile s:crfpath s:crword s:crvisual s:tagfiles s:crline s:crcursor
bgneal@0: 		\ g:ctrlp_nolimit s:crbufnr
bgneal@0: 	cal ctrlp#recordhist()
bgneal@0: 	ec
bgneal@0: endf
bgneal@0: " * Clear caches {{{1
bgneal@0: fu! ctrlp#clr(...)
bgneal@0: 	exe 'let g:ctrlp_new'.( exists('a:1') ? a:1 : 'cache' ).' = 1'
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#clra(...)
bgneal@0: 	if !exists('a:1') && ( has('dialog_gui') || has('dialog_con') ) &&
bgneal@0: 		\ confirm("Delete all cache files?", "&OK\n&Cancel") != 1 | retu | en
bgneal@0: 	let cache_dir = ctrlp#utils#cachedir()
bgneal@0: 	if isdirectory(cache_dir)
bgneal@0: 		let cache_files = split(s:glbpath(cache_dir, '**', 1), "\n")
bgneal@0: 		cal filter(cache_files, '!isdirectory(v:val) && v:val !~ ''\<cache\.txt$''')
bgneal@0: 		sil! cal map(cache_files, 'delete(v:val)')
bgneal@0: 	en
bgneal@0: 	cal ctrlp#clr()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#reset()
bgneal@0: 	if ( has('dialog_gui') || has('dialog_con') ) &&
bgneal@0: 		\ confirm("Reset and apply new options?", "&OK\n&Cancel") != 1 | retu | en
bgneal@0: 	cal s:opts()
bgneal@0: 	cal ctrlp#utils#opts()
bgneal@0: 	cal ctrlp#mrufiles#opts()
bgneal@0: 	unl! s:cline
bgneal@0: endf
bgneal@0: " * Files() {{{1
bgneal@0: fu! s:GlobPath(dirs, allfiles, depth)
bgneal@0: 	let entries = split(globpath(a:dirs, s:glob), "\n")
bgneal@0: 	if !s:folsym
bgneal@0: 		let entries = filter(entries, 'getftype(v:val) != "link"')
bgneal@0: 	en
bgneal@0: 	let g:ctrlp_allfiles = filter(copy(entries), '!isdirectory(v:val)')
bgneal@0: 	let ftrfunc = s:dotfiles ? 'ctrlp#dirfilter(v:val)' : 'isdirectory(v:val)'
bgneal@0: 	let alldirs = filter(entries, ftrfunc)
bgneal@0: 	cal extend(g:ctrlp_allfiles, a:allfiles, 0)
bgneal@0: 	let depth = a:depth + 1
bgneal@0: 	if !empty(alldirs) && !s:maxfiles(len(g:ctrlp_allfiles)) && depth <= s:maxdepth
bgneal@0: 		sil! cal ctrlp#progress(len(g:ctrlp_allfiles))
bgneal@0: 		cal s:GlobPath(join(alldirs, ','), g:ctrlp_allfiles, depth)
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:UserCommand(path, lscmd)
bgneal@0: 	let path = a:path
bgneal@0: 	if exists('+ssl') && &ssl
bgneal@0: 		let [ssl, &ssl, path] = [&ssl, 0, tr(path, '/', '\')]
bgneal@0: 	en
bgneal@0: 	let path = exists('*shellescape') ? shellescape(path) : path
bgneal@0: 	let g:ctrlp_allfiles = split(system(printf(a:lscmd, path)), "\n")
bgneal@0: 	if exists('+ssl') && exists('ssl')
bgneal@0: 		let &ssl = ssl
bgneal@0: 		cal map(g:ctrlp_allfiles, 'tr(v:val, "\\", "/")')
bgneal@0: 	en
bgneal@0: 	if exists('s:vcscmd') && s:vcscmd
bgneal@0: 		cal map(g:ctrlp_allfiles, 'tr(v:val, "/", "\\")')
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:Files()
bgneal@0: 	let [cwd, cache_file] = [getcwd(), ctrlp#utils#cachefile()]
bgneal@0: 	if g:ctrlp_newcache || !filereadable(cache_file) || !s:caching
bgneal@0: 		let lscmd = s:lscommand()
bgneal@0: 		" Get the list of files
bgneal@0: 		if empty(lscmd)
bgneal@0: 			cal s:GlobPath(cwd, [], 0)
bgneal@0: 		el
bgneal@0: 			sil! cal ctrlp#progress('Waiting...')
bgneal@0: 			try | cal s:UserCommand(cwd, lscmd) | cat | retu [] | endt
bgneal@0: 		en
bgneal@0: 		" Remove base directory
bgneal@0: 		cal ctrlp#rmbasedir(g:ctrlp_allfiles)
bgneal@0: 		let read_cache = 0
bgneal@0: 	el
bgneal@0: 		let g:ctrlp_allfiles = ctrlp#utils#readfile(cache_file)
bgneal@0: 		let read_cache = 1
bgneal@0: 	en
bgneal@0: 	if len(g:ctrlp_allfiles) <= s:compare_lim
bgneal@0: 		cal sort(g:ctrlp_allfiles, 'ctrlp#complen')
bgneal@0: 	en
bgneal@0: 	cal s:writecache(read_cache, cache_file)
bgneal@0: 	retu g:ctrlp_allfiles
bgneal@0: endf
bgneal@0: fu! s:Buffers() "{{{1
bgneal@0: 	let allbufs = []
bgneal@0: 	for each in range(1, bufnr('$'))
bgneal@0: 		if getbufvar(each, '&bl') && each != bufnr('#')
bgneal@0: 			let bufname = bufname(each)
bgneal@0: 			if strlen(bufname) && getbufvar(each, '&ma') && bufname != 'ControlP'
bgneal@0: 				cal add(allbufs, fnamemodify(bufname, ':p'))
bgneal@0: 			en
bgneal@0: 		en
bgneal@0: 	endfo
bgneal@0: 	retu allbufs
bgneal@0: endf
bgneal@0: " * MatchedItems() {{{1
bgneal@0: fu! s:MatchIt(items, pat, limit, ispathitem)
bgneal@0: 	let [items, pat, limit, newitems] = [a:items, a:pat, a:limit, []]
bgneal@0: 	let mfunc = s:byfname && a:ispathitem ? 's:matchfname'
bgneal@0: 		\ : s:itemtype > 2 && len(items) < 30000 && !a:ispathitem ? 's:matchtab'
bgneal@0: 		\ : 'match'
bgneal@0: 	for item in items
bgneal@0: 		if call(mfunc, [item, pat]) >= 0 | cal add(newitems, item) | en
bgneal@0: 		if limit > 0 && len(newitems) >= limit | brea | en
bgneal@0: 	endfo
bgneal@0: 	retu newitems
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:MatchedItems(items, pats, limit)
bgneal@0: 	let [items, pats, limit, ipt] = [a:items, a:pats, a:limit, s:ispathitem()]
bgneal@0: 	" If items is longer than s:mltipats_lim, use only the last pattern
bgneal@0: 	if len(items) >= s:mltipats_lim | let pats = [pats[-1]] | en
bgneal@0: 	cal map(pats, 'substitute(v:val, "\\\~", "\\\\\\~", "g")')
bgneal@0: 	if !s:regexp | cal map(pats, 'escape(v:val, ".")') | en
bgneal@0: 	" Loop through the patterns
bgneal@0: 	for each in pats
bgneal@0: 		" If newitems is small, set it as items to search in
bgneal@0: 		if exists('newitems') && len(newitems) < limit
bgneal@0: 			let items = copy(newitems)
bgneal@0: 		en
bgneal@0: 		if empty(items) " End here
bgneal@0: 			retu exists('newitems') ? newitems : []
bgneal@0: 		el " Start here, go back up if have 2 or more in pats
bgneal@0: 			" Loop through the items
bgneal@0: 			let newitems = s:MatchIt(items, each, limit, ipt)
bgneal@0: 		en
bgneal@0: 	endfo
bgneal@0: 	let s:matches = len(newitems)
bgneal@0: 	retu newitems
bgneal@0: endf
bgneal@0: fu! s:SplitPattern(str, ...) "{{{1
bgneal@0: 	let str = s:sanstail(a:str)
bgneal@0: 	if s:migemo && s:regexp && len(str) > 0 && executable('cmigemo')
bgneal@0: 		let dict = s:glbpath(&rtp, printf("dict/%s/migemo-dict", &encoding), 1)
bgneal@0: 		if !len(dict)
bgneal@0: 			let dict = s:glbpath(&rtp, "dict/migemo-dict", 1)
bgneal@0: 		en
bgneal@0: 		if len(dict)
bgneal@0: 			let [tokens, str, cmd] = [split(str, '\s'), '', 'cmigemo -v -w %s -d %s']
bgneal@0: 			for token in tokens
bgneal@0: 				let rtn = system(printf(cmd, shellescape(token), shellescape(dict)))
bgneal@0: 				let str .= !v:shell_error && len(rtn) > 0 ? '.*'.rtn : token
bgneal@0: 			endfo
bgneal@0: 		en
bgneal@0: 	en
bgneal@0: 	let s:savestr = str
bgneal@0: 	if s:regexp || match(str, '\\\(zs\|ze\|<\|>\)\|[*|]') >= 0
bgneal@0: 		let array = [s:regexfilter(str)]
bgneal@0: 	el
bgneal@0: 		let array = split(str, '\zs')
bgneal@0: 		if exists('+ssl') && !&ssl
bgneal@0: 			cal map(array, 'substitute(v:val, "\\", "\\\\\\", "g")')
bgneal@0: 		en
bgneal@0: 		" Literal ^ and $
bgneal@0: 		for each in ['^', '$']
bgneal@0: 			cal map(array, 'substitute(v:val, "\\\'.each.'", "\\\\\\'.each.'", "g")')
bgneal@0: 		endfo
bgneal@0: 	en
bgneal@0: 	" Build the new pattern
bgneal@0: 	let nitem = !empty(array) ? array[0] : ''
bgneal@0: 	let newpats = [nitem]
bgneal@0: 	if len(array) > 1
bgneal@0: 		for item in range(1, len(array) - 1)
bgneal@0: 			" Separator
bgneal@0: 			let sep = exists('a:1') ? a:1 : '[^'.array[item-1].']\{-}'
bgneal@0: 			let nitem .= sep.array[item]
bgneal@0: 			cal add(newpats, nitem)
bgneal@0: 		endfo
bgneal@0: 	en
bgneal@0: 	retu newpats
bgneal@0: endf
bgneal@0: " * BuildPrompt() {{{1
bgneal@0: fu! s:Render(lines, pat)
bgneal@0: 	let lines = a:lines
bgneal@0: 	" Setup the match window
bgneal@0: 	let s:height = min([len(lines), s:mxheight])
bgneal@0: 	sil! exe '%d _ | res' s:height
bgneal@0: 	" Print the new items
bgneal@0: 	if empty(lines)
bgneal@0: 		setl nocul
bgneal@0: 		cal setline(1, ' == NO ENTRIES ==')
bgneal@0: 		cal s:unmarksigns()
bgneal@0: 		if s:dohighlight() | cal clearmatches() | en
bgneal@0: 		retu
bgneal@0: 	en
bgneal@0: 	setl cul
bgneal@0: 	" Sort if not MRU
bgneal@0: 	if ( s:itemtype != 2 && !exists('g:ctrlp_nolimit') )
bgneal@0: 		\ || !empty(join(s:prompt, ''))
bgneal@0: 		let s:compat = a:pat
bgneal@0: 		cal sort(lines, 's:mixedsort')
bgneal@0: 		unl s:compat
bgneal@0: 	en
bgneal@0: 	if s:mwreverse | cal reverse(lines) | en
bgneal@0: 	let s:matched = copy(lines)
bgneal@0: 	cal map(lines, 'substitute(v:val, "^", "> ", "")')
bgneal@0: 	cal setline(1, lines)
bgneal@0: 	exe 'keepj norm!' s:mwreverse ? 'G' : 'gg'
bgneal@0: 	keepj norm! 1|
bgneal@0: 	cal s:unmarksigns()
bgneal@0: 	cal s:remarksigns()
bgneal@0: 	if exists('s:cline') | cal cursor(s:cline, 1) | en
bgneal@0: 	" Highlighting
bgneal@0: 	if s:dohighlight()
bgneal@0: 		cal s:highlight(a:pat, empty(s:mathi[1]) ? 'Identifier' : s:mathi[1])
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:Update(str)
bgneal@0: 	" Get the previous string if existed
bgneal@0: 	let oldstr = exists('s:savestr') ? s:savestr : ''
bgneal@0: 	let pats = s:SplitPattern(a:str)
bgneal@0: 	" Get the new string sans tail
bgneal@0: 	let notail = substitute(a:str, ':\([^:]\|\\:\)*$', '', 'g')
bgneal@0: 	" Stop if the string's unchanged
bgneal@0: 	if notail == oldstr && !empty(notail) && !exists('s:force')
bgneal@0: 		retu
bgneal@0: 	en
bgneal@0: 	let lines = exists('g:ctrlp_nolimit') && empty(notail) ? copy(g:ctrlp_lines)
bgneal@0: 		\ : s:MatchedItems(g:ctrlp_lines, pats, s:mxheight)
bgneal@0: 	cal s:Render(lines, pats[-1])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ForceUpdate()
bgneal@0: 	let [estr, prt] = ['"\', copy(s:prompt)]
bgneal@0: 	cal map(prt, 'escape(v:val, estr)')
bgneal@0: 	cal s:Update(join(prt, ''))
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:BuildPrompt(upd, ...)
bgneal@0: 	let base = ( s:regexp ? 'r' : '>' ).( s:byfname ? 'd' : '>' ).'> '
bgneal@0: 	let [estr, prt] = ['"\', copy(s:prompt)]
bgneal@0: 	cal map(prt, 'escape(v:val, estr)')
bgneal@0: 	let str = join(prt, '')
bgneal@0: 	let lazy = empty(str) || exists('s:force') || !has('autocmd') ? 0 : s:lazy
bgneal@0: 	if a:upd && ( s:matches || s:regexp || match(str, '[*|]') >= 0 ) && !lazy
bgneal@0: 		sil! cal s:Update(str)
bgneal@0: 	en
bgneal@0: 	sil! cal ctrlp#statusline()
bgneal@0: 	" Toggling
bgneal@0: 	let [hiactive, hicursor, base] = exists('a:1') && !a:1
bgneal@0: 		\ ? ['Comment', 'Comment', tr(base, '>', '-')]
bgneal@0: 		\ : ['Normal', 'Constant', base]
bgneal@0: 	let hibase = 'Comment'
bgneal@0: 	" Build it
bgneal@0: 	redr
bgneal@0: 	exe 'echoh' hibase '| echon "'.base.'"
bgneal@0: 		\ | echoh' hiactive '| echon "'.prt[0].'"
bgneal@0: 		\ | echoh' hicursor '| echon "'.prt[1].'"
bgneal@0: 		\ | echoh' hiactive '| echon "'.prt[2].'" | echoh None'
bgneal@0: 	" Append the cursor at the end
bgneal@0: 	if empty(prt[1]) && ( !exists('a:1') || ( exists('a:1') && a:1 ) )
bgneal@0: 		exe 'echoh' hibase '| echon "_" | echoh None'
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " ** Prt Actions {{{1
bgneal@0: " Editing {{{2
bgneal@0: fu! s:PrtClear()
bgneal@0: 	unl! s:hstgot
bgneal@0: 	let [s:prompt, s:matches] = [['', '', ''], 1]
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtAdd(char)
bgneal@0: 	unl! s:hstgot
bgneal@0: 	let s:prompt[0] = s:prompt[0] . a:char
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtBS()
bgneal@0: 	unl! s:hstgot
bgneal@0: 	let [prt, s:matches] = [s:prompt, 1]
bgneal@0: 	let prt[0] = strpart(prt[0], -1, strlen(prt[0]))
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtDelete()
bgneal@0: 	unl! s:hstgot
bgneal@0: 	let [prt, s:matches] = [s:prompt, 1]
bgneal@0: 	let prt[1] = strpart(prt[2], 0, 1)
bgneal@0: 	let prt[2] = strpart(prt[2], 1)
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtDeleteWord()
bgneal@0: 	unl! s:hstgot
bgneal@0: 	let [str, s:matches] = [s:prompt[0], 1]
bgneal@0: 	let str = match(str, '\W\w\+$') >= 0 ? matchstr(str, '^.\+\W\ze\w\+$')
bgneal@0: 		\ : match(str, '\w\W\+$') >= 0 ? matchstr(str, '^.\+\w\ze\W\+$')
bgneal@0: 		\ : match(str, '\s\+$') >= 0 ? matchstr(str, '^.*[^ \t]\+\ze\s\+$')
bgneal@0: 		\ : match(str, ' ') <= 0 ? '' : str
bgneal@0: 	let s:prompt[0] = str
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtInsert(type)
bgneal@0: 	unl! s:hstgot
bgneal@0: 	" Insert current word, search register, last visual and clipboard
bgneal@0: 	let s:prompt[0] .= a:type == 'w' ? s:crword
bgneal@0: 		\ : a:type == 's' ? getreg('/')
bgneal@0: 		\ : a:type == 'v' ? s:crvisual
bgneal@0: 		\ : a:type == '+' ? substitute(getreg('+'), '\n', '\\n', 'g') : s:prompt[0]
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: endf
bgneal@0: " Movement {{{2
bgneal@0: fu! s:PrtCurLeft()
bgneal@0: 	if !empty(s:prompt[0])
bgneal@0: 		let prt = s:prompt
bgneal@0: 		let prt[2] = prt[1] . prt[2]
bgneal@0: 		let prt[1] = strpart(prt[0], strlen(prt[0]) - 1)
bgneal@0: 		let prt[0] = strpart(prt[0], -1, strlen(prt[0]))
bgneal@0: 	en
bgneal@0: 	cal s:BuildPrompt(0)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtCurRight()
bgneal@0: 	let prt = s:prompt
bgneal@0: 	let prt[0] = prt[0] . prt[1]
bgneal@0: 	let prt[1] = strpart(prt[2], 0, 1)
bgneal@0: 	let prt[2] = strpart(prt[2], 1)
bgneal@0: 	cal s:BuildPrompt(0)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtCurStart()
bgneal@0: 	let prt = s:prompt
bgneal@0: 	let str = join(prt, '')
bgneal@0: 	let [prt[0], prt[1], prt[2]] = ['', strpart(str, 0, 1), strpart(str, 1)]
bgneal@0: 	cal s:BuildPrompt(0)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtCurEnd()
bgneal@0: 	let prt = s:prompt
bgneal@0: 	let [prt[0], prt[1], prt[2]] = [join(prt, ''), '', '']
bgneal@0: 	cal s:BuildPrompt(0)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtSelectMove(dir)
bgneal@0: 	exe 'norm!' a:dir
bgneal@0: 	let s:cline = line('.')
bgneal@0: 	if line('$') > winheight(0) | cal s:BuildPrompt(0, s:Focus()) | en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtSelectJump(char, ...)
bgneal@0: 	let lines = copy(s:matched)
bgneal@0: 	if exists('a:1')
bgneal@0: 		cal map(lines, 'split(v:val, ''[\/]\ze[^\/]\+$'')[-1]')
bgneal@0: 	en
bgneal@0: 	" Cycle through matches, use s:jmpchr to store last jump
bgneal@0: 	let chr = escape(a:char, '.~')
bgneal@0: 	if match(lines, '\c^'.chr) >= 0
bgneal@0: 		" If not exists or does but not for the same char
bgneal@0: 		let pos = match(lines, '\c^'.chr)
bgneal@0: 		if !exists('s:jmpchr') || ( exists('s:jmpchr') && s:jmpchr[0] != chr )
bgneal@0: 			let [jmpln, s:jmpchr] = [pos, [chr, pos]]
bgneal@0: 		elsei exists('s:jmpchr') && s:jmpchr[0] == chr
bgneal@0: 			" Start of lines
bgneal@0: 			if s:jmpchr[1] == -1 | let s:jmpchr[1] = pos | en
bgneal@0: 			let npos = match(lines, '\c^'.chr, s:jmpchr[1] + 1)
bgneal@0: 			let [jmpln, s:jmpchr] = [npos == -1 ? pos : npos, [chr, npos]]
bgneal@0: 		en
bgneal@0: 		keepj exe jmpln + 1
bgneal@0: 		let s:cline = line('.')
bgneal@0: 		if line('$') > winheight(0) | cal s:BuildPrompt(0, s:Focus()) | en
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " Misc {{{2
bgneal@0: fu! s:PrtClearCache()
bgneal@0: 	if s:itemtype == 1 | retu | en
bgneal@0: 	if s:itemtype == 0
bgneal@0: 		cal ctrlp#clr()
bgneal@0: 	elsei s:itemtype > 2
bgneal@0: 		cal ctrlp#clr(s:statypes[s:itemtype][1])
bgneal@0: 	en
bgneal@0: 	if s:itemtype == 2
bgneal@0: 		let g:ctrlp_lines = ctrlp#mrufiles#list(-1, 1)
bgneal@0: 	el
bgneal@0: 		cal s:SetLines(s:itemtype)
bgneal@0: 	en
bgneal@0: 	let s:force = 1
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: 	unl s:force
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtDeleteMRU()
bgneal@0: 	if s:itemtype == 2
bgneal@0: 		let s:force = 1
bgneal@0: 		let g:ctrlp_lines = ctrlp#mrufiles#list(-1, 2)
bgneal@0: 		cal s:BuildPrompt(1)
bgneal@0: 		unl s:force
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtExit()
bgneal@0: 	if !has('autocmd') | cal s:Close() | en
bgneal@0: 	exe s:currwin.'winc w'
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtHistory(...)
bgneal@0: 	if !s:maxhst | retu | en
bgneal@0: 	let [str, hst, s:matches] = [join(s:prompt, ''), s:hstry, 1]
bgneal@0: 	" Save to history if not saved before
bgneal@0: 	let [hst[0], hslen] = [exists('s:hstgot') ? hst[0] : str, len(hst)]
bgneal@0: 	let idx = exists('s:hisidx') ? s:hisidx + a:1 : a:1
bgneal@0: 	" Limit idx within 0 and hslen
bgneal@0: 	let idx = idx < 0 ? 0 : idx >= hslen ? hslen > 1 ? hslen - 1 : 0 : idx
bgneal@0: 	let s:prompt = [hst[idx], '', '']
bgneal@0: 	let [s:hisidx, s:hstgot, s:force] = [idx, 1, 1]
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: 	unl s:force
bgneal@0: endf
bgneal@0: "}}}1
bgneal@0: " * MapKeys() {{{1
bgneal@0: fu! s:MapKeys(...)
bgneal@0: 	" Normal keys
bgneal@0: 	let pfunc = exists('a:1') && !a:1 ? 'PrtSelectJump' : 'PrtAdd'
bgneal@0: 	let dojmp = s:byfname && pfunc == 'PrtSelectJump' ? ', 1' : ''
bgneal@0: 	for each in range(32, 126)
bgneal@0: 		let cmd = "nn \<buffer> \<silent> \<char-%d> :\<c-u>cal \<SID>%s(\"%s\"%s)\<cr>"
bgneal@0: 		exe printf(cmd, each, pfunc, escape(nr2char(each), '"|\'), dojmp)
bgneal@0: 	endfo
bgneal@0: 	if exists('a:2') | retu | en
bgneal@0: 	" Special keys
bgneal@0: 	cal call('s:MapSpecs', exists('a:1') && !a:1 ? [1] : [])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:MapSpecs(...)
bgneal@0: 	let [lcmap, prtmaps] = ['nn <buffer> <silent>', {
bgneal@0: 		\ 'PrtBS()':              ['<bs>'],
bgneal@0: 		\ 'PrtDelete()':          ['<del>'],
bgneal@0: 		\ 'PrtDeleteWord()':      ['<c-w>'],
bgneal@0: 		\ 'PrtClear()':           ['<c-u>'],
bgneal@0: 		\ 'PrtSelectMove("j")':   ['<c-j>', '<down>'],
bgneal@0: 		\ 'PrtSelectMove("k")':   ['<c-k>', '<up>'],
bgneal@0: 		\ 'PrtHistory(-1)':       ['<c-n>'],
bgneal@0: 		\ 'PrtHistory(1)':        ['<c-p>'],
bgneal@0: 		\ 'AcceptSelection("e")': ['<cr>', '<2-LeftMouse>'],
bgneal@0: 		\ 'AcceptSelection("h")': ['<c-x>', '<c-cr>', '<c-s>'],
bgneal@0: 		\ 'AcceptSelection("t")': ['<c-t>', '<MiddleMouse>'],
bgneal@0: 		\ 'AcceptSelection("v")': ['<c-v>', '<c-q>', '<RightMouse>'],
bgneal@0: 		\ 'ToggleFocus()':        ['<tab>'],
bgneal@0: 		\ 'ToggleRegex()':        ['<c-r>'],
bgneal@0: 		\ 'ToggleByFname()':      ['<c-d>'],
bgneal@0: 		\ 'ToggleType(1)':        ['<c-f>', '<c-up'],
bgneal@0: 		\ 'ToggleType(-1)':       ['<c-b>', '<c-down>'],
bgneal@0: 		\ 'PrtInsert("w")':       ['<F2>'],
bgneal@0: 		\ 'PrtInsert("s")':       ['<F3>'],
bgneal@0: 		\ 'PrtInsert("v")':       ['<F4>'],
bgneal@0: 		\ 'PrtInsert("+")':       ['<F6>'],
bgneal@0: 		\ 'PrtCurStart()':        ['<c-a>'],
bgneal@0: 		\ 'PrtCurEnd()':          ['<c-e>'],
bgneal@0: 		\ 'PrtCurLeft()':         ['<c-h>', '<left>'],
bgneal@0: 		\ 'PrtCurRight()':        ['<c-l>', '<right>'],
bgneal@0: 		\ 'PrtClearCache()':      ['<F5>'],
bgneal@0: 		\ 'PrtDeleteMRU()':       ['<F7>'],
bgneal@0: 		\ 'CreateNewFile()':      ['<c-y>'],
bgneal@0: 		\ 'MarkToOpen()':         ['<c-z>'],
bgneal@0: 		\ 'OpenMulti()':          ['<c-o>'],
bgneal@0: 		\ 'PrtExit()':            ['<esc>', '<c-c>', '<c-g>'],
bgneal@0: 		\ }]
bgneal@0: 	if type(s:urprtmaps) == 4
bgneal@0: 		cal extend(prtmaps, s:urprtmaps)
bgneal@0: 	en
bgneal@0: 	" Correct arrow keys in terminal
bgneal@0: 	if ( has('termresponse') && !empty(v:termresponse) )
bgneal@0: 		\ || &term =~? 'xterm\|\<k\?vt\|gnome\|screen'
bgneal@0: 		for each in ['\A <up>','\B <down>','\C <right>','\D <left>']
bgneal@0: 			exe lcmap.' <esc>['.each
bgneal@0: 		endfo
bgneal@0: 	en
bgneal@0: 	if exists('a:1')
bgneal@0: 		let prtunmaps = [
bgneal@0: 			\ 'PrtBS()',
bgneal@0: 			\ 'PrtDelete()',
bgneal@0: 			\ 'PrtDeleteWord()',
bgneal@0: 			\ 'PrtClear()',
bgneal@0: 			\ 'PrtCurStart()',
bgneal@0: 			\ 'PrtCurEnd()',
bgneal@0: 			\ 'PrtCurLeft()',
bgneal@0: 			\ 'PrtCurRight()',
bgneal@0: 			\ 'PrtHistory(-1)',
bgneal@0: 			\ 'PrtHistory(1)',
bgneal@0: 			\ 'PrtInsert("w")',
bgneal@0: 			\ 'PrtInsert("s")',
bgneal@0: 			\ 'PrtInsert("v")',
bgneal@0: 			\ 'PrtInsert("+")',
bgneal@0: 			\ ]
bgneal@0: 		for ke in prtunmaps | for kp in prtmaps[ke]
bgneal@0: 			exe lcmap kp '<Nop>'
bgneal@0: 		endfo | endfo
bgneal@0: 	el
bgneal@0: 		for [ke, va] in items(prtmaps) | for kp in va
bgneal@0: 			exe lcmap kp ':<c-u>cal <SID>'.ke.'<cr>'
bgneal@0: 		endfo | endfo
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " * Toggling {{{1
bgneal@0: fu! s:Focus()
bgneal@0: 	retu !exists('s:focus') ? 1 : s:focus
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ToggleFocus()
bgneal@0: 	let s:focus = !exists('s:focus') || s:focus ? 0 : 1
bgneal@0: 	cal s:MapKeys(s:focus)
bgneal@0: 	cal s:BuildPrompt(0, s:focus)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ToggleRegex()
bgneal@0: 	let s:regexp = s:regexp ? 0 : 1
bgneal@0: 	cal s:PrtSwitcher()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ToggleByFname()
bgneal@0: 	if s:ispathitem()
bgneal@0: 		let s:byfname = s:byfname ? 0 : 1
bgneal@0: 		cal s:MapKeys(s:Focus(), 1)
bgneal@0: 		cal s:PrtSwitcher()
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ToggleType(dir)
bgneal@0: 	let ext = exists('g:ctrlp_ext_vars') ? len(g:ctrlp_ext_vars) : 0
bgneal@0: 	let s:itemtype = s:walker(g:ctrlp_builtins + ext, s:itemtype, a:dir)
bgneal@0: 	let s:extid = s:itemtype - ( g:ctrlp_builtins + 1 )
bgneal@0: 	unl! g:ctrlp_nolimit
bgneal@0: 	cal s:SetLines(s:itemtype)
bgneal@0: 	cal s:PrtSwitcher()
bgneal@0: 	if s:itemtype > 2
bgneal@0: 		if exists('g:ctrlp_ext_vars['.s:extid.'][4][0]')
bgneal@0: 			let g:ctrlp_nolimit = g:ctrlp_ext_vars[s:extid][4][0]
bgneal@0: 		en
bgneal@0: 	el
bgneal@0: 		cal s:syntax()
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:PrtSwitcher()
bgneal@0: 	let [s:force, s:matches] = [1, 1]
bgneal@0: 	cal s:BuildPrompt(1, s:Focus())
bgneal@0: 	unl s:force
bgneal@0: endf
bgneal@0: fu! s:SetWD(...) "{{{1
bgneal@0: 	let pathmode = s:pathmode
bgneal@0: 	if exists('a:1') && len(a:1) | if type(a:1)
bgneal@0: 		cal ctrlp#setdir(a:1) | retu
bgneal@0: 	el
bgneal@0: 		let pathmode = a:1
bgneal@0: 	en | en
bgneal@0: 	if !exists('a:2')
bgneal@0: 		if match(s:crfile, '^\<.\+\>://.*') >= 0 || !pathmode | retu | en
bgneal@0: 		if exists('+acd') | let [s:glb_acd, &acd] = [&acd, 0] | en
bgneal@0: 		cal ctrlp#setdir(s:crfpath)
bgneal@0: 	en
bgneal@0: 	if pathmode == 1 | retu | en
bgneal@0: 	let markers = ['root.dir','.git/','.hg/','.vimprojects','_darcs/','.bzr/']
bgneal@0: 	if type(s:rmarkers) == 3 && !empty(s:rmarkers)
bgneal@0: 		cal extend(markers, s:rmarkers, 0)
bgneal@0: 	en
bgneal@0: 	for marker in markers
bgneal@0: 		cal s:findroot(getcwd(), marker, 0, 0)
bgneal@0: 		if exists('s:foundroot') | brea | en
bgneal@0: 	endfo
bgneal@0: 	unl! s:foundroot
bgneal@0: endf
bgneal@0: " * AcceptSelection() {{{1
bgneal@0: fu! ctrlp#acceptfile(mode, matchstr, ...)
bgneal@0: 	let [md, matchstr] = [a:mode, a:matchstr]
bgneal@0: 	" Get the full path
bgneal@0: 	let filpath = s:itemtype ? matchstr : getcwd().s:lash.matchstr
bgneal@0: 	cal s:PrtExit()
bgneal@0: 	let bufnum = bufnr(filpath)
bgneal@0: 	if s:jmptobuf && bufnum > 0 && md == 'e'
bgneal@0: 		let [jmpb, bufwinnr] = [1, bufwinnr(bufnum)]
bgneal@0: 		let buftab = s:jmptobuf > 1 ? s:buftab(bufnum) : [0, 0]
bgneal@0: 		let j2l = a:0 ? a:1 : str2nr(matchstr(s:tail(), '^ +\zs\d\+$'))
bgneal@0: 	en
bgneal@0: 	" Switch to existing buffer or open new one
bgneal@0: 	if exists('jmpb') && buftab[0]
bgneal@0: 		exe 'tabn' buftab[1]
bgneal@0: 		exe buftab[0].'winc w'
bgneal@0: 		if j2l | cal s:j2l(j2l) | en
bgneal@0: 	elsei exists('jmpb') && bufwinnr > 0
bgneal@0: 		exe bufwinnr.'winc w'
bgneal@0: 		if j2l | cal s:j2l(j2l) | en
bgneal@0: 	el
bgneal@0: 		" Determine the command to use
bgneal@0: 		let cmd = md == 't' || s:splitwin == 1 ? 'tabe'
bgneal@0: 			\ : md == 'h' || s:splitwin == 2 ? 'new'
bgneal@0: 			\ : md == 'v' || s:splitwin == 3 ? 'vne' : ctrlp#normcmd('e')
bgneal@0: 		" Open new window/buffer
bgneal@0: 		cal call('s:openfile', a:0 ? [cmd, filpath, ' +'.a:1] : [cmd, filpath])
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:AcceptSelection(mode)
bgneal@0: 	if a:mode == 'e' | if s:specinputs() | retu | en | en
bgneal@0: 	" Get the selected line
bgneal@0: 	let matchstr = matchstr(getline('.'), '^> \zs.\+\ze\t*$')
bgneal@0: 	if empty(matchstr) | retu | en
bgneal@0: 	" Do something with it
bgneal@0: 	let actfunc = s:itemtype =~ '0\|1\|2' ? 'ctrlp#acceptfile'
bgneal@0: 		\ : g:ctrlp_ext_vars[s:itemtype - ( g:ctrlp_builtins + 1 )][1]
bgneal@0: 	cal call(actfunc, [a:mode, matchstr])
bgneal@0: endf
bgneal@0: fu! s:CreateNewFile() "{{{1
bgneal@0: 	let str = join(s:prompt, '')
bgneal@0: 	if empty(str) | retu | en
bgneal@0: 	let str = s:sanstail(str)
bgneal@0: 	let arr = split(str, '[\/]')
bgneal@0: 	let fname = remove(arr, -1)
bgneal@0: 	if len(arr) | if isdirectory(s:createparentdirs(arr))
bgneal@0: 		let optyp = str
bgneal@0: 	en | el
bgneal@0: 		let optyp = fname
bgneal@0: 	en
bgneal@0: 	if exists('optyp')
bgneal@0: 		let filpath = getcwd().s:lash.optyp
bgneal@0: 		cal s:insertcache(str)
bgneal@0: 		cal s:PrtExit()
bgneal@0: 		let cmd = s:newfop == 1 ? 'tabe'
bgneal@0: 			\ : s:newfop == 2 ? 'new'
bgneal@0: 			\ : s:newfop == 3 ? 'vne' : ctrlp#normcmd('e')
bgneal@0: 		cal s:openfile(cmd, filpath)
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " * OpenMulti() {{{1
bgneal@0: fu! s:MarkToOpen()
bgneal@0: 	if s:bufnr <= 0 || !s:opmul || s:itemtype > g:ctrlp_builtins | retu | en
bgneal@0: 	let matchstr = matchstr(getline('.'), '^> \zs.\+\ze\t*$')
bgneal@0: 	if empty(matchstr) | retu | en
bgneal@0: 	let filpath = s:itemtype ? matchstr : getcwd().s:lash.matchstr
bgneal@0: 	if exists('s:marked') && s:dictindex(s:marked, filpath) > 0
bgneal@0: 		" Unmark and remove the file from s:marked
bgneal@0: 		let key = s:dictindex(s:marked, filpath)
bgneal@0: 		cal remove(s:marked, key)
bgneal@0: 		if empty(s:marked) | unl! s:marked | en
bgneal@0: 		if has('signs')
bgneal@0: 			exe 'sign unplace' key 'buffer='.s:bufnr
bgneal@0: 		en
bgneal@0: 	el
bgneal@0: 		" Add to s:marked and place a new sign
bgneal@0: 		if exists('s:marked')
bgneal@0: 			let vac = s:vacantdict(s:marked)
bgneal@0: 			let key = empty(vac) ? len(s:marked) + 1 : vac[0]
bgneal@0: 			let s:marked = extend(s:marked, { key : filpath })
bgneal@0: 		el
bgneal@0: 			let [key, s:marked] = [1, { 1 : filpath }]
bgneal@0: 		en
bgneal@0: 		if has('signs')
bgneal@0: 			exe 'sign place' key 'line='.line('.').' name=ctrlpmark buffer='.s:bufnr
bgneal@0: 		en
bgneal@0: 	en
bgneal@0: 	sil! cal ctrlp#statusline()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:OpenMulti()
bgneal@0: 	if !exists('s:marked') || !s:opmul
bgneal@0: 		cal s:AcceptSelection('e')
bgneal@0: 		retu
bgneal@0: 	en
bgneal@0: 	let mkd = s:marked
bgneal@0: 	cal s:PrtExit()
bgneal@0: 	" Try not to open a new tab
bgneal@0: 	let [ntab, norwins] = [0, s:normbuf()]
bgneal@0: 	if empty(norwins) | let ntab = 1 | el
bgneal@0: 		for each in norwins
bgneal@0: 			let bufnr = winbufnr(each)
bgneal@0: 			if !empty(bufname(bufnr)) && !empty(getbufvar(bufnr, '&ft'))
bgneal@0: 				\ && bufname(bufnr) != 'ControlP'
bgneal@0: 				let ntab = 1
bgneal@0: 			en
bgneal@0: 		endfo
bgneal@0: 		if !ntab | let wnr = min(norwins) | en
bgneal@0: 	en
bgneal@0: 	if ntab | tabnew | en
bgneal@0: 	let [ic, wnr] = [1, exists('wnr') ? wnr : 1]
bgneal@0: 	let cmds = { 'v': 'vne', 'h': 'new', 't': 'tabe' }
bgneal@0: 	let spt = len(s:opmul) > 1 ? cmds[matchstr(s:opmul, '\w$')] : 'vne'
bgneal@0: 	let nr = matchstr(s:opmul, '^\d\+')
bgneal@0: 	exe wnr.'winc w'
bgneal@0: 	for [ke, va] in items(mkd)
bgneal@0: 		let cmd = ic == 1 ? 'e' : spt
bgneal@0: 		cal s:openfile(cmd, va)
bgneal@0: 		if nr > 1 && nr < ic | clo! | el | let ic += 1 | en
bgneal@0: 	endfo
bgneal@0: endf
bgneal@0: " ** Helper functions {{{1
bgneal@0: " Sorting {{{2
bgneal@0: fu! ctrlp#complen(s1, s2)
bgneal@0: 	" By length
bgneal@0: 	let [len1, len2] = [strlen(a:s1), strlen(a:s2)]
bgneal@0: 	retu len1 == len2 ? 0 : len1 > len2 ? 1 : -1
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:compmatlen(s1, s2)
bgneal@0: 	" By match length
bgneal@0: 	let mln1 = s:shortest(s:matchlens(a:s1, s:compat))
bgneal@0: 	let mln2 = s:shortest(s:matchlens(a:s2, s:compat))
bgneal@0: 	retu mln1 == mln2 ? 0 : mln1 > mln2 ? 1 : -1
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:comptime(s1, s2)
bgneal@0: 	" By last modified time
bgneal@0: 	let [time1, time2] = [getftime(a:s1), getftime(a:s2)]
bgneal@0: 	retu time1 == time2 ? 0 : time1 < time2 ? 1 : -1
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:comparent(s1, s2)
bgneal@0: 	" By same parent dir
bgneal@0: 	if match(s:crfpath, escape(getcwd(), '.^$*\')) >= 0
bgneal@0: 		let [as1, as2] = [getcwd().s:lash.a:s1, getcwd().s:lash.a:s2]
bgneal@0: 		let [loc1, loc2] = [s:getparent(as1), s:getparent(as2)]
bgneal@0: 		if loc1 == s:crfpath && loc2 != s:crfpath | retu -1 | en
bgneal@0: 		if loc2 == s:crfpath && loc1 != s:crfpath | retu 1  | en
bgneal@0: 		retu 0
bgneal@0: 	en
bgneal@0: 	retu 0
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:matchlens(str, pat, ...)
bgneal@0: 	if empty(a:pat) || index(['^','$'], a:pat) >= 0 | retu {} | en
bgneal@0: 	let st   = exists('a:1') ? a:1 : 0
bgneal@0: 	let lens = exists('a:2') ? a:2 : {}
bgneal@0: 	let nr   = exists('a:3') ? a:3 : 0
bgneal@0: 	if match(a:str, a:pat, st) != -1
bgneal@0: 		let [mst, mnd] = [matchstr(a:str, a:pat, st), matchend(a:str, a:pat, st)]
bgneal@0: 		let lens = extend(lens, { nr : [len(mst), mst] })
bgneal@0: 		let lens = s:matchlens(a:str, a:pat, mnd, lens, nr + 1)
bgneal@0: 	en
bgneal@0: 	retu lens
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:shortest(lens)
bgneal@0: 	retu min(map(values(a:lens), 'v:val[0]'))
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:mixedsort(s1, s2)
bgneal@0: 	let [cml, cln] = [s:compmatlen(a:s1, a:s2), ctrlp#complen(a:s1, a:s2)]
bgneal@0: 	if s:itemtype < 3 && s:height < 51
bgneal@0: 		let par = s:comparent(a:s1, a:s2)
bgneal@0: 		if s:height < 21
bgneal@0: 			retu 6 * cml + 3 * par + 2 * s:comptime(a:s1, a:s2) + cln
bgneal@0: 		en
bgneal@0: 		retu 3 * cml + 2 * par + cln
bgneal@0: 	en
bgneal@0: 	retu 2 * cml + cln
bgneal@0: endf
bgneal@0: " Statusline {{{2
bgneal@0: fu! ctrlp#statusline(...)
bgneal@0: 	if !exists('s:statypes')
bgneal@0: 		let s:statypes = [
bgneal@0: 			\ ['files', 'fil'],
bgneal@0: 			\ ['buffers', 'buf'],
bgneal@0: 			\ ['mru files', 'mru'],
bgneal@0: 			\ ]
bgneal@0: 		if exists('g:ctrlp_ext_vars')
bgneal@0: 			cal map(copy(g:ctrlp_ext_vars), 'add(s:statypes, [ v:val[2], v:val[3] ])')
bgneal@0: 		en
bgneal@0: 	en
bgneal@0: 	let tps = s:statypes
bgneal@0: 	let max = len(tps) - 1
bgneal@0: 	let nxt = tps[s:walker(max, s:itemtype,  1)][1]
bgneal@0: 	let prv = tps[s:walker(max, s:itemtype, -1)][1]
bgneal@0: 	let item = tps[s:itemtype][0]
bgneal@0: 	let focus   = s:Focus() ? 'prt'  : 'win'
bgneal@0: 	let byfname = s:byfname ? 'file' : 'path'
bgneal@0: 	let regex   = s:regexp  ? '%#LineNr# regex %*' : ''
bgneal@0: 	let focus   = '%#LineNr# '.focus.' %*'
bgneal@0: 	let byfname = '%#Character# '.byfname.' %*'
bgneal@0: 	let item    = '%#Character# '.item.' %*'
bgneal@0: 	let slider  = ' <'.prv.'>={'.item.'}=<'.nxt.'>'
bgneal@0: 	let dir     = ' %=%<%#LineNr# '.getcwd().' %*'
bgneal@0: 	let marked = s:opmul ? exists('s:marked') ? ' <'.s:dismrk().'>' : ' <+>' : ''
bgneal@0: 	let &l:stl = focus.byfname.regex.slider.marked.dir
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:dismrk()
bgneal@0: 	retu has('signs') ? '+'.len(s:marked) :
bgneal@0: 		\ '%<'.join(values(map(copy(s:marked), 'split(v:val, "[\\/]")[-1]')), ', ')
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#progress(len)
bgneal@0: 	if has('macunix') || has('mac') | sl 1m | en
bgneal@0: 	let &l:stl = '%#Function# '.a:len.' %* %=%<%#LineNr# '.getcwd().' %*'
bgneal@0: 	redr
bgneal@0: endf
bgneal@0: " Paths {{{2
bgneal@0: fu! ctrlp#dirfilter(val)
bgneal@0: 	retu isdirectory(a:val) && match(a:val, '[\/]\.\{,2}$') < 0 ? 1 : 0
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:ispathitem()
bgneal@0: 	let ext = s:itemtype - ( g:ctrlp_builtins + 1 )
bgneal@0: 	if s:itemtype < 3 || ( s:itemtype > 2 && g:ctrlp_ext_vars[ext][3] == 'dir' )
bgneal@0: 		retu 1
bgneal@0: 	en
bgneal@0: 	retu 0
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#rmbasedir(items)
bgneal@0: 	let path = &ssl || !exists('+ssl') ? getcwd().'/' :
bgneal@0: 		\ substitute(getcwd(), '\\', '\\\\', 'g').'\\'
bgneal@0: 	retu map(a:items, 'substitute(v:val, path, "", "g")')
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:parentdir(curr)
bgneal@0: 	let parent = s:getparent(a:curr)
bgneal@0: 	if parent != a:curr | cal ctrlp#setdir(parent) | en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:getparent(item)
bgneal@0: 	retu split(a:item, '[\/]\ze[^\/]\+[\/:]\?$')[0]
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:getgrand(item)
bgneal@0: 	retu split(a:item, '[\/]\ze[^\/]\+[\/][^\/]\+[\/:]\?$')[0]
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:createparentdirs(arr)
bgneal@0: 	for each in a:arr
bgneal@0: 		let curr = exists('curr') ? curr.s:lash.each : each
bgneal@0: 		cal ctrlp#utils#mkdir(curr)
bgneal@0: 	endfo
bgneal@0: 	retu curr
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:listdirs(path, parent)
bgneal@0: 	let [str, dirs] = ['', split(s:glbpath(a:path, '*', 1), "\n")]
bgneal@0: 	for entry in filter(dirs, 'isdirectory(v:val)')
bgneal@0: 		let str .= a:parent . split(entry, '[\/]')[-1] . "\n"
bgneal@0: 	endfo
bgneal@0: 	retu str
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#cpl(A, L, P)
bgneal@0: 	let haslash = match(a:A, '[\/]')
bgneal@0: 	let parent = substitute(a:A, '[^\/]*$', '', 'g')
bgneal@0: 	let path = !haslash ? parent : haslash > 0 ? getcwd().s:lash.parent : getcwd()
bgneal@0: 	retu s:listdirs(path, parent)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:findroot(curr, mark, depth, type)
bgneal@0: 	let [depth, notfound] = [a:depth + 1, empty(s:glbpath(a:curr, a:mark, 1))]
bgneal@0: 	if !notfound || depth > s:maxdepth
bgneal@0: 		if notfound | cal ctrlp#setdir(s:cwd) | en
bgneal@0: 		if a:type
bgneal@0: 			let s:vcsroot = depth <= s:maxdepth ? a:curr : ''
bgneal@0: 		el
bgneal@0: 			cal ctrlp#setdir(a:curr)
bgneal@0: 			let s:foundroot = 1
bgneal@0: 		en
bgneal@0: 	el
bgneal@0: 		let parent = s:getparent(a:curr)
bgneal@0: 		if parent != a:curr | cal s:findroot(parent, a:mark, depth, a:type) | en
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:glbpath(...)
bgneal@0: 	retu call('globpath',  v:version > 701 ? a:000 : a:000[:1])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#fnesc(path)
bgneal@0: 	retu exists('*fnameescape') ? fnameescape(a:path) : escape(a:path, " %#*?|<\"\n")
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#setdir(path, ...)
bgneal@0: 	let cmd = exists('a:1') ? a:1 : 'lc!'
bgneal@0: 	try
bgneal@0: 		exe cmd.' '.ctrlp#fnesc(a:path)
bgneal@0: 	cat
bgneal@0: 		cal ctrlp#msg("Can't change working dir. Directory not exists.")
bgneal@0: 	endt
bgneal@0: endf
bgneal@0: " Highlighting {{{2
bgneal@0: fu! s:syntax()
bgneal@0: 	sy match CtrlPNoEntries '^ == NO ENTRIES ==$'
bgneal@0: 	sy match CtrlPLineMarker '^>'
bgneal@0: 	hi link CtrlPNoEntries Error
bgneal@0: 	hi CtrlPLineMarker guifg=bg
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:highlight(pat, grp)
bgneal@0: 	cal clearmatches()
bgneal@0: 	if !empty(a:pat) && a:pat != '..' && s:itemtype < 3
bgneal@0: 		let pat = substitute(a:pat, '\~', '\\~', 'g')
bgneal@0: 		if !s:regexp | let pat = escape(pat, '.') | en
bgneal@0: 		" Match only filename
bgneal@0: 		if s:byfname
bgneal@0: 			let pat = substitute(pat, '\[\^\(.\{-}\)\]\\{-}', '[^\\/\1]\\{-}', 'g')
bgneal@0: 			let pat = substitute(pat, '$', '\\ze[^\\/]*$', 'g')
bgneal@0: 		en
bgneal@0: 		cal matchadd(a:grp, '\c'.pat)
bgneal@0: 		cal matchadd('CtrlPLineMarker', '^>')
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:dohighlight()
bgneal@0: 	retu type(s:mathi) == 3 && len(s:mathi) == 2 && s:mathi[0]
bgneal@0: 		\ && exists('*clearmatches')
bgneal@0: endf
bgneal@0: " Prompt history {{{2
bgneal@0: fu! s:gethistloc()
bgneal@0: 	let cache_dir = ctrlp#utils#cachedir().s:lash.'hist'
bgneal@0: 	retu [cache_dir, cache_dir.s:lash.'cache.txt']
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:gethistdata()
bgneal@0: 	retu ctrlp#utils#readfile(s:gethistloc()[1])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#recordhist()
bgneal@0: 	let str = join(s:prompt, '')
bgneal@0: 	if empty(str) || !s:maxhst | retu | en
bgneal@0: 	let hst = s:hstry
bgneal@0: 	if len(hst) > 1 && hst[1] == str | retu | en
bgneal@0: 	cal extend(hst, [str], 1)
bgneal@0: 	if len(hst) > s:maxhst | cal remove(hst, s:maxhst, -1) | en
bgneal@0: endf
bgneal@0: " Signs {{{2
bgneal@0: fu! s:unmarksigns()
bgneal@0: 	if !s:dosigns() | retu | en
bgneal@0: 	for key in keys(s:marked)
bgneal@0: 		exe 'sign unplace' key 'buffer='.s:bufnr
bgneal@0: 	endfo
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:remarksigns()
bgneal@0: 	if !s:dosigns() | retu | en
bgneal@0: 	let nls = s:matched
bgneal@0: 	for ic in range(1, len(nls))
bgneal@0: 		let filpath = s:itemtype ? nls[ic - 1] : getcwd().s:lash.nls[ic - 1]
bgneal@0: 		let key = s:dictindex(s:marked, filpath)
bgneal@0: 		if key > 0
bgneal@0: 			exe 'sign place' key 'line='.ic.' name=ctrlpmark buffer='.s:bufnr
bgneal@0: 		en
bgneal@0: 	endfo
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:dosigns()
bgneal@0: 	retu exists('s:marked') && s:bufnr > 0 && s:opmul && has('signs')
bgneal@0: endf
bgneal@0: " Dictionaries {{{2
bgneal@0: fu! s:dictindex(dict, expr)
bgneal@0: 	for key in keys(a:dict)
bgneal@0: 		if a:dict[key] == a:expr | retu key | en
bgneal@0: 	endfo
bgneal@0: 	retu -1
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:vacantdict(dict)
bgneal@0: 	retu filter(range(1, max(keys(a:dict))), '!has_key(a:dict, v:val)')
bgneal@0: endf
bgneal@0: " Buffers {{{2
bgneal@0: fu! s:buftab(bufnum)
bgneal@0: 	for nr in range(1, tabpagenr('$'))
bgneal@0: 		let buflist = tabpagebuflist(nr)
bgneal@0: 		if match(buflist, a:bufnum) >= 0
bgneal@0: 			let [buftabnr, tabwinnrs] = [nr, tabpagewinnr(nr, '$')]
bgneal@0: 			for ewin in range(1, tabwinnrs)
bgneal@0: 				if buflist[ewin - 1] == a:bufnum
bgneal@0: 					retu [ewin, buftabnr]
bgneal@0: 				en
bgneal@0: 			endfo
bgneal@0: 		en
bgneal@0: 	endfo
bgneal@0: 	retu [0, 0]
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:normbuf()
bgneal@0: 	let winnrs = []
bgneal@0: 	for each in range(1, winnr('$'))
bgneal@0: 		let bufnr = winbufnr(each)
bgneal@0: 		if getbufvar(bufnr, '&bl') && empty(getbufvar(bufnr, '&bt'))
bgneal@0: 			\ && getbufvar(bufnr, '&ma')
bgneal@0: 			cal add(winnrs, each)
bgneal@0: 		en
bgneal@0: 	endfo
bgneal@0: 	retu winnrs
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#normcmd(cmd)
bgneal@0: 	if !empty(s:nosplit) && match([bufname('%'), &l:ft], s:nosplit) >= 0
bgneal@0: 		retu a:cmd
bgneal@0: 	en
bgneal@0: 	" Find a regular buffer
bgneal@0: 	let norwins = s:normbuf()
bgneal@0: 	let norwin = empty(norwins) ? 0 : norwins[0]
bgneal@0: 	if norwin
bgneal@0: 		if index(norwins, winnr()) < 0
bgneal@0: 			exe norwin.'winc w'
bgneal@0: 		en
bgneal@0: 		retu a:cmd
bgneal@0: 	en
bgneal@0: 	retu 'bo vne'
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:setupblank()
bgneal@0: 	setl noswf nobl nonu nowrap nolist nospell nocuc wfh
bgneal@0: 	setl fdc=0 fdl=99 tw=0 bt=nofile bh=unload
bgneal@0: 	if v:version >= 703
bgneal@0: 		setl nornu noudf cc=0
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:leavepre()
bgneal@0: 	if s:clrex && ( !has('clientserver') ||
bgneal@0: 		\ ( has('clientserver') && len(split(serverlist(), "\n")) == 1 ) )
bgneal@0: 		cal ctrlp#clra(1)
bgneal@0: 	en
bgneal@0: 	cal ctrlp#utils#writecache(s:hstry, s:gethistloc()[0], s:gethistloc()[1])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:checkbuf()
bgneal@0: 	if exists('s:init') | retu | en
bgneal@0: 	if exists('s:bufnr') && s:bufnr > 0
bgneal@0: 		exe s:bufnr.'bw!'
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " Arguments {{{2
bgneal@0: fu! s:tail()
bgneal@0: 	if exists('s:optail') && !empty('s:optail')
bgneal@0: 		let tailpref = match(s:optail, '^\s*+') < 0 ? ' +' : ' '
bgneal@0: 		retu tailpref.s:optail
bgneal@0: 	en
bgneal@0: 	retu ''
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:sanstail(str)
bgneal@0: 	" Restore the number of backslashes
bgneal@0: 	let str = substitute(a:str, '\\\\', '\', 'g')
bgneal@0: 	unl! s:optail
bgneal@0: 	if match(str, ':\([^:]\|\\:\)*$') >= 0
bgneal@0: 		let s:optail = matchstr(str, ':\zs\([^:]\|\\:\)*$')
bgneal@0: 		retu substitute(str, ':\([^:]\|\\:\)*$', '', 'g')
bgneal@0: 	en
bgneal@0: 	retu str
bgneal@0: endf
bgneal@0: " Misc {{{2
bgneal@0: fu! s:specinputs()
bgneal@0: 	let str = join(s:prompt, '')
bgneal@0: 	let type = s:itemtype > 2 ?
bgneal@0: 		\ g:ctrlp_ext_vars[s:itemtype - ( g:ctrlp_builtins + 1 )][3] : s:itemtype
bgneal@0: 	if str == '..' && type =~ '0\|dir'
bgneal@0: 		cal s:parentdir(getcwd())
bgneal@0: 		cal s:SetLines(s:itemtype)
bgneal@0: 		cal s:PrtClear()
bgneal@0: 		retu 1
bgneal@0: 	elsei ( str == '/' || str == '\' ) && type =~ '0\|dir'
bgneal@0: 		cal s:SetWD(2, 0)
bgneal@0: 		cal s:SetLines(s:itemtype)
bgneal@0: 		cal s:PrtClear()
bgneal@0: 		retu 1
bgneal@0: 	elsei str == '?'
bgneal@0: 		cal s:PrtExit()
bgneal@0: 		let hlpwin = &columns > 159 ? '| vert res 80' : ''
bgneal@0: 		sil! exe 'bo vert h ctrlp-mappings' hlpwin '| norm! 0'
bgneal@0: 		retu 1
bgneal@0: 	en
bgneal@0: 	retu 0
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:lastvisual()
bgneal@0: 	let cview = winsaveview()
bgneal@0: 	let [ovreg, ovtype] = [getreg('v'), getregtype('v')]
bgneal@0: 	let [oureg, outype] = [getreg('"'), getregtype('"')]
bgneal@0: 	sil! norm! gv"vy
bgneal@0: 	let selected = substitute(getreg('v'), '\n', '\\n', 'g')
bgneal@0: 	cal setreg('v', ovreg, ovtype)
bgneal@0: 	cal setreg('"', oureg, outype)
bgneal@0: 	cal winrestview(cview)
bgneal@0: 	retu selected
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#msg(msg)
bgneal@0: 	echoh Identifier | echon "CtrlP: ".a:msg | echoh None
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:openfile(cmd, filpath, ...)
bgneal@0: 	let cmd = a:cmd == 'e' && &modified ? 'hid e' : a:cmd
bgneal@0: 	let tail = a:0 ? a:1 : s:tail()
bgneal@0: 	try
bgneal@0: 		exe cmd.tail.' '.ctrlp#fnesc(a:filpath)
bgneal@0: 	cat
bgneal@0: 		cal ctrlp#msg("Operation can't be completed. Make sure filename is valid.")
bgneal@0: 	fina
bgneal@0: 		if !empty(tail)
bgneal@0: 			sil! norm! zOzz
bgneal@0: 		en
bgneal@0: 	endt
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:writecache(read_cache, cache_file)
bgneal@0: 	if !a:read_cache && ( ( g:ctrlp_newcache || !filereadable(a:cache_file) )
bgneal@0: 		\ && s:caching || len(g:ctrlp_allfiles) > s:nocache_lim )
bgneal@0: 		if len(g:ctrlp_allfiles) > s:nocache_lim | let s:caching = 1 | en
bgneal@0: 		cal ctrlp#utils#writecache(g:ctrlp_allfiles)
bgneal@0: 	en
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:j2l(nr)
bgneal@0: 	exe a:nr
bgneal@0: 	sil! norm! zOzz
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:regexfilter(str)
bgneal@0: 	let str = a:str
bgneal@0: 	let pats = {
bgneal@0: 		\ '^\(\\|\)\|\(\\|\)$': '\\|',
bgneal@0: 		\ '^\\\(zs\|ze\|<\|>\)': '^\\\(zs\|ze\|<\|>\)',
bgneal@0: 		\ '^\S\*$': '\*',
bgneal@0: 		\ '^\S\\?$': '\\?',
bgneal@0: 		\ }
bgneal@0: 	for key in keys(pats) | if match(str, key) >= 0
bgneal@0: 		let str = substitute(str, pats[key], '', 'g')
bgneal@0: 	en | endfo
bgneal@0: 	retu str
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:walker(max, pos, dir)
bgneal@0: 	retu a:dir > 0 ? a:pos < a:max ? a:pos + 1 : 0 : a:pos > 0 ? a:pos - 1 : a:max
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:matchfname(item, pat)
bgneal@0: 	retu match(split(a:item, '[\/]\ze[^\/]\+$')[-1], a:pat)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:matchtab(item, pat)
bgneal@0: 	retu match(split(a:item, '\t\+[^\t]\+$')[0], a:pat)
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:maxfiles(len)
bgneal@0: 	retu s:maxfiles && a:len > s:maxfiles ? 1 : 0
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:insertcache(str)
bgneal@0: 	let [data, g:ctrlp_newcache, str] = [g:ctrlp_allfiles, 1, a:str]
bgneal@0: 	if strlen(str) <= strlen(data[0])
bgneal@0: 		let pos = 0
bgneal@0: 	elsei strlen(str) >= strlen(data[-1])
bgneal@0: 		let pos = len(data) - 1
bgneal@0: 	el
bgneal@0: 		let pos = 0
bgneal@0: 		for each in data
bgneal@0: 			if strlen(each) > strlen(str) | brea | en
bgneal@0: 			let pos += 1
bgneal@0: 		endfo
bgneal@0: 	en
bgneal@0: 	cal insert(data, str, pos)
bgneal@0: 	cal s:writecache(0, ctrlp#utils#cachefile())
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! s:lscommand()
bgneal@0: 	let cmd = s:usrcmd
bgneal@0: 	if type(cmd) == 1
bgneal@0: 		retu cmd
bgneal@0: 	elsei type(cmd) == 3 && len(cmd) >= 2 && !empty(cmd[0]) && !empty(cmd[1])
bgneal@0: 		let rmarker = cmd[0]
bgneal@0: 		" Find a repo root
bgneal@0: 		cal s:findroot(getcwd(), rmarker, 0, 1)
bgneal@0: 		if !exists('s:vcsroot') || ( exists('s:vcsroot') && empty(s:vcsroot) )
bgneal@0: 			" Try the secondary_command
bgneal@0: 			retu len(cmd) == 3 ? cmd[2] : ''
bgneal@0: 		en
bgneal@0: 		let s:vcscmd = s:lash == '\' ? 1 : 0
bgneal@0: 		retu cmd[1]
bgneal@0: 	en
bgneal@0: endf
bgneal@0: " Extensions {{{2
bgneal@0: fu! s:tagfiles()
bgneal@0: 	retu filter(map(tagfiles(), 'fnamemodify(v:val, ":p")'), 'filereadable(v:val)')
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#exit()
bgneal@0: 	cal s:PrtExit()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#prtclear()
bgneal@0: 	cal s:PrtClear()
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#setlines(type)
bgneal@0: 	cal s:SetLines(a:type)
bgneal@0: endf
bgneal@0: "}}}1
bgneal@0: " * Initialization {{{1
bgneal@0: fu! s:SetLines(type)
bgneal@0: 	let s:itemtype = a:type
bgneal@0: 	let types = [
bgneal@0: 		\ 's:Files()',
bgneal@0: 		\ 's:Buffers()',
bgneal@0: 		\ 'ctrlp#mrufiles#list(-1)',
bgneal@0: 		\ ]
bgneal@0: 	if exists('g:ctrlp_ext_vars')
bgneal@0: 		cal map(copy(g:ctrlp_ext_vars), 'add(types, v:val[0])')
bgneal@0: 	en
bgneal@0: 	let g:ctrlp_lines = eval(types[a:type])
bgneal@0: endf
bgneal@0: 
bgneal@0: fu! ctrlp#init(type, ...)
bgneal@0: 	if exists('s:init') | retu | en
bgneal@0: 	let [s:matches, s:init] = [1, 1]
bgneal@0: 	cal s:Open()
bgneal@0: 	cal s:SetWD(exists('a:1') ? a:1 : '')
bgneal@0: 	cal s:MapKeys()
bgneal@0: 	cal s:SetLines(a:type)
bgneal@0: 	cal s:BuildPrompt(1)
bgneal@0: 	if has('syntax') && exists('g:syntax_on')
bgneal@0: 		cal s:syntax()
bgneal@0: 	en
bgneal@0: endf
bgneal@0: if has('autocmd') "{{{1
bgneal@0: 	aug CtrlPAug
bgneal@0: 		au!
bgneal@0: 		au BufEnter ControlP cal s:checkbuf()
bgneal@0: 		au BufLeave ControlP cal s:Close()
bgneal@0: 		au VimLeavePre * cal s:leavepre()
bgneal@0: 		if s:lazy
bgneal@0: 			au CursorHold ControlP cal s:ForceUpdate()
bgneal@0: 		en
bgneal@0: 	aug END
bgneal@0: en "}}}
bgneal@0: 
bgneal@0: " vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2