Skip to content

Instantly share code, notes, and snippets.

@holzschu
Created January 11, 2018 08:11
Show Gist options
  • Save holzschu/4d42b7ef9bb427b7b0a5843f6ae5b90b to your computer and use it in GitHub Desktop.
Save holzschu/4d42b7ef9bb427b7b0a5843f6ae5b90b to your computer and use it in GitHub Desktop.
Sample complete callback for linenoise (https://github.com/antirez/linenoise)
// Array of all commands available:
NSArray* commandList;
// Commands that don't take a file as argument (uname, ssh, mosh...):
NSArray* commandsNoFile;
void completion(const char *command, linenoiseCompletions *lc) {
// autocomplete command for lineNoise
BOOL isDir;
NSString* commandString = [NSString stringWithUTF8String:command];
if ([commandString rangeOfString:@" "].location == NSNotFound) {
// No spaces. The user is typing a command
for (NSString* existingCommand in commandList) {
if ([existingCommand hasPrefix:commandString]) linenoiseAddCompletion(lc, existingCommand.UTF8String);
}
} else {
// the user is typing an argument.
// Is this one the commands that want a file as an argument?
NSArray* commandArray = [commandString componentsSeparatedByString:@" "];
if ([commandsNoFile containsObject:commandArray[0]]) return;
// Last position of space in the command.
// Would be better if I could get position of cursor.
NSString* argument = commandArray.lastObject;
// which directory?
BOOL isDir;
NSString* directory;
NSString *file;
if ([[NSFileManager defaultManager] fileExistsAtPath:argument isDirectory:&isDir] && isDir) {
directory = argument;
file = @"";
} else {
directory = [argument stringByDeletingLastPathComponent]; // can be empty.
if (directory.length == 0) directory = @".";
file = [argument lastPathComponent];
}
directory = [directory stringByExpandingTildeInPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:directory isDirectory:&isDir] && isDir) {
NSArray* filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directory error:Nil];
for (NSString *fileName in filenames) {
if ((file.length == 0) || [fileName hasPrefix:file]) {
NSString* addition = [fileName substringFromIndex:[file length]];
NSString * newCommand = [commandString stringByAppendingString:addition];
linenoiseAddCompletion(lc,[newCommand UTF8String]);
}
}
}
}
}
// use with:
- (int)main:(int)argc argv:(char **)argv
{
// ...
linenoiseSetCompletionCallback(completion);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment