/**********************************************************************/
/*                                                                    */
/*	CRISP - Programmable editor                                   */
/*	===========================                                   */
/*                                                                    */
/*  File:          key.cr                                             */
/*  Author:        P. D. Fox                                          */
/*  Created:       3 Jun 1991                      		      */
/*                                                                    */
/*  Copyright (c) 1990, 1991 Paul Fox                                 */
/*                All Rights Reserved.                                */
/*                                                                    */
/*                                                                    */
/*--------------------------------------------------------------------*/
/*  Description:  Macro to enter a key description                    */
/*                                                                    */
/*   This  macro  allows  the user to hit a key on the keyboard, and  */
/*   either  insert  it  literally  into  the  buffer  in the format  */
/*   wanted by the assign_to_key() macro, or get help on the key.     */
/**********************************************************************/

/* SCCS ID: %Z% %M% %R%.%L% */
# include	"crisp.h"

void
key()
{	string	kseq = "";
	string	rseq = "";
	string	buf;
	int	internal_keycode = 0;
	int	ch;
	
	while (1) {
		message("Press key: %s", kseq);
		if ((ch = read_char(kseq == "" ? 0 : 250, TRUE)) < 0)
			break;
		/***********************************************/
		/*   If  top  bits  are  set  then  we have a  */
		/*   16-bit  keycode  so  we can stop at this  */
		/*   point.				       */
		/***********************************************/
		if (ch & ~0xff) {
			internal_keycode = ch;
			break;
			}
		/***********************************************/
		/*   Remember  the  raw  sequence  as well as  */
		/*   the insertable sequence.		       */
		/***********************************************/
		sprintf(buf, "%c", ch);
		rseq += buf;
		/***********************************************/
		/*   Remember  the  insertable sequence which  */
		/*   needs    the   backslashed   unprintable  */
		/*   characters.			       */
		/***********************************************/
		if (ch < ' ')
			sprintf(buf, "\\x%02x", ch);
		else
			sprintf(buf, "%c", ch);
		kseq += buf;
		}
	message("<Ins> to insert or <Enter> for help: ");
	ch = read_char();
	if (ch == key_to_int("<Ins>")) {
		if (internal_keycode)
			insert("\"" + int_to_key(internal_keycode) + "\"");
		else
			insert("\"" + kseq + "\"");
		return;
		}
	if (ch == key_to_int("<Esc>"))
		return;
	if (internal_keycode)
		explain(inq_assignment(int_to_key(internal_keycode)));
	else
		explain(inq_assignment(key_to_int(rseq, 1)));
}
