Created
November 12, 2012 18:28
-
-
Save ralphbean/4061003 to your computer and use it in GitHub Desktop.
Half-working filename tab-completer. Play with it--it mostly works, but you have to help it along more than you're used to at the command line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import readline | |
import os | |
import re | |
from pprint import * | |
# This will tab-complete from the working directory, starting from /, and going through the sub-directories, | |
# but it doesn't behave quite the way you expect. | |
# For instance, it chooses for you if there are two partial matches. | |
# The readline call to def complete does not pass a | |
# leading "/" in the "text" variable, so I had to start using get_line_buffer and really don't find | |
# much use for the variables "text" and "state". | |
# Isn't there a "right" way to do this? It seems like it ought to be a built-in in readline! | |
# Not sure what RE_SPACE is for. | |
RE_SPACE = re.compile('.*\s+$', re.M) | |
COMMANDS = os.listdir('.') | |
def complete(text, state): | |
line = readline.get_line_buffer().split() | |
# NOTE THAT THE LEADING / WILL NOT COME THROUGH IN text. | |
try: | |
if line == []: | |
path = "." | |
COMMANDS = os.listdir(path) | |
elif line[0] == "/": # Readline will never return a leading "/". | |
COMMANDS = os.listdir("/") | |
elif line == "" or line == "." or line == "./": | |
path = "." | |
COMMANDS = os.listdir(path) | |
else: | |
if "/" in line[0]: | |
if line[0] == "/": | |
base_path = "/" | |
else: | |
base_path = line[0].rsplit("/",1)[0] + "/" | |
partial_file_name = line[0].rsplit("/")[-1] | |
else: | |
base_path = "." | |
partial_file_name = line[0] | |
COMMANDS = os.listdir(base_path) | |
for one_file in COMMANDS: | |
if one_file.startswith(partial_file_name): | |
if not state: | |
return one_file | |
except: | |
print "exception" | |
COMMANDS = os.listdir(".") | |
for one_file in COMMANDS: | |
if one_file.startswith(text) and state == 0: | |
return one_file | |
else: | |
state -= 1 | |
readline.parse_and_bind("tab: complete") | |
readline.set_completer(complete) | |
while True: | |
file_name = raw_input('Enter filename: ') | |
print file_name | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a new working version in good shape on gist https://gist.github.com/4040404/ with credits in the comments.