Skip to content

Instantly share code, notes, and snippets.

@matutter
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save matutter/cfd2b5c33e472183f37f to your computer and use it in GitHub Desktop.

Select an option

Save matutter/cfd2b5c33e472183f37f to your computer and use it in GitHub Desktop.
terminal emulator... in a terminal?
#include <iostream>
#include <unistd.h>
#include <termios.h>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
char getch() {
char buf = 0;
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror ("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
return (buf);
}
void run( string cmd )
{
cout << endl;
//cout << "cmd: " << cmd << endl;
}
void clear( vector<string>::iterator it )
{
cout << "\r";
for (int i = 0; i < (*it).size() + 2; ++i)
cout << " ";
cout << "\r";
}
void backspace( vector<string>::iterator it )
{
if( (*it).size() == 0 ) return;
(*it).resize( (*it).size() - 1 );
}
int main(int argc, char const *argv[])
{
cout << "..." << endl;
char c = 0
, l;
vector<string> history;
history.push_back( string("") );
static vector<string>::iterator it = history.begin();
do
{
l = c;
c = getch();
switch( c )
{
case '\n':
cout << endl;
run( *it );
history.push_back( *it );
history.back();
it = history.begin();
history.front() = "";
break;
case 'q':
if( l == 'q' ) continue;
cout << "\rType 'q' again to quit. " << endl;
cout << *it << flush;
break;
case 0x7f:
backspace( it );
break;
default:
if( l == '[' && c == 'A' )
{
backspace( it );
if( it != history.end() -1 )
it++;
}
else if( l == '[' && c == 'B' )
{
backspace( it );
if( it != history.begin() )
it--;
}
else if( isprint(c) )
{
(*it).append<char>(1,c);
}
}
clear( it );
cout << "\r" << *it << flush;
} while( c != 'q' || l != 'q' );
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment