
/*
	Opt builtin
*/


#define OPT

#include "rc.h"
#include "key.h"
#include "opt.h"


char *
key_putchar (int c)
{
	char *s = ealloc (3);
   if (c == 127) {
		*s = '^';
		*(s + 1) = '?';
		*(s + 2) = '\0';
   } else if (c > 31) {
		*s = c;
		*(s + 1) = '\0';
   } else {
		*s = '^';
		*(s + 1) = c + '@';
		*(s + 2) = '\0';
   }
	return s;
}


int
key_getchar (char *s)
{
	if (*s == '\'') s ++;
	if (*s == '^') {
		if (*(s + 1) == '?') {
			return 127;
		} else {
			return *(s + 1) - '@';
		}
	}
	return *s;
}


char *
pad (int i, char c)
{
	int loop = 0;
	char *s = ealloc (i + 1);
	for (; loop < i; loop ++) s [loop] = c;
	s [loop] = '\0';
	return s;
}


#define pad_len 15

void
b_opt (char **av)
{
	int loop;
	if (*++av == NULL) {
		for (loop = 0; loop < key_max; loop ++) {
			fprint (1, "%s%s%s\n", key_name [loop], pad (pad_len - strlen (key_name [loop]), ' '), key_putchar (key [loop]));
		}
		for (loop = 0; loop < opt_max; loop ++) {
			fprint (1, "%s%s%s\n", opt_name [loop], pad (pad_len - strlen (opt_name [loop]), ' '), opt [loop] ? "on" : "off");
		}
	} else if (av [1] == NULL && streq (av [0], "defaults")) {
		for (loop = 0; loop < key_max; loop ++) key [loop] = key_dfl [loop];
		for (loop = 0; loop < opt_max; loop ++) opt [loop] = opt_dfl [loop];
	} else {
		do {
			for (loop = 0; loop < opt_max && !streq (av [0], opt_name [loop]); loop ++);
			if (loop != opt_max) {
				if (av [1] == NULL) {
					fprint (2, "option '%s' has no argument\n", av [0]);
					set (FALSE);
					return;
				}
				if (streq (av [1], "on")) {
					opt [loop] = TRUE;
				} else if (streq (av [1], "off")) {
					opt [loop] = FALSE;
				} else {
					fprint (2, "option '%s' needs on or off argument\n", av [0]);
					set (FALSE);
					return;
				}
			} else {
				for (loop = 0; loop < key_max && !streq (av [0], key_name [loop]); loop ++);
				if (loop == key_max) {
					fprint (2, "no such option as '%s'\n", av [0]);
					set (FALSE);
					return;
				}
				if (av [1] == NULL) {
					fprint (2, "key name '%s' has no argument\n", av [0]);
					set (FALSE);
					return;
				}
				key [loop] = key_getchar (av [1]);
			}
			av += 2;
		} while (av [0]);
	}
	set (TRUE);
}

