##// END OF EJS Templates
find prefix with regex
Matthias BUSSONNIER -
Show More
@@ -32,25 +32,29 b' from kill_ring import QtKillRing'
32 # Functions
32 # Functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 ESCAPE_CHARS = ''.join(ESC_SEQUENCES)
36 ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+")
37
35 def commonprefix(items):
38 def commonprefix(items):
36 """Given a list of pathnames, returns the longest common leading component
39 """Get common prefix for completions
37
40
38 Same function as os.path.commonprefix, but don't considere prefix made of
41 Return the longest common prefix of a list of strings, but with special
39 special caracters like #!$%... see
42 treatment of escape characters that might precede commands in IPython,
43 such as %magic functions. Used in tab completion.
40
44
41 IPython.core.inputsplitter import ESC_SEQUENCES
45 For a more general function, see os.path.commonprefix
42 """
46 """
43 # the last item will always have the least leading % symbol
47 # the last item will always have the least leading % symbol
44 prefixes = ''.join(ESC_SEQUENCES)
45 get_prefix = lambda x : x[0:-len(x.lstrip(prefixes))]
46 # min / max are first/last in alphabetical order
48 # min / max are first/last in alphabetical order
47 first_prefix = get_prefix(min(items))
49 first_match = ESCAPE_RE.match(min(items))
48 last_prefix = get_prefix(max(items))
50 last_match = ESCAPE_RE.match(max(items))
49
50 # common suffix is (common prefix of reversed items) reversed
51 # common suffix is (common prefix of reversed items) reversed
51 prefix = os.path.commonprefix((first_prefix[::-1], last_prefix[::-1]))[::-1]
52 if first_match and last_match:
53 prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
54 else:
55 prefix = ''
52
56
53 items = [ s.lstrip(prefixes) for s in items ]
57 items = [s.lstrip(ESCAPE_CHARS) for s in items]
54 return prefix+os.path.commonprefix(items)
58 return prefix+os.path.commonprefix(items)
55
59
56 def is_letter_or_number(char):
60 def is_letter_or_number(char):
General Comments 0
You need to be logged in to leave comments. Login now