%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% async shell for jed
!if (is_defined ("Shell_Default_Shell"))
{
#ifdef WIN32
   variable Shell_Default_Shell = getenv ("COMSPEC");
   if (Shell_Default_Shell == NULL)
     Shell_Default_Shell = "cmd.exe";
#else   
   variable Shell_Default_Shell = getenv ("SHELL");
   if (Shell_Default_Shell == NULL)
     Shell_Default_Shell = "sh";
#endif
}

!if (is_defined ("Shell_Default_Interactive_Shell"))
{
#ifdef WIN32
   variable Shell_Default_Interactive_Shell = "";
#else   
   variable Shell_Default_Interactive_Shell = "-i";
#endif  
}

variable AShell_Id = -1;

define ashell_send_input ()
{
   variable buf;
   variable this_line, mark_line;
   variable m, ch, prompt;

   m = process_mark (AShell_Id);

   this_line = what_line ();
   push_mark ();
   goto_user_mark (m);
   mark_line = what_line ();

   if (this_line >= mark_line)
     {
	pop_mark_0 ();
	push_mark_eob ();
	buf = bufsubstr ();
     }
   else
     {
	bskip_chars ("\t ");
	push_mark ();
	!if (bolp ())
	  {
	     go_left_1 ();
	     ch = what_char ();
	  }
	bol ();
	prompt = bufsubstr ();
	pop_mark_1 ();
	bol ();
	if (looking_at (prompt))
	  {
	     go_right (strlen (prompt));
	  }
	else if (ffind_char (ch))
	  {
	     go_right_1 ();
	  }
	push_mark_eol ();
	buf = bufsubstr ();
	eob ();
	insert (buf);
     }
   newline ();
   move_user_mark (m);
#ifdef WIN32
   send_process (AShell_Id, buf + "\n\r");
#else   
   send_process (AShell_Id, buf + "\n");
#endif
}

define ashell_send_intr ()
{
   signal_process (AShell_Id, 2);
}

$1 = "AShellMap";
!if (keymap_p ($1)) make_keymap ($1);
definekey ("ashell_send_input", "^M", $1);
undefinekey ("^C", $1);
definekey ("ashell_send_intr", "^C", $1);

define ashell_signal_handler (pid, flags, status)
{
   variable msg;

   eob ();
   msg = aprocess_stringify_status (pid, flags, status);
   vinsert ("\n\n----- %s ------\n\n", msg);
   AShell_Id = -1;
}

define ashell_insert_output (pid, str)
{
   eob ();
   push_spot ();
   insert (str);
   pop_spot ();
   bol ();
   replace ("\r", Null_String);
   eob ();
   move_user_mark (process_mark (pid));
}

   
define ashell ()
{
   variable buf = "*ashell*";
   variable arg, nargs = 0;

   if ((AShell_Id != -1) and bufferp (buf))
     {
	error ("Currently, only one shell process is supported.");
     }

   pop2buf (buf);
   use_keymap ("AShellMap");
   run_mode_hooks ("ashell_mode_hook");
   erase_buffer ();
#iffalse
   AShell_Id = open_process (Shell_Default_Shell, 
			     Shell_Default_Interactive_Shell, 1);
#else
   % parse possible arguments
   forever
     {
	arg = extract_element (Shell_Default_Shell, nargs, ' ');
	if (arg == NULL)
	  break;

	nargs++;
	arg;		% push on stack
     }

   Shell_Default_Interactive_Shell; nargs;% push on stack  
   AShell_Id = open_process ();
#endif
   set_process (AShell_Id, "signal", "ashell_signal_handler");
   set_process (AShell_Id, "output", "ashell_insert_output");
}
