1# Copyright (C) 2011-2019 Patrick Totzke <patricktotzke@gmail.com> 2# This file is released under the GNU GPL, version 3 or a later revision. 3# For further details see the COPYING file 4 5import glob 6import os 7from .completer import Completer 8 9 10class PathCompleter(Completer): 11 """Completes for file system paths.""" 12 13 def complete(self, original, pos): 14 if not original: 15 return [('~/', 2)] 16 prefix = os.path.expanduser(original[:pos]) 17 18 def escape(path): 19 """Escape all backslashes and spaces in path with a backslash. 20 21 :param path: the path to escape 22 :type path: str 23 :returns: the escaped path 24 :rtype: str 25 """ 26 return path.replace('\\', '\\\\').replace(' ', r'\ ') 27 28 def deescape(escaped_path): 29 """Remove escaping backslashes in front of spaces and backslashes. 30 31 :param escaped_path: a path potentially with escaped spaces and 32 backslashs 33 :type escaped_path: str 34 :returns: the actual path 35 :rtype: str 36 """ 37 return escaped_path.replace('\\ ', ' ').replace('\\\\', '\\') 38 39 def prep(path): 40 escaped_path = escape(path) 41 return escaped_path, len(escaped_path) 42 43 return [prep(g) for g in glob.glob(deescape(prefix) + '*')] 44