-- source file picker
vis:command_register('pick', function(argv, force, win, selection, range)
	local depth = 1
	local addendum = ''
	for i, arg in ipairs(argv) do
		if (i == 1) then
			depth = tonumber(arg) + 1
		end
		if (i == 2) then
			addendum = arg
		end
	end
	--vis:info("was command forced with ! "..(force and "yes" or "no"))
	--vis:info(win.file:content(range.start, range.finish - range.start))
	local path = win.file.path
	if not path then
		vis:info('file not yet named')
		return false;
	end
	local pickerresult, pickerstdout = vis:pipe(
		win.file, 
		range,
		'dirname $(readlink -f '..win.file.path..')'
	)
	--vis:info(pickerresult..' ('..pickerstdout..')');
	if (pickerresult ~= 0) then
		vis:info('error at finding root directory of current file (shell returned'..pickerresult..')')
	end
	-- somehow removes leading and trailing whitespace characters lmao
	pickerstdout = pickerstdout:gsub("^%s*(.-)%s*$", "%1")
	while depth > 1 do
		pickerstdout = pickerstdout..'/..'
		depth = depth - 1
	end
	--vis:info(pickerstdout)
	
	pickerresult, pickerstdout = vis:pipe(
		win.file,
		range,
		'find '..pickerstdout..' -iname "*$(cat)*'..addendum..'" -type f | head -1'
	)
	if (pickerresult ~= 0) then
		vis:info('error at finding matching file (shell returned'..pickerresult..')')
		return false;
	end
	if not pickerstdout then
		vis:info('search returned no matches at current depth ('..depth..')')
		return true;
	end
	vis:info(pickerstdout..' (error code '..pickerresult..')')
	if (force) then
		vis:command('open '..pickerstdout)
	end
	return true;
	end, 'Open the first filename that matches the selection,\
                                 per default at a depth of 1, will only display filematch\
                                 unless force is specified (!)\
                                 depth and trailing match characters can be specified\
                                 as parameters `:pick [<depth> [<addendum>]]`'
)

vis:command_register('pickf', function(argv)
	vis:command('pick! '..table.concat(argv, ' '))
	end, ':pick! [<depth> [<addendum>]]'
)
