/* options.c - functions dealing with editor options
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif				/* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "terminal.h"
#include "editor.h"


int ed_opt__insert = 1;			 /* insert mode */
int ed_opt__indent = 0;			 /* autoindent mode */
int ed_opt__wrap = 1;			 /* word wrapping */
int ed_opt__margin = 77;		 /* right margin for wrapping */


/* Read editor options from the environment variable $EDITOR_OPTIONS.
 */
void ed_loadopts(void)
{
	char *a;

	ed_opt__insert = 1;		    /* default settings */
	ed_opt__indent = 0;
	ed_opt__wrap = 1;
	ed_opt__margin = 77;

	a = getenv("EDITOR_OPTIONS");
	if (!a)
		return;

	if (strchr(a, 'I'))
		ed_opt__insert = 1;
	if (strchr(a, 'i'))
		ed_opt__insert = 0;
	if (strchr(a, 'A'))
		ed_opt__indent = 1;
	if (strchr(a, 'a'))
		ed_opt__indent = 0;
	if (strchr(a, 'W'))
		ed_opt__wrap = 1;
	if (strchr(a, 'w'))
		ed_opt__wrap = 0;
	if (strchr(a, 'R'))
		ed_opt__margin = atoi(strchr(a, 'R') + 1);

	if (ed_opt__margin < 10)
		ed_opt__margin = 10;
	if (ed_opt__margin > 999)
		ed_opt__margin = 999;
}


/* Store editor options to the environment variable $EDITOR_OPTIONS.
 */
void ed_saveopts(void)
{
	char buf[16];

	if (ed_opt__margin < 10)
		ed_opt__margin = 10;
	if (ed_opt__margin > 999)
		ed_opt__margin = 999;

	sprintf(buf, "%c%c%cR%d", ed_opt__insert ? 'I' : 'i',
		ed_opt__indent ? 'A' : 'a',
		ed_opt__wrap ? 'W' : 'w', ed_opt__margin);

	setenv("EDITOR_OPTIONS", buf, 1);
}


/* Toggle between Insert and Overwrite mode.
 */
void ed__op_insert(void)
{
	ed_opt__insert = 1 - ed_opt__insert;
}


/* Toggle Autoindent on/off.
 */
void ed__op_indent(void)
{
	ed_opt__indent = 1 - ed_opt__indent;
}


/* Toggle word wrapping on/off.
 */
void ed__op_togwrap(void)
{
	ed_opt__wrap = 1 - ed_opt__wrap;
}


/* Set right hand margin.
 */
void ed__op_margin(void)
{
	char buf[16];
	int n;

	sprintf(buf, "%d", ed_opt__margin);

	t_goto(0, t_rows - 1);
	t_clrtoeol();

	do {
		n = t_input("Right margin : ", buf, sizeof(buf) - 1);
	} while (n == 1);

	t_goto(0, t_rows - 1);
	t_clrtoeol();

	t_goto(ed__curchar - ed__leftchar,
	       ed__start_line + (ed__curline - ed__topline));

	n = atoi(buf);
	if ((n < 10) || (n > 999))
		return;

	ed_opt__margin = n;
}

/* EOF */
