[net.sources] VT220 function keys

ken@ektools.UUCP (Kenneth J. Lester) (11/06/85)

What follows is a program which  loads the  function keys  of a VT220
terminal with user defined strings.   It  has been  tested in 4.2bsd,
but  I  don't  guarantee,  warrant,  and  etc.   the functionality or
fitness of the code.  

It was recently submitted to the net by :
	Barry Shein, Boston University 
	root%bostonu.csnet@CSNET-RELAY.ARPA (BostonU SysMgr)

I  have  made "improvements"  and the  source is  different enough to
repost the entire code, rather than the diffs.  

"IMPROVEMENTS" :-)

	1) the program can read an initialization file
	2) the program will set the VT220 in the VT200 mode
	3) the program uses getopt (not include)

I also wrote a man page, and makefile,  which I've  included.  Lastly
the  program  name  has  been  changed  to vt220  rather than key220.
Sorry, Barry ...  I found vt220 easier to  remember (it  stares at me
daily!)  

I've found the program very useful, and wish  to thank  Barry for 
posting the original version.  

		Ken Lester
		{seismo, allegra}!rochester!kodak!ektools!ken


------------------------- CUT HERE --------------------------------
# This is a shell archive.  Remove anything before this line, then
# unpack it by saving it in a file and typing "sh file".  (Files
# unpacked will be owned by you and have default permissions.)
#
# This archive contains:
# vt220.1 Makefile vt220.c

