/* Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include #include "../include/readline.h" std::list > rl_commands; ReadLine::ReadLine(const std::string & prompt, const std::string & name) : prompt(prompt), bad(false) { if (name.length() > 0) rl_readline_name = name.c_str(); this->setCompleter(&ReadLine::completer); } void ReadLine::RegisterFunction(const std::string & cmd, rl_icpfunc_t * completer, const std::string & help) { boost::tuple tmp(cmd, completer, help); rl_commands.push_back(tmp); } std::string ReadLine::GetPrompt() const { return this->prompt; } void ReadLine::SetPrompt(const std::string & prompt) { this->prompt = prompt; } char ** ReadLine::completer(const char * text, int start, int end) { return (start == 0) ? rl_completion_matches(text, &ReadLine::command_generator) : (char **)NULL; } char * ReadLine::command_generator(const char * text, int state) { static std::list >::const_iterator index; std::string name(text); if (!state) index = rl_commands.begin(); if (index++ != rl_commands.end() && name.length() <= boost::get<0>(*index).length() && strncmp(name.c_str(), boost::get<0>(*index).c_str(), name.length()) == 0) return const_cast(name.c_str()); return (char *)NULL; } void ReadLine::setCompleter(char ** (* completer)(const char *, int, int)) { rl_attempted_completion_function = completer; } std::string ReadLine::GetLine() { std::string tmp = ""; char * line = readline(this->prompt.c_str()); if (!line) this->bad = true; else tmp = std::string(line); int i; for (i = 0; tmp[i] && whitespace(tmp[i]); ++i); add_history(tmp.substr(i).c_str()); return tmp.substr(i); } bool ReadLine::Bad() const { return this->bad; } rl_icpfunc_t * ReadLine::GetFunction(const std::string & line) { using namespace boost; using namespace std; int i; for (i = 0; line[i] && !whitespace(line[i]); ++i); string cmd = line.substr(0, i); for (list >::iterator j = rl_commands.begin(); j != rl_commands.end(); ++j) if (cmd == get<0>(*j)) return get<1>(*j); return (rl_icpfunc_t *)NULL; } void ReadLine::PrintHelp() const { using namespace boost; using namespace std; for (list >::const_iterator i = rl_commands.begin(); i != rl_commands.end(); ++i) cout << get<0>(*i) << ": " << get<2>(*i) << endl; return; }