vm: fix potential null deref
[minix.git] / commands / less / lesskey / lesskey.c
blobfded6cfb0e311f92b84e58865d77a6b14e8e00e4
1 /* $NetBSD: lesskey.c,v 1.9 2006/10/26 01:33:08 mrg Exp $ */
3 /*
4 * Copyright (C) 1984-2004 Mark Nudelman
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.
9 * For more information about less, or for information on how to
10 * contact the author, see the README file.
15 * lesskey [-o output] [input]
17 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
19 * Make a .less file.
20 * If no input file is specified, standard input is used.
21 * If no output file is specified, $HOME/.less is used.
23 * The .less file is used to specify (to "less") user-defined
24 * key bindings. Basically any sequence of 1 to MAX_CMDLEN
25 * keystrokes may be bound to an existing less function.
27 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
29 * The input file is an ascii file consisting of a
30 * sequence of lines of the form:
31 * string <whitespace> action [chars] <newline>
33 * "string" is a sequence of command characters which form
34 * the new user-defined command. The command
35 * characters may be:
36 * 1. The actual character itself.
37 * 2. A character preceded by ^ to specify a
38 * control character (e.g. ^X means control-X).
39 * 3. A backslash followed by one to three octal digits
40 * to specify a character by its octal value.
41 * 4. A backslash followed by b, e, n, r or t
42 * to specify \b, ESC, \n, \r or \t, respectively.
43 * 5. Any character (other than those mentioned above) preceded
44 * by a \ to specify the character itself (characters which
45 * must be preceded by \ include ^, \, and whitespace.
46 * "action" is the name of a "less" action, from the table below.
47 * "chars" is an optional sequence of characters which is treated
48 * as keyboard input after the command is executed.
50 * Blank lines and lines which start with # are ignored,
51 * except for the special control lines:
52 * #command Signals the beginning of the command
53 * keys section.
54 * #line-edit Signals the beginning of the line-editing
55 * keys section.
56 * #env Signals the beginning of the environment
57 * variable section.
58 * #stop Stops command parsing in less;
59 * causes all default keys to be disabled.
61 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
63 * The output file is a non-ascii file, consisting of a header,
64 * one or more sections, and a trailer.
65 * Each section begins with a section header, a section length word
66 * and the section data. Normally there are three sections:
67 * CMD_SECTION Definition of command keys.
68 * EDIT_SECTION Definition of editing keys.
69 * END_SECTION A special section header, with no
70 * length word or section data.
72 * Section data consists of zero or more byte sequences of the form:
73 * string <0> <action>
74 * or
75 * string <0> <action|A_EXTRA> chars <0>
77 * "string" is the command string.
78 * "<0>" is one null byte.
79 * "<action>" is one byte containing the action code (the A_xxx value).
80 * If action is ORed with A_EXTRA, the action byte is followed
81 * by the null-terminated "chars" string.
83 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
86 #include "less.h"
87 #include "lesskey.h"
88 #include "cmd.h"
90 struct cmdname
92 char *cn_name;
93 int cn_action;
96 struct cmdname cmdnames[] =
98 { "back-bracket", A_B_BRACKET },
99 { "back-line", A_B_LINE },
100 { "back-line-force", A_BF_LINE },
101 { "back-screen", A_B_SCREEN },
102 { "back-scroll", A_B_SCROLL },
103 { "back-search", A_B_SEARCH },
104 { "back-window", A_B_WINDOW },
105 { "debug", A_DEBUG },
106 { "digit", A_DIGIT },
107 { "display-flag", A_DISP_OPTION },
108 { "display-option", A_DISP_OPTION },
109 { "end", A_GOEND },
110 { "examine", A_EXAMINE },
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-line", A_F_LINE },
117 { "forw-line-force", A_FF_LINE },
118 { "forw-screen", A_F_SCREEN },
119 { "forw-screen-force", A_FF_SCREEN },
120 { "forw-scroll", A_F_SCROLL },
121 { "forw-search", A_F_SEARCH },
122 { "forw-window", A_F_WINDOW },
123 { "goto-end", A_GOEND },
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 }
157 struct cmdname editnames[] =
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 { "left", EC_LEFT },
171 { "literal", EC_LITERAL },
172 { "right", EC_RIGHT },
173 { "up", EC_UP },
174 { "word-backspace", EC_W_BACKSPACE },
175 { "word-delete", EC_W_DELETE },
176 { "word-left", EC_W_LEFT },
177 { "word-right", EC_W_RIGHT },
178 { NULL, 0 }
181 struct table
183 struct cmdname *names;
184 char *pbuffer;
185 char buffer[MAX_USERCMD];
188 struct table cmdtable;
189 struct table edittable;
190 struct table vartable;
191 struct table *currtable = &cmdtable;
193 char fileheader[] = {
194 C0_LESSKEY_MAGIC,
195 C1_LESSKEY_MAGIC,
196 C2_LESSKEY_MAGIC,
197 C3_LESSKEY_MAGIC
199 char filetrailer[] = {
200 C0_END_LESSKEY_MAGIC,
201 C1_END_LESSKEY_MAGIC,
202 C2_END_LESSKEY_MAGIC
204 char cmdsection[1] = { CMD_SECTION };
205 char editsection[1] = { EDIT_SECTION };
206 char varsection[1] = { VAR_SECTION };
207 char endsection[1] = { END_SECTION };
209 char *infile = NULL;
210 char *outfile = NULL ;
212 int linenum;
213 int errors;
215 void terror(char *);
217 extern char version[];
219 void
220 usage()
222 fprintf(stderr, "usage: lesskey [-o output] [input]\n");
223 exit(1);
226 char *
227 mkpathname(dirname, filename)
228 char *dirname;
229 char *filename;
231 char *pathname;
233 pathname = calloc(strlen(dirname) + strlen(filename) + 2, sizeof(char));
234 strcpy(pathname, dirname);
235 strcat(pathname, PATHNAME_SEP);
236 strcat(pathname, filename);
237 return (pathname);
241 * Figure out the name of a default file (in the user's HOME directory).
243 char *
244 homefile(filename)
245 char *filename;
247 char *p;
248 char *pathname;
250 if ((p = getenv("HOME")) != NULL && *p != '\0')
251 pathname = mkpathname(p, filename);
252 #if OS2
253 else if ((p = getenv("INIT")) != NULL && *p != '\0')
254 pathname = mkpathname(p, filename);
255 #endif
256 else
258 fprintf(stderr, "cannot find $HOME - using current directory\n");
259 pathname = mkpathname(".", filename);
261 return (pathname);
265 * Parse command line arguments.
267 void
268 parse_args(argc, argv)
269 int argc;
270 char **argv;
272 char *arg;
274 outfile = NULL;
275 while (--argc > 0)
277 arg = *++argv;
278 if (arg[0] != '-')
279 /* Arg does not start with "-"; it's not an option. */
280 break;
281 if (arg[1] == '\0')
282 /* "-" means standard input. */
283 break;
284 if (arg[1] == '-' && arg[2] == '\0')
286 /* "--" means end of options. */
287 argc--;
288 argv++;
289 break;
291 switch (arg[1])
293 case '-':
294 if (strncmp(arg, "--output", 8) == 0)
296 if (arg[8] == '\0')
297 outfile = &arg[8];
298 else if (arg[8] == '=')
299 outfile = &arg[9];
300 else
301 usage();
302 goto opt_o;
304 if (strcmp(arg, "--version") == 0)
306 goto opt_V;
308 usage();
309 break;
310 case 'o':
311 outfile = &argv[0][2];
312 opt_o:
313 if (*outfile == '\0')
315 if (--argc <= 0)
316 usage();
317 outfile = *(++argv);
319 break;
320 case 'V':
321 opt_V:
322 printf("lesskey version %s\n", version);
323 exit(0);
324 default:
325 usage();
328 if (argc > 1)
329 usage();
331 * Open the input file, or use DEF_LESSKEYINFILE if none specified.
333 if (argc > 0)
334 infile = *argv;
335 else
336 infile = homefile(DEF_LESSKEYINFILE);
340 * Initialize data structures.
342 void
343 init_tables()
345 cmdtable.names = cmdnames;
346 cmdtable.pbuffer = cmdtable.buffer;
348 edittable.names = editnames;
349 edittable.pbuffer = edittable.buffer;
351 vartable.names = NULL;
352 vartable.pbuffer = vartable.buffer;
356 * Parse one character of a string.
358 char *
359 tstr(pp, xlate)
360 char **pp;
361 int xlate;
363 register char *p;
364 register char ch;
365 register int i;
366 static char buf[10];
367 static char tstr_control_k[] =
368 { SK_SPECIAL_KEY, SK_CONTROL_K, 6, 1, 1, 1, '\0' };
370 p = *pp;
371 switch (*p)
373 case '\\':
374 ++p;
375 switch (*p)
377 case '0': case '1': case '2': case '3':
378 case '4': case '5': case '6': case '7':
380 * Parse an octal number.
382 ch = 0;
383 i = 0;
385 ch = 8*ch + (*p - '0');
386 while (*++p >= '0' && *p <= '7' && ++i < 3);
387 *pp = p;
388 if (xlate && ch == CONTROL('K'))
389 return tstr_control_k;
390 buf[0] = ch;
391 buf[1] = '\0';
392 return (buf);
393 case 'b':
394 *pp = p+1;
395 return ("\b");
396 case 'e':
397 *pp = p+1;
398 buf[0] = ESC;
399 buf[1] = '\0';
400 return (buf);
401 case 'n':
402 *pp = p+1;
403 return ("\n");
404 case 'r':
405 *pp = p+1;
406 return ("\r");
407 case 't':
408 *pp = p+1;
409 return ("\t");
410 case 'k':
411 if (xlate)
413 switch (*++p)
415 case 'u': ch = SK_UP_ARROW; break;
416 case 'd': ch = SK_DOWN_ARROW; break;
417 case 'r': ch = SK_RIGHT_ARROW; break;
418 case 'l': ch = SK_LEFT_ARROW; break;
419 case 'U': ch = SK_PAGE_UP; break;
420 case 'D': ch = SK_PAGE_DOWN; break;
421 case 'h': ch = SK_HOME; break;
422 case 'e': ch = SK_END; break;
423 case 'x': ch = SK_DELETE; break;
424 default:
425 terror("illegal char after \\k");
426 *pp = p+1;
427 return ("");
429 *pp = p+1;
430 buf[0] = SK_SPECIAL_KEY;
431 buf[1] = ch;
432 buf[2] = 6;
433 buf[3] = 1;
434 buf[4] = 1;
435 buf[5] = 1;
436 buf[6] = '\0';
437 return (buf);
439 /* FALLTHRU */
440 default:
442 * Backslash followed by any other char
443 * just means that char.
445 *pp = p+1;
446 buf[0] = *p;
447 buf[1] = '\0';
448 if (xlate && buf[0] == CONTROL('K'))
449 return tstr_control_k;
450 return (buf);
452 case '^':
454 * Carat means CONTROL.
456 *pp = p+2;
457 buf[0] = CONTROL(p[1]);
458 buf[1] = '\0';
459 if (buf[0] == CONTROL('K'))
460 return tstr_control_k;
461 return (buf);
463 *pp = p+1;
464 buf[0] = *p;
465 buf[1] = '\0';
466 if (xlate && buf[0] == CONTROL('K'))
467 return tstr_control_k;
468 return (buf);
472 * Skip leading spaces in a string.
474 public char *
475 skipsp(s)
476 register char *s;
478 while (*s == ' ' || *s == '\t')
479 s++;
480 return (s);
484 * Skip non-space characters in a string.
486 public char *
487 skipnsp(s)
488 register char *s;
490 while (*s != '\0' && *s != ' ' && *s != '\t')
491 s++;
492 return (s);
496 * Clean up an input line:
497 * strip off the trailing newline & any trailing # comment.
499 char *
500 clean_line(s)
501 char *s;
503 register int i;
505 s = skipsp(s);
506 for (i = 0; s[i] != '\n' && s[i] != '\r' && s[i] != '\0'; i++)
507 if (s[i] == '#' && (i == 0 || s[i-1] != '\\'))
508 break;
509 s[i] = '\0';
510 return (s);
514 * Add a byte to the output command table.
516 void
517 add_cmd_char(c)
518 int c;
520 if (currtable->pbuffer >= currtable->buffer + MAX_USERCMD)
522 terror("too many commands");
523 exit(1);
525 *(currtable->pbuffer)++ = c;
529 * Add a string to the output command table.
531 void
532 add_cmd_str(s)
533 char *s;
535 for ( ; *s != '\0'; s++)
536 add_cmd_char(*s);
540 * See if we have a special "control" line.
543 control_line(s)
544 char *s;
546 #define PREFIX(str,pat) (strncmp(str,pat,strlen(pat)-1) == 0)
548 if (PREFIX(s, "#line-edit"))
550 currtable = &edittable;
551 return (1);
553 if (PREFIX(s, "#command"))
555 currtable = &cmdtable;
556 return (1);
558 if (PREFIX(s, "#env"))
560 currtable = &vartable;
561 return (1);
563 if (PREFIX(s, "#stop"))
565 add_cmd_char('\0');
566 add_cmd_char(A_END_LIST);
567 return (1);
569 return (0);
573 * Output some bytes.
575 void
576 fputbytes(fd, buf, len)
577 FILE *fd;
578 char *buf;
579 int len;
581 while (len-- > 0)
583 fwrite(buf, sizeof(char), 1, fd);
584 buf++;
589 * Output an integer, in special KRADIX form.
591 void
592 fputint(fd, val)
593 FILE *fd;
594 unsigned int val;
596 char c;
598 if (val >= KRADIX*KRADIX)
600 fprintf(stderr, "error: integer too big (%d > %d)\n",
601 val, KRADIX*KRADIX);
602 exit(1);
604 c = val % KRADIX;
605 fwrite(&c, sizeof(char), 1, fd);
606 c = val / KRADIX;
607 fwrite(&c, sizeof(char), 1, fd);
611 * Find an action, given the name of the action.
614 findaction(actname)
615 char *actname;
617 int i;
619 for (i = 0; currtable->names[i].cn_name != NULL; i++)
620 if (strcmp(currtable->names[i].cn_name, actname) == 0)
621 return (currtable->names[i].cn_action);
622 terror("unknown action");
623 return (A_INVALID);
626 void
627 terror(s)
628 char *s;
630 fprintf(stderr, "line %d: %s\n", linenum, s);
631 errors++;
635 void
636 parse_cmdline(p)
637 char *p;
639 int cmdlen;
640 char *actname;
641 int action;
642 char *s;
643 char c;
646 * Parse the command string and store it in the current table.
648 cmdlen = 0;
651 s = tstr(&p, 1);
652 cmdlen += strlen(s);
653 if (cmdlen > MAX_CMDLEN)
654 terror("command too long");
655 else
656 add_cmd_str(s);
657 } while (*p != ' ' && *p != '\t' && *p != '\0');
659 * Terminate the command string with a null byte.
661 add_cmd_char('\0');
664 * Skip white space between the command string
665 * and the action name.
666 * Terminate the action name with a null byte.
668 p = skipsp(p);
669 if (*p == '\0')
671 terror("missing action");
672 return;
674 actname = p;
675 p = skipnsp(p);
676 c = *p;
677 *p = '\0';
680 * Parse the action name and store it in the current table.
682 action = findaction(actname);
685 * See if an extra string follows the action name.
687 *p = c;
688 p = skipsp(p);
689 if (*p == '\0')
691 add_cmd_char(action);
692 } else
695 * OR the special value A_EXTRA into the action byte.
696 * Put the extra string after the action byte.
698 add_cmd_char(action | A_EXTRA);
699 while (*p != '\0')
700 add_cmd_str(tstr(&p, 0));
701 add_cmd_char('\0');
705 void
706 parse_varline(p)
707 char *p;
709 char *s;
713 s = tstr(&p, 0);
714 add_cmd_str(s);
715 } while (*p != ' ' && *p != '\t' && *p != '=' && *p != '\0');
717 * Terminate the variable name with a null byte.
719 add_cmd_char('\0');
721 p = skipsp(p);
722 if (*p++ != '=')
724 terror("missing =");
725 return;
728 add_cmd_char(EV_OK|A_EXTRA);
730 p = skipsp(p);
731 while (*p != '\0')
733 s = tstr(&p, 0);
734 add_cmd_str(s);
736 add_cmd_char('\0');
740 * Parse a line from the lesskey file.
742 void
743 parse_line(line)
744 char *line;
746 char *p;
749 * See if it is a control line.
751 if (control_line(line))
752 return;
754 * Skip leading white space.
755 * Replace the final newline with a null byte.
756 * Ignore blank lines and comments.
758 p = clean_line(line);
759 if (*p == '\0')
760 return;
762 if (currtable == &vartable)
763 parse_varline(p);
764 else
765 parse_cmdline(p);
769 main(argc, argv)
770 int argc;
771 char *argv[];
773 FILE *desc;
774 FILE *out;
775 char line[1024];
777 #ifdef WIN32
778 if (getenv("HOME") == NULL)
781 * If there is no HOME environment variable,
782 * try the concatenation of HOMEDRIVE + HOMEPATH.
784 char *drive = getenv("HOMEDRIVE");
785 char *path = getenv("HOMEPATH");
786 if (drive != NULL && path != NULL)
788 char *env = (char *) calloc(strlen(drive) +
789 strlen(path) + 6, sizeof(char));
790 strcpy(env, "HOME=");
791 strcat(env, drive);
792 strcat(env, path);
793 putenv(env);
796 #endif /* WIN32 */
799 * Process command line arguments.
801 parse_args(argc, argv);
802 init_tables();
805 * Open the input file.
807 if (strcmp(infile, "-") == 0)
808 desc = stdin;
809 else if ((desc = fopen(infile, "r")) == NULL)
811 #if HAVE_PERROR
812 perror(infile);
813 #else
814 fprintf(stderr, "Cannot open %s\n", infile);
815 #endif
816 usage();
820 * Read and parse the input file, one line at a time.
822 errors = 0;
823 linenum = 0;
824 while (fgets(line, sizeof(line), desc) != NULL)
826 ++linenum;
827 parse_line(line);
831 * Write the output file.
832 * If no output file was specified, use "$HOME/.less"
834 if (errors > 0)
836 fprintf(stderr, "%d errors; no output produced\n", errors);
837 exit(1);
840 if (outfile == NULL)
841 outfile = getenv("LESSKEY");
842 if (outfile == NULL)
843 outfile = homefile(LESSKEYFILE);
844 if ((out = fopen(outfile, "wb")) == NULL)
846 #if HAVE_PERROR
847 perror(outfile);
848 #else
849 fprintf(stderr, "Cannot open %s\n", outfile);
850 #endif
851 exit(1);
854 /* File header */
855 fputbytes(out, fileheader, sizeof(fileheader));
857 /* Command key section */
858 fputbytes(out, cmdsection, sizeof(cmdsection));
859 fputint(out, cmdtable.pbuffer - cmdtable.buffer);
860 fputbytes(out, (char *)cmdtable.buffer, cmdtable.pbuffer-cmdtable.buffer);
861 /* Edit key section */
862 fputbytes(out, editsection, sizeof(editsection));
863 fputint(out, edittable.pbuffer - edittable.buffer);
864 fputbytes(out, (char *)edittable.buffer, edittable.pbuffer-edittable.buffer);
866 /* Environment variable section */
867 fputbytes(out, varsection, sizeof(varsection));
868 fputint(out, vartable.pbuffer - vartable.buffer);
869 fputbytes(out, (char *)vartable.buffer, vartable.pbuffer-vartable.buffer);
871 /* File trailer */
872 fputbytes(out, endsection, sizeof(endsection));
873 fputbytes(out, filetrailer, sizeof(filetrailer));
874 return (0);