xref: /minix/external/bsd/less/dist/lesskey.c (revision 84d9c625)
1 /*	$NetBSD: lesskey.c,v 1.4 2013/09/04 19:44:21 tron Exp $	*/
2 
3 /*
4  * Copyright (C) 1984-2012  Mark Nudelman
5  *
6  * You may distribute under the terms of either the GNU General Public
7  * License or the Less License, as specified in the README file.
8  *
9  * For more information, see the README file.
10  */
11 
12 
13 /*
14  *	lesskey [-o output] [input]
15  *
16  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
17  *
18  *	Make a .less file.
19  *	If no input file is specified, standard input is used.
20  *	If no output file is specified, $HOME/.less is used.
21  *
22  *	The .less file is used to specify (to "less") user-defined
23  *	key bindings.  Basically any sequence of 1 to MAX_CMDLEN
24  *	keystrokes may be bound to an existing less function.
25  *
26  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
27  *
28  *	The input file is an ascii file consisting of a
29  *	sequence of lines of the form:
30  *		string <whitespace> action [chars] <newline>
31  *
32  *	"string" is a sequence of command characters which form
33  *		the new user-defined command.  The command
34  *		characters may be:
35  *		1. The actual character itself.
36  *		2. A character preceded by ^ to specify a
37  *		   control character (e.g. ^X means control-X).
38  *		3. A backslash followed by one to three octal digits
39  *		   to specify a character by its octal value.
40  *		4. A backslash followed by b, e, n, r or t
41  *		   to specify \b, ESC, \n, \r or \t, respectively.
42  *		5. Any character (other than those mentioned above) preceded
43  *		   by a \ to specify the character itself (characters which
44  *		   must be preceded by \ include ^, \, and whitespace.
45  *	"action" is the name of a "less" action, from the table below.
46  *	"chars" is an optional sequence of characters which is treated
47  *		as keyboard input after the command is executed.
48  *
49  *	Blank lines and lines which start with # are ignored,
50  *	except for the special control lines:
51  *		#command	Signals the beginning of the command
52  *				keys section.
53  *		#line-edit	Signals the beginning of the line-editing
54  *				keys section.
55  *		#env		Signals the beginning of the environment
56  *				variable section.
57  *		#stop		Stops command parsing in less;
58  *				causes all default keys to be disabled.
59  *
60  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
61  *
62  *	The output file is a non-ascii file, consisting of a header,
63  *	one or more sections, and a trailer.
64  *	Each section begins with a section header, a section length word
65  *	and the section data.  Normally there are three sections:
66  *		CMD_SECTION	Definition of command keys.
67  *		EDIT_SECTION	Definition of editing keys.
68  *		END_SECTION	A special section header, with no
69  *				length word or section data.
70  *
71  *	Section data consists of zero or more byte sequences of the form:
72  *		string <0> <action>
73  *	or
74  *		string <0> <action|A_EXTRA> chars <0>
75  *
76  *	"string" is the command string.
77  *	"<0>" is one null byte.
78  *	"<action>" is one byte containing the action code (the A_xxx value).
79  *	If action is ORed with A_EXTRA, the action byte is followed
80  *		by the null-terminated "chars" string.
81  *
82  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
83  */
84 
85 #include "less.h"
86 #include "lesskey.h"
87 #include "cmd.h"
88 
89 struct cmdname
90 {
91 	char *cn_name;
92 	int cn_action;
93 };
94 
95 struct cmdname cmdnames[] =
96 {
97 	{ "back-bracket",         A_B_BRACKET },
98 	{ "back-line",            A_B_LINE },
99 	{ "back-line-force",      A_BF_LINE },
100 	{ "back-screen",          A_B_SCREEN },
101 	{ "back-scroll",          A_B_SCROLL },
102 	{ "back-search",          A_B_SEARCH },
103 	{ "back-window",          A_B_WINDOW },
104 	{ "debug",                A_DEBUG },
105 	{ "digit",                A_DIGIT },
106 	{ "display-flag",         A_DISP_OPTION },
107 	{ "display-option",       A_DISP_OPTION },
108 	{ "end",                  A_GOEND },
109 	{ "examine",              A_EXAMINE },
110 	{ "filter",               A_FILTER },
111 	{ "first-cmd",            A_FIRSTCMD },
112 	{ "firstcmd",             A_FIRSTCMD },
113 	{ "flush-repaint",        A_FREPAINT },
114 	{ "forw-bracket",         A_F_BRACKET },
115 	{ "forw-forever",         A_F_FOREVER },
116 	{ "forw-until-hilite",    A_F_UNTIL_HILITE },
117 	{ "forw-line",            A_F_LINE },
118 	{ "forw-line-force",      A_FF_LINE },
119 	{ "forw-screen",          A_F_SCREEN },
120 	{ "forw-screen-force",    A_FF_SCREEN },
121 	{ "forw-scroll",          A_F_SCROLL },
122 	{ "forw-search",          A_F_SEARCH },
123 	{ "forw-window",          A_F_WINDOW },
124 	{ "goto-end",             A_GOEND },
125 	{ "goto-line",            A_GOLINE },
126 	{ "goto-mark",            A_GOMARK },
127 	{ "help",                 A_HELP },
128 	{ "index-file",           A_INDEX_FILE },
129 	{ "invalid",              A_UINVALID },
130 	{ "left-scroll",          A_LSHIFT },
131 	{ "next-file",            A_NEXT_FILE },
132 	{ "next-tag",             A_NEXT_TAG },
133 	{ "noaction",             A_NOACTION },
134 	{ "percent",              A_PERCENT },
135 	{ "pipe",                 A_PIPE },
136 	{ "prev-file",            A_PREV_FILE },
137 	{ "prev-tag",             A_PREV_TAG },
138 	{ "quit",                 A_QUIT },
139 	{ "remove-file",          A_REMOVE_FILE },
140 	{ "repaint",              A_REPAINT },
141 	{ "repaint-flush",        A_FREPAINT },
142 	{ "repeat-search",        A_AGAIN_SEARCH },
143 	{ "repeat-search-all",    A_T_AGAIN_SEARCH },
144 	{ "reverse-search",       A_REVERSE_SEARCH },
145 	{ "reverse-search-all",   A_T_REVERSE_SEARCH },
146 	{ "right-scroll",         A_RSHIFT },
147 	{ "set-mark",             A_SETMARK },
148 	{ "shell",                A_SHELL },
149 	{ "status",               A_STAT },
150 	{ "toggle-flag",          A_OPT_TOGGLE },
151 	{ "toggle-option",        A_OPT_TOGGLE },
152 	{ "undo-hilite",          A_UNDO_SEARCH },
153 	{ "version",              A_VERSION },
154 	{ "visual",               A_VISUAL },
155 	{ NULL,   0 }
156 };
157 
158 struct cmdname editnames[] =
159 {
160 	{ "back-complete",	EC_B_COMPLETE },
161 	{ "backspace",		EC_BACKSPACE },
162 	{ "delete",		EC_DELETE },
163 	{ "down",		EC_DOWN },
164 	{ "end",		EC_END },
165 	{ "expand",		EC_EXPAND },
166 	{ "forw-complete",	EC_F_COMPLETE },
167 	{ "home",		EC_HOME },
168 	{ "insert",		EC_INSERT },
169 	{ "invalid",		EC_UINVALID },
170 	{ "kill-line",		EC_LINEKILL },
171 	{ "abort",		EC_ABORT },
172 	{ "left",		EC_LEFT },
173 	{ "literal",		EC_LITERAL },
174 	{ "right",		EC_RIGHT },
175 	{ "up",			EC_UP },
176 	{ "word-backspace",	EC_W_BACKSPACE },
177 	{ "word-delete",	EC_W_DELETE },
178 	{ "word-left",		EC_W_LEFT },
179 	{ "word-right",		EC_W_RIGHT },
180 	{ NULL, 0 }
181 };
182 
183 struct table
184 {
185 	struct cmdname *names;
186 	char *pbuffer;
187 	char buffer[MAX_USERCMD];
188 };
189 
190 struct table cmdtable;
191 struct table edittable;
192 struct table vartable;
193 struct table *currtable = &cmdtable;
194 
195 char fileheader[] = {
196 	C0_LESSKEY_MAGIC,
197 	C1_LESSKEY_MAGIC,
198 	C2_LESSKEY_MAGIC,
199 	C3_LESSKEY_MAGIC
200 };
201 char filetrailer[] = {
202 	C0_END_LESSKEY_MAGIC,
203 	C1_END_LESSKEY_MAGIC,
204 	C2_END_LESSKEY_MAGIC
205 };
206 char cmdsection[1] =	{ CMD_SECTION };
207 char editsection[1] =	{ EDIT_SECTION };
208 char varsection[1] =	{ VAR_SECTION };
209 char endsection[1] =	{ END_SECTION };
210 
211 char *infile = NULL;
212 char *outfile = NULL ;
213 
214 int linenum;
215 int errors;
216 
217 void terror(char *);
218 
219 extern char version[];
220 
221 	void
usage()222 usage()
223 {
224 	fprintf(stderr, "usage: lesskey [-o output] [input]\n");
225 	exit(1);
226 }
227 
228 	char *
mkpathname(dirname,filename)229 mkpathname(dirname, filename)
230 	char *dirname;
231 	char *filename;
232 {
233 	char *pathname;
234 
235 	pathname = calloc(strlen(dirname) + strlen(filename) + 2, sizeof(char));
236 	strcpy(pathname, dirname);
237 	strcat(pathname, PATHNAME_SEP);
238 	strcat(pathname, filename);
239 	return (pathname);
240 }
241 
242 /*
243  * Figure out the name of a default file (in the user's HOME directory).
244  */
245 	char *
homefile(filename)246 homefile(filename)
247 	char *filename;
248 {
249 	char *p;
250 	char *pathname;
251 
252 	if ((p = getenv("HOME")) != NULL && *p != '\0')
253 		pathname = mkpathname(p, filename);
254 #if OS2
255 	else if ((p = getenv("INIT")) != NULL && *p != '\0')
256 		pathname = mkpathname(p, filename);
257 #endif
258 	else
259 	{
260 		fprintf(stderr, "cannot find $HOME - using current directory\n");
261 		pathname = mkpathname(".", filename);
262 	}
263 	return (pathname);
264 }
265 
266 /*
267  * Parse command line arguments.
268  */
269 	void
parse_args(argc,argv)270 parse_args(argc, argv)
271 	int argc;
272 	char **argv;
273 {
274 	char *arg;
275 
276 	outfile = NULL;
277 	while (--argc > 0)
278 	{
279 		arg = *++argv;
280 		if (arg[0] != '-')
281 			/* Arg does not start with "-"; it's not an option. */
282 			break;
283 		if (arg[1] == '\0')
284 			/* "-" means standard input. */
285 			break;
286 		if (arg[1] == '-' && arg[2] == '\0')
287 		{
288 			/* "--" means end of options. */
289 			argc--;
290 			argv++;
291 			break;
292 		}
293 		switch (arg[1])
294 		{
295 		case '-':
296 			if (strncmp(arg, "--output", 8) == 0)
297 			{
298 				if (arg[8] == '\0')
299 					outfile = &arg[8];
300 				else if (arg[8] == '=')
301 					outfile = &arg[9];
302 				else
303 					usage();
304 				goto opt_o;
305 			}
306 			if (strcmp(arg, "--version") == 0)
307 			{
308 				goto opt_V;
309 			}
310 			usage();
311 			break;
312 		case 'o':
313 			outfile = &argv[0][2];
314 		opt_o:
315 			if (*outfile == '\0')
316 			{
317 				if (--argc <= 0)
318 					usage();
319 				outfile = *(++argv);
320 			}
321 			break;
322 		case 'V':
323 		opt_V:
324 			printf("lesskey  version %s\n", version);
325 			exit(0);
326 		default:
327 			usage();
328 		}
329 	}
330 	if (argc > 1)
331 		usage();
332 	/*
333 	 * Open the input file, or use DEF_LESSKEYINFILE if none specified.
334 	 */
335 	if (argc > 0)
336 		infile = *argv;
337 	else
338 		infile = homefile(DEF_LESSKEYINFILE);
339 }
340 
341 /*
342  * Initialize data structures.
343  */
344 	void
init_tables()345 init_tables()
346 {
347 	cmdtable.names = cmdnames;
348 	cmdtable.pbuffer = cmdtable.buffer;
349 
350 	edittable.names = editnames;
351 	edittable.pbuffer = edittable.buffer;
352 
353 	vartable.names = NULL;
354 	vartable.pbuffer = vartable.buffer;
355 }
356 
357 /*
358  * Parse one character of a string.
359  */
360 	char *
tstr(pp,xlate)361 tstr(pp, xlate)
362 	char **pp;
363 	int xlate;
364 {
365 	register char *p;
366 	register char ch;
367 	register int i;
368 	static char buf[10];
369 	static char tstr_control_k[] =
370 		{ SK_SPECIAL_KEY, SK_CONTROL_K, 6, 1, 1, 1, '\0' };
371 
372 	p = *pp;
373 	switch (*p)
374 	{
375 	case '\\':
376 		++p;
377 		switch (*p)
378 		{
379 		case '0': case '1': case '2': case '3':
380 		case '4': case '5': case '6': case '7':
381 			/*
382 			 * Parse an octal number.
383 			 */
384 			ch = 0;
385 			i = 0;
386 			do
387 				ch = 8*ch + (*p - '0');
388 			while (*++p >= '0' && *p <= '7' && ++i < 3);
389 			*pp = p;
390 			if (xlate && ch == CONTROL('K'))
391 				return tstr_control_k;
392 			buf[0] = ch;
393 			buf[1] = '\0';
394 			return (buf);
395 		case 'b':
396 			*pp = p+1;
397 			return ("\b");
398 		case 'e':
399 			*pp = p+1;
400 			buf[0] = ESC;
401 			buf[1] = '\0';
402 			return (buf);
403 		case 'n':
404 			*pp = p+1;
405 			return ("\n");
406 		case 'r':
407 			*pp = p+1;
408 			return ("\r");
409 		case 't':
410 			*pp = p+1;
411 			return ("\t");
412 		case 'k':
413 			if (xlate)
414 			{
415 				switch (*++p)
416 				{
417 				case 'u': ch = SK_UP_ARROW; break;
418 				case 'd': ch = SK_DOWN_ARROW; break;
419 				case 'r': ch = SK_RIGHT_ARROW; break;
420 				case 'l': ch = SK_LEFT_ARROW; break;
421 				case 'U': ch = SK_PAGE_UP; break;
422 				case 'D': ch = SK_PAGE_DOWN; break;
423 				case 'h': ch = SK_HOME; break;
424 				case 'e': ch = SK_END; break;
425 				case 'x': ch = SK_DELETE; break;
426 				default:
427 					terror("illegal char after \\k");
428 					*pp = p+1;
429 					return ("");
430 				}
431 				*pp = p+1;
432 				buf[0] = SK_SPECIAL_KEY;
433 				buf[1] = ch;
434 				buf[2] = 6;
435 				buf[3] = 1;
436 				buf[4] = 1;
437 				buf[5] = 1;
438 				buf[6] = '\0';
439 				return (buf);
440 			}
441 			/* FALLTHRU */
442 		default:
443 			/*
444 			 * Backslash followed by any other char
445 			 * just means that char.
446 			 */
447 			*pp = p+1;
448 			buf[0] = *p;
449 			buf[1] = '\0';
450 			if (xlate && buf[0] == CONTROL('K'))
451 				return tstr_control_k;
452 			return (buf);
453 		}
454 	case '^':
455 		/*
456 		 * Caret means CONTROL.
457 		 */
458 		*pp = p+2;
459 		buf[0] = CONTROL(p[1]);
460 		buf[1] = '\0';
461 		if (buf[0] == CONTROL('K'))
462 			return tstr_control_k;
463 		return (buf);
464 	}
465 	*pp = p+1;
466 	buf[0] = *p;
467 	buf[1] = '\0';
468 	if (xlate && buf[0] == CONTROL('K'))
469 		return tstr_control_k;
470 	return (buf);
471 }
472 
473 /*
474  * Skip leading spaces in a string.
475  */
476 	public char *
skipsp(s)477 skipsp(s)
478 	register char *s;
479 {
480 	while (*s == ' ' || *s == '\t')
481 		s++;
482 	return (s);
483 }
484 
485 /*
486  * Skip non-space characters in a string.
487  */
488 	public char *
skipnsp(s)489 skipnsp(s)
490 	register char *s;
491 {
492 	while (*s != '\0' && *s != ' ' && *s != '\t')
493 		s++;
494 	return (s);
495 }
496 
497 /*
498  * Clean up an input line:
499  * strip off the trailing newline & any trailing # comment.
500  */
501 	char *
clean_line(s)502 clean_line(s)
503 	char *s;
504 {
505 	register int i;
506 
507 	s = skipsp(s);
508 	for (i = 0;  s[i] != '\n' && s[i] != '\r' && s[i] != '\0';  i++)
509 		if (s[i] == '#' && (i == 0 || s[i-1] != '\\'))
510 			break;
511 	s[i] = '\0';
512 	return (s);
513 }
514 
515 /*
516  * Add a byte to the output command table.
517  */
518 	void
add_cmd_char(c)519 add_cmd_char(c)
520 	int c;
521 {
522 	if (currtable->pbuffer >= currtable->buffer + MAX_USERCMD)
523 	{
524 		terror("too many commands");
525 		exit(1);
526 	}
527 	*(currtable->pbuffer)++ = c;
528 }
529 
530 /*
531  * Add a string to the output command table.
532  */
533 	void
add_cmd_str(s)534 add_cmd_str(s)
535 	char *s;
536 {
537 	for ( ;  *s != '\0';  s++)
538 		add_cmd_char(*s);
539 }
540 
541 /*
542  * See if we have a special "control" line.
543  */
544 	int
control_line(s)545 control_line(s)
546 	char *s;
547 {
548 #define	PREFIX(str,pat)	(strncmp(str,pat,strlen(pat)) == 0)
549 
550 	if (PREFIX(s, "#line-edit"))
551 	{
552 		currtable = &edittable;
553 		return (1);
554 	}
555 	if (PREFIX(s, "#command"))
556 	{
557 		currtable = &cmdtable;
558 		return (1);
559 	}
560 	if (PREFIX(s, "#env"))
561 	{
562 		currtable = &vartable;
563 		return (1);
564 	}
565 	if (PREFIX(s, "#stop"))
566 	{
567 		add_cmd_char('\0');
568 		add_cmd_char(A_END_LIST);
569 		return (1);
570 	}
571 	return (0);
572 }
573 
574 /*
575  * Output some bytes.
576  */
577 	void
fputbytes(fd,buf,len)578 fputbytes(fd, buf, len)
579 	FILE *fd;
580 	char *buf;
581 	int len;
582 {
583 	while (len-- > 0)
584 	{
585 		fwrite(buf, sizeof(char), 1, fd);
586 		buf++;
587 	}
588 }
589 
590 /*
591  * Output an integer, in special KRADIX form.
592  */
593 	void
fputint(fd,val)594 fputint(fd, val)
595 	FILE *fd;
596 	unsigned int val;
597 {
598 	char c;
599 
600 	if (val >= KRADIX*KRADIX)
601 	{
602 		fprintf(stderr, "error: integer too big (%d > %d)\n",
603 			val, KRADIX*KRADIX);
604 		exit(1);
605 	}
606 	c = val % KRADIX;
607 	fwrite(&c, sizeof(char), 1, fd);
608 	c = val / KRADIX;
609 	fwrite(&c, sizeof(char), 1, fd);
610 }
611 
612 /*
613  * Find an action, given the name of the action.
614  */
615 	int
findaction(actname)616 findaction(actname)
617 	char *actname;
618 {
619 	int i;
620 
621 	for (i = 0;  currtable->names[i].cn_name != NULL;  i++)
622 		if (strcmp(currtable->names[i].cn_name, actname) == 0)
623 			return (currtable->names[i].cn_action);
624 	terror("unknown action");
625 	return (A_INVALID);
626 }
627 
628 	void
terror(s)629 terror(s)
630 	char *s;
631 {
632 	fprintf(stderr, "line %d: %s\n", linenum, s);
633 	errors++;
634 }
635 
636 
637 	void
parse_cmdline(p)638 parse_cmdline(p)
639 	char *p;
640 {
641 	int cmdlen;
642 	char *actname;
643 	int action;
644 	char *s;
645 	char c;
646 
647 	/*
648 	 * Parse the command string and store it in the current table.
649 	 */
650 	cmdlen = 0;
651 	do
652 	{
653 		s = tstr(&p, 1);
654 		cmdlen += strlen(s);
655 		if (cmdlen > MAX_CMDLEN)
656 			terror("command too long");
657 		else
658 			add_cmd_str(s);
659 	} while (*p != ' ' && *p != '\t' && *p != '\0');
660 	/*
661 	 * Terminate the command string with a null byte.
662 	 */
663 	add_cmd_char('\0');
664 
665 	/*
666 	 * Skip white space between the command string
667 	 * and the action name.
668 	 * Terminate the action name with a null byte.
669 	 */
670 	p = skipsp(p);
671 	if (*p == '\0')
672 	{
673 		terror("missing action");
674 		return;
675 	}
676 	actname = p;
677 	p = skipnsp(p);
678 	c = *p;
679 	*p = '\0';
680 
681 	/*
682 	 * Parse the action name and store it in the current table.
683 	 */
684 	action = findaction(actname);
685 
686 	/*
687 	 * See if an extra string follows the action name.
688 	 */
689 	*p = c;
690 	p = skipsp(p);
691 	if (*p == '\0')
692 	{
693 		add_cmd_char(action);
694 	} else
695 	{
696 		/*
697 		 * OR the special value A_EXTRA into the action byte.
698 		 * Put the extra string after the action byte.
699 		 */
700 		add_cmd_char(action | A_EXTRA);
701 		while (*p != '\0')
702 			add_cmd_str(tstr(&p, 0));
703 		add_cmd_char('\0');
704 	}
705 }
706 
707 	void
parse_varline(p)708 parse_varline(p)
709 	char *p;
710 {
711 	char *s;
712 
713 	do
714 	{
715 		s = tstr(&p, 0);
716 		add_cmd_str(s);
717 	} while (*p != ' ' && *p != '\t' && *p != '=' && *p != '\0');
718 	/*
719 	 * Terminate the variable name with a null byte.
720 	 */
721 	add_cmd_char('\0');
722 
723 	p = skipsp(p);
724 	if (*p++ != '=')
725 	{
726 		terror("missing =");
727 		return;
728 	}
729 
730 	add_cmd_char(EV_OK|A_EXTRA);
731 
732 	p = skipsp(p);
733 	while (*p != '\0')
734 	{
735 		s = tstr(&p, 0);
736 		add_cmd_str(s);
737 	}
738 	add_cmd_char('\0');
739 }
740 
741 /*
742  * Parse a line from the lesskey file.
743  */
744 	void
parse_line(line)745 parse_line(line)
746 	char *line;
747 {
748 	char *p;
749 
750 	/*
751 	 * See if it is a control line.
752 	 */
753 	if (control_line(line))
754 		return;
755 	/*
756 	 * Skip leading white space.
757 	 * Replace the final newline with a null byte.
758 	 * Ignore blank lines and comments.
759 	 */
760 	p = clean_line(line);
761 	if (*p == '\0')
762 		return;
763 
764 	if (currtable == &vartable)
765 		parse_varline(p);
766 	else
767 		parse_cmdline(p);
768 }
769 
770 	int
main(argc,argv)771 main(argc, argv)
772 	int argc;
773 	char *argv[];
774 {
775 	FILE *desc;
776 	FILE *out;
777 	char line[1024];
778 
779 #ifdef WIN32
780 	if (getenv("HOME") == NULL)
781 	{
782 		/*
783 		 * If there is no HOME environment variable,
784 		 * try the concatenation of HOMEDRIVE + HOMEPATH.
785 		 */
786 		char *drive = getenv("HOMEDRIVE");
787 		char *path  = getenv("HOMEPATH");
788 		if (drive != NULL && path != NULL)
789 		{
790 			char *env = (char *) calloc(strlen(drive) +
791 					strlen(path) + 6, sizeof(char));
792 			strcpy(env, "HOME=");
793 			strcat(env, drive);
794 			strcat(env, path);
795 			putenv(env);
796 		}
797 	}
798 #endif /* WIN32 */
799 
800 	/*
801 	 * Process command line arguments.
802 	 */
803 	parse_args(argc, argv);
804 	init_tables();
805 
806 	/*
807 	 * Open the input file.
808 	 */
809 	if (strcmp(infile, "-") == 0)
810 		desc = stdin;
811 	else if ((desc = fopen(infile, "r")) == NULL)
812 	{
813 #if HAVE_PERROR
814 		perror(infile);
815 #else
816 		fprintf(stderr, "Cannot open %s\n", infile);
817 #endif
818 		usage();
819 	}
820 
821 	/*
822 	 * Read and parse the input file, one line at a time.
823 	 */
824 	errors = 0;
825 	linenum = 0;
826 	while (fgets(line, sizeof(line), desc) != NULL)
827 	{
828 		++linenum;
829 		parse_line(line);
830 	}
831 
832 	/*
833 	 * Write the output file.
834 	 * If no output file was specified, use "$HOME/.less"
835 	 */
836 	if (errors > 0)
837 	{
838 		fprintf(stderr, "%d errors; no output produced\n", errors);
839 		exit(1);
840 	}
841 
842 	if (outfile == NULL)
843 		outfile = getenv("LESSKEY");
844 	if (outfile == NULL)
845 		outfile = homefile(LESSKEYFILE);
846 	if ((out = fopen(outfile, "wb")) == NULL)
847 	{
848 #if HAVE_PERROR
849 		perror(outfile);
850 #else
851 		fprintf(stderr, "Cannot open %s\n", outfile);
852 #endif
853 		exit(1);
854 	}
855 
856 	/* File header */
857 	fputbytes(out, fileheader, sizeof(fileheader));
858 
859 	/* Command key section */
860 	fputbytes(out, cmdsection, sizeof(cmdsection));
861 	fputint(out, cmdtable.pbuffer - cmdtable.buffer);
862 	fputbytes(out, (char *)cmdtable.buffer, cmdtable.pbuffer-cmdtable.buffer);
863 	/* Edit key section */
864 	fputbytes(out, editsection, sizeof(editsection));
865 	fputint(out, edittable.pbuffer - edittable.buffer);
866 	fputbytes(out, (char *)edittable.buffer, edittable.pbuffer-edittable.buffer);
867 
868 	/* Environment variable section */
869 	fputbytes(out, varsection, sizeof(varsection));
870 	fputint(out, vartable.pbuffer - vartable.buffer);
871 	fputbytes(out, (char *)vartable.buffer, vartable.pbuffer-vartable.buffer);
872 
873 	/* File trailer */
874 	fputbytes(out, endsection, sizeof(endsection));
875 	fputbytes(out, filetrailer, sizeof(filetrailer));
876 	return (0);
877 }
878