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