echo x - vt220.1
cat > "vt220.1" << '//E*O*F vt220.1//'
.TH VT220 1 
.UC 4
.SH NAME
vt220 \- define SHIFTED function keys on VT220 terminal
.SH SYNTAX
.B vt220
[
.B \-cil
]
[ keyname keystring ] ...
.SH DESCRIPTION
.I Vt220
sets up a "vt220 terminal" in vt200 mode to allow user
definition of the SHIFTED function keys. Each
\f2keyname\f1 specified on the command line will be loaded with
the corresponding \f2keystring\f1.  
A \f2keyname\f1 is one of the  following "words":
F6 F7 F8 F9 F10 F11 ESC F12 BS F13 LF F14 HELP DO F17 F18 F19 F20.  
\f2Keystrings\f1
must be quoted if spaces, tabs, or shell metacharacters are included. 
.PP
.B Vt220
expects to receive some combination of option flags and/or 
argument pair(s), otherwised an usage message
is printed.
.PP
The options are:
.TP
.B \-c 
Clears all SHIFTED function key definitions before setting them to user
defined strings.
.TP
.B \-i
Read the initialization file 
.I $HOME/.vt220rc
for SHIFTED function key definitions.  This is done before any
argument pair specified on the command line is processed.
Each line in the file must consist of two fields (separated by spaces
or tabs) where the first field is the 
\f2keyname\f1 and the second field is the \f2keystring\f1.
The second field extends to the end of the line, thus a
\f2keystring\f1
may include spaces or tabs.  A newline (return) may be specified
within the string by using the C Language notation for newline (\\n).
.TP
.B \-l 
Locks the function keys from further definition.  
Locking occurs after processing the initialization file (if the "i"
option is specified) and any argument
pairs.
The only way
to unlock is by turning the power off.
.SH EXAMPLES
vt220 -ci
.br
vt220 F6 'nroff -ms '
.br
vt220 -i F20 'cc -O -c '
.br
vt220 -l HELP man
.SH "OTHER FEATURES"
Pressing the function keys without using the shift key, generates
a string of characters.  With
\f2csh\f1(1) this string can be aliased to some command.  For example:
.br
	alias ^[[17~ "ls -CR | more"
.br
where ^[[17~ is what is generated by pressing the F6 key.  Therefore
F6 can perform two commands, depending if pressed with/without the SHIFT
key.
.PP
.B Vt220
can be called from your .login or .profile file.  Typically an user
will create a initialization file and include a line like
.br
	vt220 -ci
.br
OR
.br
	vt220 -cil
.br
in the above mentioned files.  This way the SHIFTED function keys
will be set to your favorite commands when logging in.
.SH CAVEATS
If the SHIFTED function keys are unlocked, redefinition of a SHIFTED 
function key will rewrite the old string.
.PP
There are 256 bytes available for the SHIFTED function keys.  Space is 
supplied on a first-come/first-serve basis.  After the 256 bytes are
used, you can't define any more keys unless space is cleared.  This
can be done by redefining a key to contain a string of fewer bytes. 
.PP
All key definitions are stored in volatile RAM, and are lost when
terminal power is lost.
.PP
The ESC key (unshifted) no longer generates the proper escape character.  This
is of particular importance since many editors require use  of the
ESC key.  Here are some available alternatives:
.sp
.in +.5i
The escape character can be generated by typing ^[ (control-[).
.sp
Use 
.B vt220
as follows (note ^[ is control-[)
.br
.in +.5i
vt220 ESC '^['  
.in
.br
This will require you
to press the SHIFT key and ESC to generate the escape sequence.
.sp
Some editors, allow other character(s) to be substituted for the 
escape character. For example with 
.B emacs
include this line in your .emacs_pro:
.br
    (bind-to-key "ESC-prefix" "\\033[23~")
.br
Thus when the ESC key is pressed, emacs will allow the characters
generated (^[[23~) to perform the same function as the escape
character.
.in
.SH FILES
$HOME/.vt220rc	\- initialization file
.SH "SEE ALSO"
VT220 Programmer Reference Manual
.br
VT220 Programmer Pocket Guide

//E*O*F vt220.1//

echo x - Makefile
cat > "Makefile" << '//E*O*F Makefile//'
all: vt220

vt220: vt220.o getopt.o
	cc -o vt220 -O vt220.o getopt.o

vt220.o: vt220.c
	cc -c -O vt220.c

getopt.o: getopt.c
	cc -c -O getopt.c
//E*O*F Makefile//

echo x - vt220.c
cat > "vt220.c" << '//E*O*F vt220.c//'
/*
 *      Trivial program to load VT220 Function keys with strings,
 *      note that the values only get sent when the key is shifted
 *      (shoulda been an option to flip the shift set like the Z19!)
 *
 *      Typing no args gives help, basically pairs of keyname/value
 *      strings.
 *
 *      Author, Author: Barry Shein, Boston University
 * 
 * HISTORY
  {1}   30-Oct-85  Kenneth J. Lester (ken) at ektools

        Added the necessary code to read an initialization file.  This
        should make it easier to used this program.  Also added code
        that will set-up the terminal in vt200 (this saves the user the
        trouble of checking if the set-up is in vt200). 
        
        Restructed  the  main  function  to  use   getopt,  for  argument
        processing.  
        
        Alterated usage function  to include  new "i"  option (init file)
 
*/

#include <stdio.h>
#include <ctype.h>

/*
 *      The default toupper() macro is stupid, will toupper anything
 */

#ifdef toupper(c)
#undef toupper(c)
#endif
#define toupper(c) (islower(c) ? ((c)-' ') : c)

#define VT200_7BIT 1
#define ESC 033
#define INITFILE ".vt220rc"

struct keynames {
  char *name ;
  char *string ;
} keys[] = {
  "F6", "17",
  "F7", "18",
  "F8", "19",
  "F9", "20",
  "F10", "21",
  "F11", "23",
  "ESC", "23",
  "F12", "24",
  "BS", "24",
  "F13", "25",
  "LF", "25",
  "F14", "26",
  "HELP", "28",
  "DO", "29",
  "F17", "31",
  "F18", "32",
  "F19", "33",
  "F20", "34",
    NULL, NULL
};

char prog[BUFSIZ];

main(argc,argv) 
        int argc; 
        char *argv[];
{
        /* these are defined in the getopt routine                       */
        extern char *optarg;    /* argument give to an option            */
        extern int  optind;     /* argv index after option processing    */

        int option;             /* option character returned by getopt   */
        int initf = 0;          /* read initialization file              */
        int lockf = 0;          /* lock keys after loading strings       */
        int clearf = 0;         /* clear all keys before loading strings */
	char *strcpy();

        (void) strcpy(prog, *argv);  /* store program name               */

        if(argc == 1) usage();  /* program requires options              */

        /* get options */
        while ((option = getopt(argc, argv, "cli")) != EOF)
          switch(option) 
          {
                case 'c' :
                        clearf++;
                        break;
                case 'l' :
                        lockf++;
                        break;
                case 'i' :
                        initf++;
                        break;
                case '?' :
                        usage();
          }

        if (VT200_7BIT)
                printf("[62;1\"p");    /* vt200 7 bits */
        else
                printf("[62;2\"p");    /* vt200 8 bits */

        if(clearf) clearkeys();
        
        if (initf) getinit();

        /* process {key, key string} pairs.  Note optind is index to argv
           for first pair.  By adding 1 to optind insures that a pair exists
           i.e. the last key has a key string.                             */

        while(optind + 1 < argc) 
        {
                dokey(argv[optind], argv[optind+1]);
                optind += 2;
        }

        if(lockf) lockkeys();

        exit(0);
}

/****************************************************************************/

/*
 *      Load the VT220 SHIFT-FNKEY value, the basic pattern is
 *              "\EP1;1|"+KEYNAME+"/"+VAL_AS_HEX+"\E\\"
 *      that is, literally what is in quotes (w/o quotes) then the
 *      name of the key from the keytable above (a numeric string)
 *      then a slash, then the string value as hex pairs then ESC-BACKSLASH
 *
 *      Note: you can gang together key defns with semicolons but that
 *      would complicate things, especially error handling, so do it all
 *      for each pair, who cares, really.
 */

dokey(nm,val) char *nm, *val;
{
        register char *scr;
        register struct keynames *kp;

        for(scr = nm; *scr = toupper(*scr); scr++)
                        ;
        for(kp = keys; kp->name != NULL; kp++)
          if(strcmp(nm,kp->name) == 0) {
            printf("%cP1;1|%s/",ESC,kp->string);
            while(*val) printf("%02x",*val++);
            printf("%c\\",ESC);
            fflush(stdout);
            return;
        }
        fprintf(stderr,"Bad key name: %s\n",nm);
        usage();        /* bad key name, give up */
}

/****************************************************************************/

clearkeys()
{
        printf("%cP0;1|%c\\",ESC,ESC);
        fflush(stdout);
}

/****************************************************************************/

lockkeys()
{
        printf("%cP1;0|%c\\",ESC,ESC);
        fflush(stdout);
}

/****************************************************************************/

usage()
{
        int i;

        fprintf(stderr,"Usage: %s [-cil] [keyname string keyname string...]\n\n",prog);
        fprintf(stderr,"The following options are available\n");
        fprintf(stderr,"\t-c\tclears keys first\n");
        fprintf(stderr,"\t-l\t[sets then] locks further setting\n");
        fprintf(stderr,"\t-i\tfirst read initialization file $HOME/%s\n",INITFILE);
        fprintf(stderr,"(note that the only way to unlock is via Set-Up)\n\n");
        fprintf(stderr,"Keyname is one of:\n\t");
        for(i=0; keys[i].name != NULL; i++)
                fprintf(stderr,"%s ",keys[i].name);
        fprintf(stderr,"\nKeyname is SHIFTED function key that sends the string\n\n");
        fprintf(stderr,"Strings may need quoting to protect from shell\n");
        fprintf(stderr,"You must specify an option or key,string pairs\n\n");
        exit(1);
}

/****************************************************************************/

/* This routine process the INITFILE.  This file expects lines in the format

                <ws> keyname ws string

   Where ws is white space (spaces or tabs) and <ws> is optional white space.
   The string may include spaces or tabs and need not be quoted.  If the 
   string has the sequence of "\n" then a newline character is included in 
   the string.

   examples:

        F6      ls -lg\n
        F7      uulog -s

*/

#include <sys/types.h>
#include <sys/stat.h>

getinit()
{
        char *home;             /* user's home directory                */
        char path[BUFSIZ];      /* full path name of init file          */
        char buf[BUFSIZ];       /* buffer to hold 1 line from init file */
        char key[BUFSIZ];       /* buffer, to hold specified fcn key    */
        char keystr[BUFSIZ];    /* string associated with fcn key       */
        char *ptr;              /* pointer to transverse buf            */
        int i, j;               /* array indices                        */
        int statflag;           /* whether init file is regular & readable */
        struct stat statbuf;    /* stat of the init file                */
        FILE *fp;               /* file pointer to init file            */

        /* system calls and subroutines */
        FILE *fopen();
        char *strcpy();
        char *strcat();
        char *fgets();
        char *getenv();

        /* construct full path name for init file */
        home = getenv("HOME");
        (void) strcpy(path, home);
        (void) strcat(path,"/");
        (void) strcat(path,INITFILE);

        /* check status if init file    */
        if (stat(path, &statbuf) != -1)
        {
            statflag = statbuf.st_mode & S_IFREG && statbuf.st_mode & S_IREAD;
            if (!statflag || (fp = fopen(path, "r")) == NULL)
            {
                fprintf("couldn't open initalization file: %s\n", path);
                exit(1);
            }

            /* process lines from init file */
            while (fgets(buf, BUFSIZ, fp) != NULL)
            {
                /* variable initializations */
                i = 0; j = 0;
                key[0] = '\0'; keystr[0] = '\0';
                ptr = buf;

                while (*ptr == ' ' || *ptr == '\t') ptr++; /*skip whitespace*/

		if (*ptr == '\n') break;   /* we hit an emtpy line          */

                while (!isspace(*ptr) && *ptr != '\0')     /* get keyname   */
                    key[i++] = *ptr++;
                key[i] = '\0'; /* place EOS in buffer */

                while (*ptr == ' ' || *ptr == '\t') ptr++; /*skip whitespace*/

                while (*ptr != '\n' && *ptr != '\0')       /* get string    */
                {
                    /* check if string is to include newline i.e. \n        */
                    if (*ptr == '\\' && *(ptr+1) == 'n')
                    {
                          keystr[j] = '\012';
                          ptr++;
                    }
                    else
                          keystr[j] = *ptr;
                    j++; ptr++;
                }
                keystr[j] = '\0';     /* place EOS in buffer  */
                dokey(key, keystr);   /* load key with string */
            }
        }
        else 
        {
            fprintf(stderr, "init file %s not found\n\n", path);
            usage();
        }
}
//E*O*F vt220.c//

echo Possible errors detected by \'wc\' [hopefully none]:
temp=/tmp/shar$$
trap "rm -f $temp; exit" 0 1 2 3 15
cat > $temp <<\!!!
     131     647    3818 vt220.1
      10      23     144 Makefile
     294    1057    9293 vt220.c
     435    1727   13255 total
!!!
wc  vt220.1 Makefile vt220.c | sed 's=[^ ]*/==' | diff -b $temp -
exit 0