// $Id: cmd.cpp,v 1.1 2014/09/24 06:39:16 querbach Exp $

// cmd.cpp			   Copyright (C) 2009, Real-Time Systems Inc.
//-------------------------------------------- All Rights Reserved ----------
//
//	Command-Line Interface
//
//---------------------------------------------------------------------------

#include "new.h"
#include "minmax.h"
#include "cmd.h"


// Show prompt and get a command line from the input stream with simple line
// editing and playback or editing of the previous command.

#define ctl(c) ((c) & 0x1F)

bool CmdBuf::fill()
{
  // Show prompt.

  os << prompt << flush;

  // Collect response.
  
  char* bp = line;			// current character
  char* ep = &line[sizeof(line)];	// end of input area

  bool done = false;
  while (!done)
  {
    if (is.rdbuf()->in_avail() == 0)	// flush when no more input available
      os.flush();

    int c = is.get();
    switch (c)
    {
      case ctl('H'):  case 0x7F:	// backspace/delete
        if (bp > line)
        {
          --bp;
          os << "\b \b";
        }
        break;
        
      case ctl('X'):			// line erase
        while (bp > line)
        {
          --bp;
          os << "\b \b";
        }
        break;
        
      case ctl('E'):			// edit previous command
        while (*bp)
          os << *bp++;
        break;
        
      case ctl('R'):			// repeat command
        while (*bp)
          os << *bp++;
          // fall through
          
      case '\r':  case '\n':		// end input
        pendNL = true;
        done = true;
        break;

      case EOF:				// EOF from input stream
        if (bp == line)
          return false;
        os << endl;
        done = true;
        break;
        
      default:				// all other characters
        if (isprint(c) && bp < ep)
          os << (*bp++ = c);
        break;
    }
    *bp = 0;				// terminate after each change
  }
  
  // Set string stream up for parsers.

  new (&iss) istrstream(line, strlen(line));
  return true;
}

