Get relative path to file

1 Point

Sergey Vlasov Sergey Vlasov

10 years ago

Unlike :. filename-modifier, this also works for files that aren't under pwd. Can be used in statusline, like so:

set statusline+=%{RelativePathString(expand('%:p'))}
fu! RelativePathString(file)
	if strlen(a:file) == 0
		retu "[No Name]"
	en
	let common = getcwd()
	let result = ""
	while substitute(a:file, common, '', '') ==# a:file
		let common = fnamemodify(common, ':h')
		let result = ".." . (empty(result) ? '' : '/' . result)
	endw
	let forward = substitute(a:file, common, '', '')
	if !empty(result) && !empty(forward)
		retu result . forward
	elsei !empty(forward)
		retu forward[1:]
	en
endf