1 /* Copyright (c) 2010
2  *      Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
3  *      Sadrul Habib Chowdhury (sadrul@users.sourceforge.net)
4  * Copyright (c) 2008, 2009
5  *      Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
6  *      Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
7  *      Micah Cowan (micah@cowan.name)
8  *      Sadrul Habib Chowdhury (sadrul@users.sourceforge.net)
9  * Copyright (c) 1993-2002, 2003, 2005, 2006, 2007
10  *      Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
11  *      Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
12  * Copyright (c) 1987 Oliver Laumann
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 3, or (at your option)
17  * any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program (see the file COPYING); if not, see
26  * https://www.gnu.org/licenses/, or contact Free Software Foundation, Inc.,
27  * 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
28  *
29  ****************************************************************
30  */
31 
32 #include "config.h"
33 
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #if !defined(sun) && !defined(B43) && !defined(ISC) && !defined(pyr) && !defined(_CX_UX)
39 # include <time.h>
40 #endif
41 #include <sys/time.h>
42 #ifndef sun
43 #include <sys/ioctl.h>
44 #endif
45 
46 
47 /* for solaris 2.1, Unixware (SVR4.2) and possibly others: */
48 #ifdef HAVE_STROPTS_H
49 # include <sys/stropts.h>
50 #endif
51 
52 #include "screen.h"
53 #include "extern.h"
54 #include "logfile.h"
55 #include "layout.h"
56 #include "viewport.h"
57 #include "list_generic.h"
58 
59 extern struct comm comms[];
60 extern char *rc_name;
61 extern char *RcFileName, *home;
62 extern char *BellString, *ActivityString, *ShellProg, *ShellArgs[];
63 extern char *hstatusstring, *captionstring, *timestring;
64 extern char *wliststr, *wlisttit;
65 extern int captionalways;
66 extern int queryflag;
67 extern char *hardcopydir, *screenlogfile, *logtstamp_string;
68 extern int log_flush, logtstamp_on, logtstamp_after;
69 extern char *VisualBellString;
70 extern int VBellWait, MsgWait, MsgMinWait, SilenceWait;
71 extern char SockPath[], *SockName;
72 extern int TtyMode, auto_detach, use_altscreen;
73 extern int iflag, maxwin;
74 extern int focusminwidth, focusminheight;
75 extern int use_hardstatus, visual_bell;
76 #ifdef COLOR
77 extern int attr2color[][4];
78 extern int nattr2color;
79 #endif
80 extern int hardstatusemu;
81 extern char *printcmd;
82 extern int default_startup;
83 extern int defobuflimit;
84 extern int defnonblock;
85 extern int defmousetrack;
86 extern int ZombieKey_destroy;
87 extern int ZombieKey_resurrect;
88 extern int ZombieKey_onerror;
89 #ifdef AUTO_NUKE
90 extern int defautonuke;
91 #endif
92 extern int separate_sids;
93 extern struct NewWindow nwin_default, nwin_undef;
94 #ifdef COPY_PASTE
95 extern int join_with_cr;
96 extern int compacthist;
97 extern int search_ic;
98 # ifdef FONT
99 extern int pastefont;
100 # endif
101 extern unsigned char mark_key_tab[];
102 extern char *BufferFile;
103 #endif
104 #ifdef POW_DETACH
105 extern char *BufferFile, *PowDetachString;
106 #endif
107 #ifdef MULTIUSER
108 extern struct acluser *EffectiveAclUser;	/* acl.c */
109 #endif
110 extern struct term term[];      /* terminal capabilities */
111 #ifdef MAPKEYS
112 extern char *kmapdef[];
113 extern char *kmapadef[];
114 extern char *kmapmdef[];
115 #endif
116 extern struct mchar mchar_so, mchar_null;
117 extern int renditions[];
118 extern int VerboseCreate;
119 #ifdef UTF8
120 extern char *screenencodings;
121 #endif
122 #ifdef DW_CHARS
123 extern int cjkwidth;
124 #endif
125 
126 static int  CheckArgNum __P((int, char **));
127 static void ClearAction __P((struct action *));
128 static void SaveAction __P((struct action *, int, char **, int *));
129 static int  NextWindow __P((void));
130 static int  PreviousWindow __P((void));
131 static int  MoreWindows __P((void));
132 static void CollapseWindowlist __P((void));
133 static void LogToggle __P((int));
134 static void ShowInfo __P((void));
135 static void ShowDInfo __P((void));
136 static struct win *WindowByName __P((char *));
137 static int  WindowByNumber __P((char *));
138 static int  ParseOnOff __P((struct action *, int *));
139 static int  ParseWinNum __P((struct action *, int *));
140 static int  ParseBase __P((struct action *, char *, int *, int, char *));
141 static int  ParseNum1000 __P((struct action *, int *));
142 static char **SaveArgs __P((char **));
143 static int  IsNum __P((char *, int));
144 static void Colonfin __P((char *, int, char *));
145 static void InputSelect __P((void));
146 static void InputSetenv __P((char *));
147 static void InputAKA __P((void));
148 #ifdef MULTIUSER
149 static int  InputSu __P((struct win *, struct acluser **, char *));
150 static void su_fin __P((char *, int, char *));
151 #endif
152 static void AKAfin __P((char *, int, char *));
153 #ifdef COPY_PASTE
154 static void copy_reg_fn __P((char *, int, char *));
155 static void ins_reg_fn __P((char *, int, char *));
156 #endif
157 static void process_fn __P((char *, int, char *));
158 #ifdef PASSWORD
159 static void pass1 __P((char *, int, char *));
160 static void pass2 __P((char *, int, char *));
161 #endif
162 #ifdef POW_DETACH
163 static void pow_detach_fn __P((char *, int, char *));
164 #endif
165 static void digraph_fn __P((char *, int, char *));
166 static int  digraph_find __P((const char *buf));
167 static void confirm_fn __P((char *, int, char *));
168 static int  IsOnDisplay __P((struct win *));
169 static void ResizeRegions __P((char *, int));
170 static void ResizeFin __P((char *, int, char *));
171 static struct action *FindKtab __P((char *, int));
172 static void SelectFin __P((char *, int, char *));
173 static void SelectLayoutFin __P((char *, int, char *));
174 static void ShowWindowsX __P((char *));
175 
176 
177 extern struct layer *flayer;
178 extern struct display *display, *displays;
179 extern struct win *fore, *console_window, *windows;
180 extern struct acluser *users;
181 extern struct layout *layouts, *layout_attach, layout_last_marker;
182 extern struct layout *laytab[];
183 
184 extern char screenterm[], HostName[], version[];
185 extern struct NewWindow nwin_undef, nwin_default;
186 extern struct LayFuncs WinLf, MarkLf;
187 
188 extern const int Z0width, Z1width;
189 extern int real_uid, real_gid;
190 
191 #ifdef NETHACK
192 extern int nethackflag;
193 #endif
194 
195 
196 extern struct win **wtab;
197 
198 #ifdef MULTIUSER
199 extern char *multi;
200 extern int maxusercount;
201 #endif
202 char NullStr[] = "";
203 
204 struct plop plop_tab[MAX_PLOP_DEFS];
205 
206 #ifndef PTYMODE
207 # define PTYMODE 0622
208 #endif
209 
210 int TtyMode = PTYMODE;
211 int hardcopy_append = 0;
212 int all_norefresh = 0;
213 #ifdef ZMODEM
214 int zmodem_mode = 0;
215 char *zmodem_sendcmd;
216 char *zmodem_recvcmd;
217 static char *zmodes[4] = {"off", "auto", "catch", "pass"};
218 #endif
219 
220 int idletimo;
221 struct action idleaction;
222 #ifdef BLANKER_PRG
223 char **blankerprg;
224 #endif
225 
226 struct action ktab[256 + KMAP_KEYS];	/* command key translation table */
227 struct kclass {
228   struct kclass *next;
229   char *name;
230   struct action ktab[256 + KMAP_KEYS];
231 };
232 struct kclass *kclasses;
233 
234 #ifdef MAPKEYS
235 struct action umtab[KMAP_KEYS+KMAP_AKEYS];
236 struct action dmtab[KMAP_KEYS+KMAP_AKEYS];
237 struct action mmtab[KMAP_KEYS+KMAP_AKEYS];
238 struct kmap_ext *kmap_exts;
239 int kmap_extn;
240 static int maptimeout = 300;
241 #endif
242 
243 #ifndef MAX_DIGRAPH
244 #define MAX_DIGRAPH 512
245 #endif
246 
247 struct digraph
248 {
249   unsigned char d[2];
250   int value;
251 };
252 
253 /* digraph table taken from old vim and rfc1345 */
254 static struct digraph digraphs[MAX_DIGRAPH + 1] = {
255     {{' ', ' '}, 160},	/* � */
256     {{'N', 'S'}, 160},	/* � */
257     {{'~', '!'}, 161},	/* � */
258     {{'!', '!'}, 161},	/* � */
259     {{'!', 'I'}, 161},	/* � */
260     {{'c', '|'}, 162},	/* � */
261     {{'c', 't'}, 162},	/* � */
262     {{'$', '$'}, 163},	/* � */
263     {{'P', 'd'}, 163},	/* � */
264     {{'o', 'x'}, 164},	/* � */
265     {{'C', 'u'}, 164},	/* � */
266     {{'C', 'u'}, 164},	/* � */
267     {{'E', 'u'}, 164},	/* � */
268     {{'Y', '-'}, 165},	/* � */
269     {{'Y', 'e'}, 165},	/* � */
270     {{'|', '|'}, 166},	/* � */
271     {{'B', 'B'}, 166},	/* � */
272     {{'p', 'a'}, 167},	/* � */
273     {{'S', 'E'}, 167},	/* � */
274     {{'"', '"'}, 168},	/* � */
275     {{'\'', ':'}, 168},	/* � */
276     {{'c', 'O'}, 169},	/* � */
277     {{'C', 'o'}, 169},	/* � */
278     {{'a', '-'}, 170},	/* � */
279     {{'<', '<'}, 171},	/* � */
280     {{'-', ','}, 172},	/* � */
281     {{'N', 'O'}, 172},	/* � */
282     {{'-', '-'}, 173},	/* � */
283     {{'r', 'O'}, 174},	/* � */
284     {{'R', 'g'}, 174},	/* � */
285     {{'-', '='}, 175},	/* � */
286     {{'\'', 'm'}, 175},	/* � */
287     {{'~', 'o'}, 176},	/* � */
288     {{'D', 'G'}, 176},	/* � */
289     {{'+', '-'}, 177},	/* � */
290     {{'2', '2'}, 178},	/* � */
291     {{'2', 'S'}, 178},	/* � */
292     {{'3', '3'}, 179},	/* � */
293     {{'3', 'S'}, 179},	/* � */
294     {{'\'', '\''}, 180},	/* � */
295     {{'j', 'u'}, 181},	/* � */
296     {{'M', 'y'}, 181},	/* � */
297     {{'p', 'p'}, 182},	/* � */
298     {{'P', 'I'}, 182},	/* � */
299     {{'~', '.'}, 183},	/* � */
300     {{'.', 'M'}, 183},	/* � */
301     {{',', ','}, 184},	/* � */
302     {{'\'', ','}, 184},	/* � */
303     {{'1', '1'}, 185},	/* � */
304     {{'1', 'S'}, 185},	/* � */
305     {{'o', '-'}, 186},	/* � */
306     {{'>', '>'}, 187},	/* � */
307     {{'1', '4'}, 188},	/* � */
308     {{'1', '2'}, 189},	/* � */
309     {{'3', '4'}, 190},	/* � */
310     {{'~', '?'}, 191},	/* � */
311     {{'?', '?'}, 191},	/* � */
312     {{'?', 'I'}, 191},	/* � */
313     {{'A', '`'}, 192},	/* � */
314     {{'A', '!'}, 192},	/* � */
315     {{'A', '\''}, 193},	/* � */
316     {{'A', '^'}, 194},	/* � */
317     {{'A', '>'}, 194},	/* � */
318     {{'A', '~'}, 195},	/* � */
319     {{'A', '?'}, 195},	/* � */
320     {{'A', '"'}, 196},	/* � */
321     {{'A', ':'}, 196},	/* � */
322     {{'A', '@'}, 197},	/* � */
323     {{'A', 'A'}, 197},	/* � */
324     {{'A', 'E'}, 198},	/* � */
325     {{'C', ','}, 199},	/* � */
326     {{'E', '`'}, 200},	/* � */
327     {{'E', '!'}, 200},	/* � */
328     {{'E', '\''}, 201},	/* � */
329     {{'E', '^'}, 202},	/* � */
330     {{'E', '>'}, 202},	/* � */
331     {{'E', '"'}, 203},	/* � */
332     {{'E', ':'}, 203},	/* � */
333     {{'I', '`'}, 204},	/* � */
334     {{'I', '!'}, 204},	/* � */
335     {{'I', '\''}, 205},	/* � */
336     {{'I', '^'}, 206},	/* � */
337     {{'I', '>'}, 206},	/* � */
338     {{'I', '"'}, 207},	/* � */
339     {{'I', ':'}, 207},	/* � */
340     {{'D', '-'}, 208},	/* � */
341     {{'N', '~'}, 209},	/* � */
342     {{'N', '?'}, 209},	/* � */
343     {{'O', '`'}, 210},	/* � */
344     {{'O', '!'}, 210},	/* � */
345     {{'O', '\''}, 211},	/* � */
346     {{'O', '^'}, 212},	/* � */
347     {{'O', '>'}, 212},	/* � */
348     {{'O', '~'}, 213},	/* � */
349     {{'O', '?'}, 213},	/* � */
350     {{'O', '"'}, 214},	/* � */
351     {{'O', ':'}, 214},	/* � */
352     {{'/', '\\'}, 215},	/* � */
353     {{'*', 'x'}, 215},	/* � */
354     {{'O', '/'}, 216},	/* � */
355     {{'U', '`'}, 217},	/* � */
356     {{'U', '!'}, 217},	/* � */
357     {{'U', '\''}, 218},	/* � */
358     {{'U', '^'}, 219},	/* � */
359     {{'U', '>'}, 219},	/* � */
360     {{'U', '"'}, 220},	/* � */
361     {{'U', ':'}, 220},	/* � */
362     {{'Y', '\''}, 221},	/* � */
363     {{'I', 'p'}, 222},	/* � */
364     {{'T', 'H'}, 222},	/* � */
365     {{'s', 's'}, 223},	/* � */
366     {{'s', '"'}, 223},	/* � */
367     {{'a', '`'}, 224},	/* � */
368     {{'a', '!'}, 224},	/* � */
369     {{'a', '\''}, 225},	/* � */
370     {{'a', '^'}, 226},	/* � */
371     {{'a', '>'}, 226},	/* � */
372     {{'a', '~'}, 227},	/* � */
373     {{'a', '?'}, 227},	/* � */
374     {{'a', '"'}, 228},	/* � */
375     {{'a', ':'}, 228},	/* � */
376     {{'a', 'a'}, 229},	/* � */
377     {{'a', 'e'}, 230},	/* � */
378     {{'c', ','}, 231},	/* � */
379     {{'e', '`'}, 232},	/* � */
380     {{'e', '!'}, 232},	/* � */
381     {{'e', '\''}, 233},	/* � */
382     {{'e', '^'}, 234},	/* � */
383     {{'e', '>'}, 234},	/* � */
384     {{'e', '"'}, 235},	/* � */
385     {{'e', ':'}, 235},	/* � */
386     {{'i', '`'}, 236},	/* � */
387     {{'i', '!'}, 236},	/* � */
388     {{'i', '\''}, 237},	/* � */
389     {{'i', '^'}, 238},	/* � */
390     {{'i', '>'}, 238},	/* � */
391     {{'i', '"'}, 239},	/* � */
392     {{'i', ':'}, 239},	/* � */
393     {{'d', '-'}, 240},	/* � */
394     {{'n', '~'}, 241},	/* � */
395     {{'n', '?'}, 241},	/* � */
396     {{'o', '`'}, 242},	/* � */
397     {{'o', '!'}, 242},	/* � */
398     {{'o', '\''}, 243},	/* � */
399     {{'o', '^'}, 244},	/* � */
400     {{'o', '>'}, 244},	/* � */
401     {{'o', '~'}, 245},	/* � */
402     {{'o', '?'}, 245},	/* � */
403     {{'o', '"'}, 246},	/* � */
404     {{'o', ':'}, 246},	/* � */
405     {{':', '-'}, 247},	/* � */
406     {{'o', '/'}, 248},	/* � */
407     {{'u', '`'}, 249},	/* � */
408     {{'u', '!'}, 249},	/* � */
409     {{'u', '\''}, 250},	/* � */
410     {{'u', '^'}, 251},	/* � */
411     {{'u', '>'}, 251},	/* � */
412     {{'u', '"'}, 252},	/* � */
413     {{'u', ':'}, 252},	/* � */
414     {{'y', '\''}, 253},	/* � */
415     {{'i', 'p'}, 254},	/* � */
416     {{'t', 'h'}, 254},	/* � */
417     {{'y', '"'}, 255},	/* � */
418     {{'y', ':'}, 255},	/* � */
419     {{'"', '['}, 196},	/* � */
420     {{'"', '\\'}, 214},	/* � */
421     {{'"', ']'}, 220},	/* � */
422     {{'"', '{'}, 228},	/* � */
423     {{'"', '|'}, 246},	/* � */
424     {{'"', '}'}, 252},	/* � */
425     {{'"', '~'}, 223}	/* � */
426 };
427 
428 #define RESIZE_FLAG_H 1
429 #define RESIZE_FLAG_V 2
430 #define RESIZE_FLAG_L 4
431 
432 static char *resizeprompts[] = {
433   "resize # lines: ",
434   "resize -h # lines: ",
435   "resize -v # lines: ",
436   "resize -b # lines: ",
437   "resize -l # lines: ",
438   "resize -l -h # lines: ",
439   "resize -l -v # lines: ",
440   "resize -l -b # lines: ",
441 };
442 
443 
444 static int
parse_input_int(buf,len,val)445 parse_input_int(buf, len, val)
446 const char *buf;
447 int len;
448 int *val;
449 {
450   int x = 0, i;
451   if (len >= 1 && ((*buf == 'U' && buf[1] == '+') || (*buf == '0' && (buf[1] == 'x' || buf[1] == 'X'))))
452     {
453       x = 0;
454       for (i = 2; i < len; i++)
455 	{
456 	  if (buf[i] >= '0' && buf[i] <= '9')
457 	    x = x * 16 | (buf[i] - '0');
458 	  else if (buf[i] >= 'a' && buf[i] <= 'f')
459 	    x = x * 16 | (buf[i] - ('a' - 10));
460 	  else if (buf[i] >= 'A' && buf[i] <= 'F')
461 	    x = x * 16 | (buf[i] - ('A' - 10));
462 	  else
463 	    return 0;
464 	}
465     }
466   else if (buf[0] == '0')
467     {
468       x = 0;
469       for (i = 1; i < len; i++)
470 	{
471 	  if (buf[i] < '0' || buf[i] > '7')
472 	    return 0;
473 	  x = x * 8 | (buf[i] - '0');
474 	}
475     }
476   else
477     return 0;
478   *val = x;
479   return 1;
480 }
481 
482 char *noargs[1];
483 
484 int enter_window_name_mode = 0;
485 
486 void
InitKeytab()487 InitKeytab()
488 {
489   register unsigned int i;
490 #ifdef MAPKEYS
491   char *argarr[2];
492 #endif
493 
494   for (i = 0; i < sizeof(ktab)/sizeof(*ktab); i++)
495     {
496       ktab[i].nr = RC_ILLEGAL;
497       ktab[i].args = noargs;
498       ktab[i].argl = 0;
499     }
500 #ifdef MAPKEYS
501   for (i = 0; i < KMAP_KEYS+KMAP_AKEYS; i++)
502     {
503       umtab[i].nr = RC_ILLEGAL;
504       umtab[i].args = noargs;
505       umtab[i].argl = 0;
506       dmtab[i].nr = RC_ILLEGAL;
507       dmtab[i].args = noargs;
508       dmtab[i].argl = 0;
509       mmtab[i].nr = RC_ILLEGAL;
510       mmtab[i].args = noargs;
511       mmtab[i].argl = 0;
512     }
513   argarr[1] = 0;
514   for (i = 0; i < NKMAPDEF; i++)
515     {
516       if (i + KMAPDEFSTART < T_CAPS)
517 	continue;
518       if (i + KMAPDEFSTART >= T_CAPS + KMAP_KEYS)
519 	continue;
520       if (kmapdef[i] == 0)
521 	continue;
522       argarr[0] = kmapdef[i];
523       SaveAction(dmtab + i + (KMAPDEFSTART - T_CAPS), RC_STUFF, argarr, 0);
524     }
525   for (i = 0; i < NKMAPADEF; i++)
526     {
527       if (i + KMAPADEFSTART < T_CURSOR)
528 	continue;
529       if (i + KMAPADEFSTART >= T_CURSOR + KMAP_AKEYS)
530 	continue;
531       if (kmapadef[i] == 0)
532 	continue;
533       argarr[0] = kmapadef[i];
534       SaveAction(dmtab + i + (KMAPADEFSTART - T_CURSOR + KMAP_KEYS), RC_STUFF, argarr, 0);
535     }
536   for (i = 0; i < NKMAPMDEF; i++)
537     {
538       if (i + KMAPMDEFSTART < T_CAPS)
539 	continue;
540       if (i + KMAPMDEFSTART >= T_CAPS + KMAP_KEYS)
541 	continue;
542       if (kmapmdef[i] == 0)
543 	continue;
544       argarr[0] = kmapmdef[i];
545       argarr[1] = 0;
546       SaveAction(mmtab + i + (KMAPMDEFSTART - T_CAPS), RC_STUFF, argarr, 0);
547     }
548 #endif
549 
550   ktab['h'].nr = RC_HARDCOPY;
551 #ifdef BSDJOBS
552   ktab['z'].nr = ktab[Ctrl('z')].nr = RC_SUSPEND;
553 #endif
554   ktab['c'].nr = ktab[Ctrl('c')].nr = RC_SCREEN;
555   ktab[' '].nr = ktab[Ctrl(' ')].nr =
556     ktab['n'].nr = ktab[Ctrl('n')].nr = RC_NEXT;
557   ktab['N'].nr = RC_NUMBER;
558   ktab[Ctrl('h')].nr = ktab[0177].nr = ktab['p'].nr = ktab[Ctrl('p')].nr = RC_PREV;
559   ktab['k'].nr = ktab[Ctrl('k')].nr = RC_KILL;
560   ktab['l'].nr = ktab[Ctrl('l')].nr = RC_REDISPLAY;
561   ktab['w'].nr = ktab[Ctrl('w')].nr = RC_WINDOWS;
562   ktab['v'].nr = RC_VERSION;
563   ktab[Ctrl('v')].nr = RC_DIGRAPH;
564   ktab['q'].nr = ktab[Ctrl('q')].nr = RC_XON;
565   ktab['s'].nr = ktab[Ctrl('s')].nr = RC_XOFF;
566   ktab['t'].nr = ktab[Ctrl('t')].nr = RC_TIME;
567   ktab['i'].nr = ktab[Ctrl('i')].nr = RC_INFO;
568   ktab['m'].nr = ktab[Ctrl('m')].nr = RC_LASTMSG;
569   ktab['A'].nr = RC_TITLE;
570 #if defined(UTMPOK) && defined(LOGOUTOK)
571   ktab['L'].nr = RC_LOGIN;
572 #endif
573   ktab[','].nr = RC_LICENSE;
574   ktab['W'].nr = RC_WIDTH;
575   ktab['.'].nr = RC_DUMPTERMCAP;
576   ktab[Ctrl('\\')].nr = RC_QUIT;
577 #ifdef DETACH
578   ktab['d'].nr = ktab[Ctrl('d')].nr = RC_DETACH;
579 # ifdef POW_DETACH
580   ktab['D'].nr = RC_POW_DETACH;
581 # endif
582 #endif
583   ktab['r'].nr = ktab[Ctrl('r')].nr = RC_WRAP;
584   ktab['f'].nr = ktab[Ctrl('f')].nr = RC_FLOW;
585   ktab['C'].nr = RC_CLEAR;
586   ktab['Z'].nr = RC_RESET;
587   ktab['H'].nr = RC_LOG;
588   ktab['M'].nr = RC_MONITOR;
589   ktab['?'].nr = RC_HELP;
590 #ifdef MULTI
591   ktab['*'].nr = RC_DISPLAYS;
592 #endif
593   {
594     char *args[2];
595     args[0] = "-";
596     args[1] = NULL;
597     SaveAction(ktab + '-', RC_SELECT, args, 0);
598   }
599   for (i = 0; i < ((maxwin && maxwin < 10) ? maxwin : 10); i++)
600     {
601       char *args[2], arg1[10];
602       args[0] = arg1;
603       args[1] = 0;
604       sprintf(arg1, "%d", i);
605       SaveAction(ktab + '0' + i, RC_SELECT, args, 0);
606     }
607   ktab['\''].nr = RC_SELECT; /* calling a window by name */
608   {
609     char *args[2];
610     args[0] = "-b";
611     args[1] = 0;
612     SaveAction(ktab + '"', RC_WINDOWLIST, args, 0);
613   }
614   ktab[Ctrl('G')].nr = RC_VBELL;
615   ktab[':'].nr = RC_COLON;
616 #ifdef COPY_PASTE
617   ktab['['].nr = ktab[Ctrl('[')].nr = RC_COPY;
618   {
619     char *args[2];
620     args[0] = ".";
621     args[1] = 0;
622     SaveAction(ktab + ']', RC_PASTE, args, 0);
623     SaveAction(ktab + Ctrl(']'), RC_PASTE, args, 0);
624   }
625   ktab['{'].nr = RC_HISTORY;
626   ktab['}'].nr = RC_HISTORY;
627   ktab['>'].nr = RC_WRITEBUF;
628   ktab['<'].nr = RC_READBUF;
629   ktab['='].nr = RC_REMOVEBUF;
630 #endif
631 #ifdef POW_DETACH
632   ktab['D'].nr = RC_POW_DETACH;
633 #endif
634 #ifdef LOCK
635   ktab['x'].nr = ktab[Ctrl('x')].nr = RC_LOCKSCREEN;
636 #endif
637   ktab['b'].nr = ktab[Ctrl('b')].nr = RC_BREAK;
638   ktab['B'].nr = RC_POW_BREAK;
639   ktab['_'].nr = RC_SILENCE;
640   ktab['S'].nr = RC_SPLIT;
641   ktab['Q'].nr = RC_ONLY;
642   ktab['X'].nr = RC_REMOVE;
643   ktab['F'].nr = RC_FIT;
644   ktab['\t'].nr = RC_FOCUS;
645   {
646     char *args[2];
647     args[0] = "prev";
648     args[1] = 0;
649     SaveAction(ktab + T_BACKTAB - T_CAPS + 256, RC_FOCUS, args, 0);
650   }
651   {
652     char *args[2];
653     args[0] = "-v";
654     args[1] = 0;
655     SaveAction(ktab + '|', RC_SPLIT, args, 0);
656   }
657   /* These come last; they may want overwrite others: */
658   if (DefaultEsc >= 0)
659     {
660       ClearAction(&ktab[DefaultEsc]);
661       ktab[DefaultEsc].nr = RC_OTHER;
662     }
663   if (DefaultMetaEsc >= 0)
664     {
665       ClearAction(&ktab[DefaultMetaEsc]);
666       ktab[DefaultMetaEsc].nr = RC_META;
667     }
668 
669   idleaction.nr = RC_BLANKER;
670   idleaction.args = noargs;
671   idleaction.argl = 0;
672 }
673 
674 static struct action *
FindKtab(class,create)675 FindKtab(class, create)
676 char *class;
677 int create;
678 {
679   struct kclass *kp, **kpp;
680   int i;
681 
682   if (class == 0)
683     return ktab;
684   for (kpp = &kclasses; (kp = *kpp) != 0; kpp = &kp->next)
685     if (!strcmp(kp->name, class))
686       break;
687   if (kp == 0)
688     {
689       if (!create)
690 	return 0;
691       if (strlen(class) > 80)
692 	{
693 	  Msg(0, "Command class name too long.");
694 	  return 0;
695 	}
696       kp = malloc(sizeof(*kp));
697       if (kp == 0)
698 	{
699 	  Msg(0, "%s", strnomem);
700 	  return 0;
701 	}
702       kp->name = SaveStr(class);
703       for (i = 0; i < (int)(sizeof(kp->ktab)/sizeof(*kp->ktab)); i++)
704 	{
705 	  kp->ktab[i].nr = RC_ILLEGAL;
706 	  kp->ktab[i].args = noargs;
707 	  kp->ktab[i].argl = 0;
708 	  kp->ktab[i].quiet = 0;
709 	}
710       kp->next = 0;
711       *kpp = kp;
712     }
713   return kp->ktab;
714 }
715 
716 static void
ClearAction(act)717 ClearAction(act)
718 struct action *act;
719 {
720   char **p;
721 
722   if (act->nr == RC_ILLEGAL)
723     return;
724   act->nr = RC_ILLEGAL;
725   if (act->args == noargs)
726     return;
727   for (p = act->args; *p; p++)
728     free(*p);
729   free((char *)act->args);
730   act->args = noargs;
731   act->argl = 0;
732 }
733 
734 /*
735  * ProcessInput: process input from display and feed it into
736  * the layer on canvas D_forecv.
737  */
738 
739 #ifdef MAPKEYS
740 
741 /*
742  *  This ProcessInput just does the keybindings and passes
743  *  everything else on to ProcessInput2.
744  */
745 
746 void
ProcessInput(ibuf,ilen)747 ProcessInput(ibuf, ilen)
748 char *ibuf;
749 int ilen;
750 {
751   int ch, slen;
752   unsigned char *s, *q;
753   int i, l;
754   char *p;
755 
756   debug1("ProcessInput: %d bytes\n", ilen);
757   if (display == 0 || ilen == 0)
758     return;
759   if (D_seql)
760     evdeq(&D_mapev);
761   slen = ilen;
762   s = (unsigned char *)ibuf;
763   while (ilen-- > 0)
764     {
765       ch = *s++;
766       if (D_dontmap || !D_nseqs)
767 	{
768           D_dontmap = 0;
769 	  continue;
770 	}
771       for (;;)
772 	{
773 	  debug3("cmp %c %c[%d]\n", ch, *D_seqp, D_seqp - D_kmaps);
774 	  if (*D_seqp != ch)
775 	    {
776 	      l = D_seqp[D_seqp[-D_seql-1] + 1];
777 	      if (l)
778 		{
779 		  D_seqp += l * 2 + 4;
780 		  debug1("miss %d\n", D_seqp - D_kmaps);
781 		  continue;
782 		}
783 	      debug("complete miss\n");
784 	      D_mapdefault = 0;
785 	      l = D_seql;
786 	      p = (char *)D_seqp - l;
787 	      D_seql = 0;
788 	      D_seqp = D_kmaps + 3;
789 	      if (l == 0)
790 		break;
791 	      if ((q = D_seqh) != 0)
792 		{
793 		  D_seqh = 0;
794 		  i = q[0] << 8 | q[1];
795 		  i &= ~KMAP_NOTIMEOUT;
796 		  debug1("Mapping former hit #%d - ", i);
797 		  debug2("%d(%s) - ", q[2], q + 3);
798 		  if (StuffKey(i))
799 		    ProcessInput2((char *)q + 3, q[2]);
800 		  if (display == 0)
801 		    return;
802 		  l -= q[2];
803 		  p += q[2];
804 		}
805 	      else
806 	        D_dontmap = 1;
807 	      debug1("flush old %d\n", l);
808 	      ProcessInput(p, l);
809 	      if (display == 0)
810 		return;
811 	      evdeq(&D_mapev);
812 	      continue;
813 	    }
814 	  if (D_seql++ == 0)
815 	    {
816 	      /* Finish old stuff */
817 	      slen -= ilen + 1;
818 	      debug1("finish old %d\n", slen);
819 	      if (slen)
820 	        ProcessInput2(ibuf, slen);
821 	      if (display == 0)
822 		return;
823 	      D_seqh = 0;
824 	    }
825 	  ibuf = (char *)s;
826 	  slen = ilen;
827 	  D_seqp++;
828 	  l = D_seql;
829 	  debug2("length am %d, want %d\n", l, D_seqp[-l - 1]);
830 	  if (l == D_seqp[-l - 1])
831 	    {
832 	      if (D_seqp[l] != l)
833 		{
834 		  q = D_seqp + 1 + l;
835 		  if (D_kmaps + D_nseqs > q && q[2] > l && !bcmp(D_seqp - l, q + 3, l))
836 		    {
837 		      debug1("have another mapping (%s), delay execution\n", q + 3);
838 		      D_seqh = D_seqp - 3 - l;
839 		      D_seqp = q + 3 + l;
840 		      break;
841 		    }
842 		}
843 	      i = D_seqp[-l - 3] << 8 | D_seqp[-l - 2];
844 	      i &= ~KMAP_NOTIMEOUT;
845 	      debug1("Mapping #%d - ", i);
846 	      p = (char *)D_seqp - l;
847 	      debug2("%d(%s) - ", l, p);
848 	      D_seql = 0;
849 	      D_seqp = D_kmaps + 3;
850 	      D_seqh = 0;
851 	      if (StuffKey(i))
852 		ProcessInput2(p, l);
853 	      if (display == 0)
854 		return;
855 	    }
856 	  break;
857 	}
858     }
859   if (D_seql)
860     {
861       debug("am in sequence -> check for timeout\n");
862       l = D_seql;
863       for (s = D_seqp; ; s += i * 2 + 4)
864 	{
865 	  if (s[-l-3] & KMAP_NOTIMEOUT >> 8)
866 	    break;
867 	  if ((i = s[s[-l-1] + 1]) == 0)
868 	    {
869 	      SetTimeout(&D_mapev, maptimeout);
870 	      evenq(&D_mapev);
871 	      break;
872 	    }
873 	}
874     }
875   ProcessInput2(ibuf, slen);
876 }
877 
878 #else
879 # define ProcessInput2 ProcessInput
880 #endif
881 
882 
883 /*
884  *  Here only the screen escape commands are handled.
885  */
886 
887 void
ProcessInput2(ibuf,ilen)888 ProcessInput2(ibuf, ilen)
889 char *ibuf;
890 int ilen;
891 {
892   char *s;
893   int ch, slen;
894   struct action *ktabp;
895 
896   debug1("ProcessInput2: %d bytes\n", ilen);
897   while (ilen && display)
898     {
899       debug1(" - ilen now %d bytes\n", ilen);
900       flayer = D_forecv->c_layer;
901       fore = D_fore;
902       slen = ilen;
903       s = ibuf;
904       if (!D_ESCseen)
905 	{
906 	  while (ilen > 0)
907 	    {
908 	      if ((unsigned char)*s++ == D_user->u_Esc)
909 		break;
910 	      ilen--;
911 	    }
912 	  slen -= ilen;
913 	  if (slen)
914 	    DoProcess(fore, &ibuf, &slen, 0);
915 	  if (--ilen == 0)
916 	    {
917 	      D_ESCseen = ktab;
918 	      WindowChanged(fore, 'E');
919 	    }
920 	}
921       if (ilen <= 0)
922         return;
923       ktabp = D_ESCseen ? D_ESCseen : ktab;
924       if (D_ESCseen)
925         {
926           D_ESCseen = 0;
927           WindowChanged(fore, 'E');
928         }
929       ch = (unsigned char)*s;
930 
931       /*
932        * As users have different esc characters, but a common ktab[],
933        * we fold back the users esc and meta-esc key to the Default keys
934        * that can be looked up in the ktab[]. grmbl. jw.
935        * XXX: make ktab[] a per user thing.
936        */
937       if (ch == D_user->u_Esc)
938         ch = DefaultEsc;
939       else if (ch == D_user->u_MetaEsc)
940         ch = DefaultMetaEsc;
941 
942       if (ch >= 0)
943         DoAction(&ktabp[ch], ch);
944       ibuf = (char *)(s + 1);
945       ilen--;
946     }
947 }
948 
949 void
DoProcess(p,bufp,lenp,pa)950 DoProcess(p, bufp, lenp, pa)
951 struct win *p;
952 char **bufp;
953 int *lenp;
954 struct paster *pa;
955 {
956   int oldlen;
957   struct display *d = display;
958 
959 #ifdef COPY_PASTE
960   /* XXX -> PasteStart */
961   if (pa && *lenp > 1 && p && p->w_slowpaste)
962     {
963       /* schedule slowpaste event */
964       SetTimeout(&p->w_paster.pa_slowev, p->w_slowpaste);
965       evenq(&p->w_paster.pa_slowev);
966       return;
967     }
968 #endif
969   while (flayer && *lenp)
970     {
971 #ifdef COPY_PASTE
972       if (!pa && p && p->w_paster.pa_pastelen && flayer == p->w_paster.pa_pastelayer)
973 	{
974 	  debug("layer is busy - beep!\n");
975 	  WBell(p, visual_bell);
976 	  *bufp += *lenp;
977 	  *lenp = 0;
978 	  display = d;
979 	  return;
980 	}
981 #endif
982       oldlen = *lenp;
983       LayProcess(bufp, lenp);
984 #ifdef COPY_PASTE
985       if (pa && !pa->pa_pastelayer)
986 	break;		/* flush rest of paste */
987 #endif
988       if (*lenp == oldlen)
989 	{
990 	  if (pa)
991 	    {
992 	      display = d;
993 	      return;
994 	    }
995 	  /* We're full, let's beep */
996 	  debug("layer is full - beep!\n");
997 	  WBell(p, visual_bell);
998 	  break;
999 	}
1000     }
1001   *bufp += *lenp;
1002   *lenp = 0;
1003   display = d;
1004 #ifdef COPY_PASTE
1005   if (pa && pa->pa_pastelen == 0)
1006     FreePaster(pa);
1007 #endif
1008 }
1009 
1010 int
FindCommnr(str)1011 FindCommnr(str)
1012 const char *str;
1013 {
1014   int x, m, l = 0, r = RC_LAST;
1015   while (l <= r)
1016     {
1017       m = (l + r) / 2;
1018       x = strcmp(str, comms[m].name);
1019       if (x > 0)
1020 	l = m + 1;
1021       else if (x < 0)
1022 	r = m - 1;
1023       else
1024 	return m;
1025     }
1026   return RC_ILLEGAL;
1027 }
1028 
1029 static int
CheckArgNum(nr,args)1030 CheckArgNum(nr, args)
1031 int nr;
1032 char **args;
1033 {
1034   int i, n;
1035   static char *argss[] = {"no", "one", "two", "three", "four", "OOPS"};
1036   static char *orformat[] =
1037     {
1038       "%s: %s: %s argument%s required",
1039       "%s: %s: %s or %s argument%s required",
1040       "%s: %s: %s, %s or %s argument%s required",
1041       "%s: %s: %s, %s, %s or %s argument%s required"
1042     };
1043 
1044   n = comms[nr].flags & ARGS_MASK;
1045   for (i = 0; args[i]; i++)
1046     ;
1047   if (comms[nr].flags & ARGS_ORMORE)
1048     {
1049       if (i < n)
1050 	{
1051 	  Msg(0, "%s: %s: at least %s argument%s required",
1052 	      rc_name, comms[nr].name, argss[n], n != 1 ? "s" : "");
1053 	  return -1;
1054 	}
1055     }
1056   else if ((comms[nr].flags & ARGS_PLUS1) &&
1057            (comms[nr].flags & ARGS_PLUS2) &&
1058 	   (comms[nr].flags & ARGS_PLUS3))
1059     {
1060       if (i != n && i != n + 1 && i != n + 2 && i != n + 3)
1061         {
1062 	  Msg(0, orformat[3], rc_name, comms[nr].name, argss[n],
1063 	      argss[n + 1], argss[n + 2], argss[n + 3], "");
1064 	  return -1;
1065 	}
1066     }
1067   else if ((comms[nr].flags & ARGS_PLUS1) &&
1068            (comms[nr].flags & ARGS_PLUS2))
1069     {
1070       if (i != n && i != n + 1 && i != n + 2)
1071 	{
1072 	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n],
1073 	      argss[n + 1], argss[n + 2], "");
1074           return -1;
1075 	}
1076     }
1077   else if ((comms[nr].flags & ARGS_PLUS1) &&
1078            (comms[nr].flags & ARGS_PLUS3))
1079     {
1080       if (i != n && i != n + 1 && i != n + 3)
1081         {
1082 	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n],
1083 	      argss[n + 1], argss[n + 3], "");
1084 	  return -1;
1085 	}
1086     }
1087   else if ((comms[nr].flags & ARGS_PLUS2) &&
1088            (comms[nr].flags & ARGS_PLUS3))
1089     {
1090       if (i != n && i != n + 2 && i != n + 3)
1091         {
1092 	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n],
1093 	      argss[n + 2], argss[n + 3], "");
1094 	  return -1;
1095 	}
1096     }
1097   else if (comms[nr].flags & ARGS_PLUS1)
1098     {
1099       if (i != n && i != n + 1)
1100         {
1101 	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n],
1102 	      argss[n + 1], n != 0 ? "s" : "");
1103 	  return -1;
1104 	}
1105     }
1106   else if (comms[nr].flags & ARGS_PLUS2)
1107     {
1108       if (i != n && i != n + 2)
1109         {
1110 	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n],
1111 	      argss[n + 2], "s");
1112 	  return -1;
1113 	}
1114     }
1115   else if (comms[nr].flags & ARGS_PLUS3)
1116     {
1117       if (i != n && i != n + 3)
1118         {
1119 	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n],
1120 	      argss[n + 3], "");
1121 	  return -1;
1122 	}
1123     }
1124   else if (i != n)
1125     {
1126       Msg(0, orformat[0], rc_name, comms[nr].name, argss[n], n != 1 ? "s" : "");
1127       return -1;
1128     }
1129   return i;
1130 }
1131 
1132 static void
StuffFin(buf,len,data)1133 StuffFin(buf, len, data)
1134 char *buf;
1135 int len;
1136 char *data;
1137 {
1138   if (!flayer)
1139     return;
1140   while(len)
1141     LayProcess(&buf, &len);
1142 }
1143 
1144 /* If the command is not 'quieted', then use Msg to output the message. If it's a remote
1145  * query, then Msg takes care of also outputting the message to the querying client.
1146  *
1147  * If we want the command to be quiet, and it's a remote query, then use QueryMsg so that
1148  * the response does go back to the querying client.
1149  *
1150  * If the command is quieted, and it's not a remote query, then just don't print the message.
1151  */
1152 #define OutputMsg	(!act->quiet ? Msg : queryflag >= 0 ? QueryMsg : Dummy)
1153 
1154 /*ARGSUSED*/
1155 void
DoAction(act,key)1156 DoAction(act, key)
1157 struct action *act;
1158 int key;
1159 {
1160   int nr = act->nr;
1161   char **args = act->args;
1162   int *argl = act->argl;
1163   struct win *p;
1164   int argc, i, n, msgok;
1165   char *s;
1166   char ch;
1167   struct display *odisplay = display;
1168   struct acluser *user;
1169 
1170   user = display ? D_user : users;
1171   if (nr == RC_ILLEGAL)
1172     {
1173       debug1("key '%c': No action\n", key);
1174       return;
1175     }
1176   n = comms[nr].flags;
1177   /* Commands will have a CAN_QUERY flag, depending on whether they have
1178    * something to return on a query. For example, 'windows' can return a result,
1179    * but 'other' cannot.
1180    * If some command causes an error, then it should reset queryflag to -1, so that
1181    * the process requesting the query can be notified that an error happened.
1182    */
1183   if (!(n & CAN_QUERY) && queryflag >= 0)
1184     {
1185       /* Query flag is set, but this command cannot be queried. */
1186       OutputMsg(0, "%s command cannot be queried.", comms[nr].name);
1187       queryflag = -1;
1188       return;
1189     }
1190   if ((n & NEED_DISPLAY) && display == 0)
1191     {
1192       OutputMsg(0, "%s: %s: display required", rc_name, comms[nr].name);
1193       queryflag = -1;
1194       return;
1195     }
1196   if ((n & NEED_FORE) && fore == 0)
1197     {
1198       OutputMsg(0, "%s: %s: window required", rc_name, comms[nr].name);
1199       queryflag = -1;
1200       return;
1201     }
1202   if ((n & NEED_LAYER) && flayer == 0)
1203     {
1204       OutputMsg(0, "%s: %s: display or window required", rc_name, comms[nr].name);
1205       queryflag = -1;
1206       return;
1207     }
1208   if ((argc = CheckArgNum(nr, args)) < 0)
1209     return;
1210 #ifdef MULTIUSER
1211   if (display)
1212     {
1213       if (AclCheckPermCmd(D_user, ACL_EXEC, &comms[nr]))
1214         {
1215 	  OutputMsg(0, "%s: %s: permission denied (user %s)",
1216 	      rc_name, comms[nr].name, (EffectiveAclUser ? EffectiveAclUser : D_user)->u_name);
1217 	  queryflag = -1;
1218 	  return;
1219 	}
1220     }
1221 #endif /* MULTIUSER */
1222 
1223   msgok = display && !*rc_name;
1224   switch(nr)
1225     {
1226     case RC_SELECT:
1227       if (!*args)
1228         InputSelect();
1229       else if (args[0][0] == '-' && !args[0][1])
1230 	{
1231 	  SetForeWindow((struct win *)0);
1232 	  Activate(0);
1233 	}
1234       else if (args[0][0] == '.' && !args[0][1])
1235 	{
1236 	  if (!fore)
1237 	    {
1238 	      OutputMsg(0, "select . needs a window");
1239 	      queryflag = -1;
1240 	    }
1241 	  else
1242 	    {
1243 	      SetForeWindow(fore);
1244 	      Activate(0);
1245 	    }
1246 	}
1247       else if (ParseWinNum(act, &n) == 0)
1248         SwitchWindow(n);
1249       else if (queryflag >= 0)
1250 	queryflag = -1;	/* ParseWinNum already prints out an appropriate error message. */
1251       break;
1252 #ifdef AUTO_NUKE
1253     case RC_DEFAUTONUKE:
1254       if (ParseOnOff(act, &defautonuke) == 0 && msgok)
1255 	OutputMsg(0, "Default autonuke turned %s", defautonuke ? "on" : "off");
1256       if (display && *rc_name)
1257 	D_auto_nuke = defautonuke;
1258       break;
1259     case RC_AUTONUKE:
1260       if (ParseOnOff(act, &D_auto_nuke) == 0 && msgok)
1261 	OutputMsg(0, "Autonuke turned %s", D_auto_nuke ? "on" : "off");
1262       break;
1263 #endif
1264     case RC_DEFOBUFLIMIT:
1265       if (ParseNum(act, &defobuflimit) == 0 && msgok)
1266 	OutputMsg(0, "Default limit set to %d", defobuflimit);
1267       if (display && *rc_name)
1268 	{
1269 	  D_obufmax = defobuflimit;
1270 	  D_obuflenmax = D_obuflen - D_obufmax;
1271 	}
1272       break;
1273     case RC_OBUFLIMIT:
1274       if (*args == 0)
1275 	OutputMsg(0, "Limit is %d, current buffer size is %d", D_obufmax, D_obuflen);
1276       else if (ParseNum(act, &D_obufmax) == 0 && msgok)
1277 	OutputMsg(0, "Limit set to %d", D_obufmax);
1278       D_obuflenmax = D_obuflen - D_obufmax;
1279       break;
1280     case RC_DUMPTERMCAP:
1281       WriteFile(user, (char *)0, DUMP_TERMCAP);
1282       break;
1283     case RC_HARDCOPY:
1284       {
1285 	int mode = DUMP_HARDCOPY;
1286 	char *file = NULL;
1287 
1288 	if (args[0])
1289 	  {
1290 	    if (!strcmp(*args, "-h"))
1291 	      {
1292 		mode = DUMP_SCROLLBACK;
1293 		file = args[1];
1294 	      }
1295 	    else if (!strcmp(*args, "--") && args[1])
1296 	      file = args[1];
1297 	    else
1298 	      file = args[0];
1299 	  }
1300 
1301 	if (args[0] && file == args[0] && args[1])
1302 	  {
1303 	    OutputMsg(0, "%s: hardcopy: too many arguments", rc_name);
1304 	    break;
1305 	  }
1306 	WriteFile(user, file, mode);
1307       }
1308       break;
1309     case RC_DEFLOG:
1310       (void)ParseOnOff(act, &nwin_default.Lflag);
1311       break;
1312     case RC_LOG:
1313       n = fore->w_log ? 1 : 0;
1314       ParseSwitch(act, &n);
1315       LogToggle(n);
1316       break;
1317 #ifdef BSDJOBS
1318     case RC_SUSPEND:
1319       Detach(D_STOP);
1320       break;
1321 #endif
1322     case RC_NEXT:
1323       if (MoreWindows())
1324 	SwitchWindow(NextWindow());
1325       break;
1326     case RC_PREV:
1327       if (MoreWindows())
1328 	SwitchWindow(PreviousWindow());
1329       break;
1330     case RC_KILL:
1331       {
1332 	char *name;
1333 
1334 	if (key >= 0)
1335 	  {
1336 #ifdef PSEUDOS
1337 	    Input(fore->w_pwin ? "Really kill this filter [y/n]" : "Really kill this window [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_KILL);
1338 #else
1339 	    Input("Really kill this window [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_KILL);
1340 #endif
1341 	    break;
1342 	  }
1343 	n = fore->w_number;
1344 #ifdef PSEUDOS
1345 	if (fore->w_pwin)
1346 	  {
1347 	    FreePseudowin(fore);
1348 	    OutputMsg(0, "Filter removed.");
1349 	    break;
1350 	  }
1351 #endif
1352 	name = SaveStr(fore->w_title);
1353 	KillWindow(fore);
1354 	OutputMsg(0, "Window %d (%s) killed.", n, name);
1355 	if (name)
1356 	  free(name);
1357 	break;
1358       }
1359     case RC_QUIT:
1360       if (key >= 0)
1361 	{
1362 	  Input("Really quit and kill all your windows [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_QUIT);
1363 	  break;
1364 	}
1365       Finit(0);
1366       /* NOTREACHED */
1367 #ifdef DETACH
1368     case RC_DETACH:
1369       if (*args && !strcmp(*args, "-h"))
1370         Hangup();
1371       else
1372         Detach(D_DETACH);
1373       break;
1374 # ifdef POW_DETACH
1375     case RC_POW_DETACH:
1376       if (key >= 0)
1377 	{
1378 	  static char buf[2];
1379 
1380 	  buf[0] = key;
1381 	  Input(buf, 1, INP_RAW, pow_detach_fn, NULL, 0);
1382 	}
1383       else
1384         Detach(D_POWER); /* detach and kill Attacher's parent */
1385       break;
1386 # endif
1387 #endif
1388     case RC_DEBUG:
1389 #ifdef DEBUG
1390       if (!*args)
1391         {
1392 	  if (dfp)
1393 	    OutputMsg(0, "debugging info is written to %s/", DEBUGDIR);
1394 	  else
1395 	    OutputMsg(0, "debugging is currently off. Use 'debug on' to enable.");
1396 	  break;
1397 	}
1398       if (dfp)
1399         {
1400 	  debug("debug: closing debug file.\n");
1401 	  fflush(dfp);
1402 	  fclose(dfp);
1403 	  dfp = NULL;
1404 	}
1405       if (strcmp("off", *args))
1406         opendebug(0, 1);
1407 # ifdef SIG_NODEBUG
1408       else if (display)
1409         kill(D_userpid, SIG_NODEBUG);	/* a one shot item, but hey... */
1410 # endif /* SIG_NODEBUG */
1411 #else
1412       if (*args == 0 || strcmp("off", *args))
1413         OutputMsg(0, "Sorry, screen was compiled without -DDEBUG option.");
1414 #endif
1415       break;
1416 #ifdef ZMODEM
1417     case RC_ZMODEM:
1418       if (*args && !strcmp(*args, "sendcmd"))
1419 	{
1420 	  if (args[1])
1421 	    {
1422 	      free(zmodem_sendcmd);
1423 	      zmodem_sendcmd = SaveStr(args[1]);
1424 	    }
1425 	  if (msgok)
1426 	    OutputMsg(0, "zmodem sendcmd: %s", zmodem_sendcmd);
1427 	  break;
1428 	}
1429       if (*args && !strcmp(*args, "recvcmd"))
1430 	{
1431 	  if (args[1])
1432 	    {
1433 	      free(zmodem_recvcmd);
1434 	      zmodem_recvcmd = SaveStr(args[1]);
1435 	    }
1436 	  if (msgok)
1437 	    OutputMsg(0, "zmodem recvcmd: %s", zmodem_recvcmd);
1438 	  break;
1439 	}
1440       if (*args)
1441 	{
1442 	  for (i = 0; i < 4; i++)
1443 	    if (!strcmp(zmodes[i], *args))
1444 	      break;
1445 	  if (i == 4 && !strcmp(*args, "on"))
1446 	    i = 1;
1447 	  if (i == 4)
1448 	    {
1449 	      OutputMsg(0, "usage: zmodem off|auto|catch|pass");
1450 	      break;
1451 	    }
1452 	  zmodem_mode = i;
1453 	}
1454       if (msgok)
1455 	OutputMsg(0, "zmodem mode is %s", zmodes[zmodem_mode]);
1456       break;
1457 #endif
1458     case RC_UNBINDALL:
1459       {
1460         register unsigned int i;
1461 
1462         for (i = 0; i < sizeof(ktab)/sizeof(*ktab); i++)
1463 	  ClearAction(&ktab[i]);
1464         OutputMsg(0, "Unbound all keys." );
1465         break;
1466       }
1467     case RC_ZOMBIE:
1468       {
1469         if (!(s = *args))
1470           {
1471             ZombieKey_destroy = 0;
1472             break;
1473           }
1474 	if (*argl == 0 || *argl > 2)
1475 	  {
1476 	    OutputMsg(0, "%s:zombie: one or two characters expected.", rc_name);
1477 	    break;
1478 	  }
1479 	if (args[1])
1480 	  {
1481 	    if (!strcmp(args[1], "onerror"))
1482 	      {
1483 		ZombieKey_onerror = 1;
1484 	      } else {
1485 		OutputMsg(0, "usage: zombie [keys [onerror]]");
1486 	    	break;
1487 	      }
1488 	  } else
1489 	    ZombieKey_onerror = 0;
1490         ZombieKey_destroy = args[0][0];
1491         ZombieKey_resurrect = *argl == 2 ? args[0][1] : 0;
1492       }
1493       break;
1494     case RC_WALL:
1495 #ifdef MULTIUSER
1496       s = D_user->u_name;
1497 #else
1498       s = D_usertty;
1499 #endif
1500         {
1501 	  struct display *olddisplay = display;
1502           display = 0;		/* no display will cause a broadcast */
1503           OutputMsg(0, "%s: %s", s, *args);
1504 	  display = olddisplay;
1505         }
1506       break;
1507     case RC_AT:
1508       /* where this AT command comes from: */
1509       if (!user)
1510 	break;
1511 #ifdef MULTIUSER
1512       s = SaveStr(user->u_name);
1513       /* DO NOT RETURN FROM HERE WITHOUT RESETTING THIS: */
1514       EffectiveAclUser = user;
1515 #else
1516       s = SaveStr(display ? D_usertty : user->u_name);
1517 #endif
1518       n = strlen(args[0]);
1519       if (n) n--;
1520       /*
1521        * the windows/displays loops are quite dangerous here, take extra
1522        * care not to trigger landmines. Things may appear/disappear while
1523        * we are walking along.
1524        */
1525       switch (args[0][n])
1526         {
1527 	case '*':		/* user */
1528 	  {
1529 	    struct display *nd;
1530 	    struct acluser *u;
1531 
1532 	    if (!n)
1533 	      u = user;
1534 	    else
1535 	      {
1536 		for (u = users; u; u = u->u_next)
1537 		  {
1538 		    debug3("strncmp('%s', '%s', %d)\n", *args, u->u_name, n);
1539 		    if (!strncmp(*args, u->u_name, n))
1540 		      break;
1541 		  }
1542 		if (!u)
1543 		  {
1544 		    args[0][n] = '\0';
1545 		    OutputMsg(0, "Did not find any user matching '%s'", args[0]);
1546 		    break;
1547 		  }
1548 	      }
1549 	    debug1("at all displays of user %s\n", u->u_name);
1550 	    for (display = displays; display; display = nd)
1551 	      {
1552 		nd = display->d_next;
1553 		if (D_forecv == 0)
1554 		  continue;
1555 		flayer = D_forecv->c_layer;
1556 		fore = D_fore;
1557 	        if (D_user != u)
1558 		  continue;
1559 		debug1("AT display %s\n", D_usertty);
1560 		DoCommand(args + 1, argl + 1);
1561 		if (display)
1562 		  OutputMsg(0, "command from %s: %s %s",
1563 		      s, args[1], args[2] ? args[2] : "");
1564 		display = NULL;
1565 		flayer = 0;
1566 		fore = NULL;
1567 	      }
1568 	    break;
1569 	  }
1570 	case '%':		/* display */
1571 	  {
1572 	    struct display *nd;
1573 
1574 	    debug1("at display matching '%s'\n", args[0]);
1575 	    for (display = displays; display; display = nd)
1576 	      {
1577 	        nd = display->d_next;
1578 		if (D_forecv == 0)
1579 		  continue;
1580 		fore = D_fore;
1581 		flayer = D_forecv->c_layer;
1582 	        if (strncmp(args[0], D_usertty, n) &&
1583 		    (strncmp("/dev/", D_usertty, 5) ||
1584 		     strncmp(args[0], D_usertty + 5, n)) &&
1585 		    (strncmp("/dev/tty", D_usertty, 8) ||
1586 		     strncmp(args[0], D_usertty + 8, n)))
1587 		  continue;
1588 		debug1("AT display %s\n", D_usertty);
1589 		DoCommand(args + 1, argl + 1);
1590 		if (display)
1591 		  OutputMsg(0, "command from %s: %s %s",
1592 		      s, args[1], args[2] ? args[2] : "");
1593 		display = NULL;
1594 		fore = NULL;
1595 		flayer = 0;
1596 	      }
1597 	    break;
1598 	  }
1599 	case '#':		/* window */
1600 	  n--;
1601 	  /* FALLTHROUGH */
1602 	default:
1603 	  {
1604 	    struct win *nw;
1605 	    int ch;
1606 
1607 	    n++;
1608 	    ch = args[0][n];
1609 	    args[0][n] = '\0';
1610 	    if (!*args[0] || (i = WindowByNumber(args[0])) < 0)
1611 	      {
1612 	        args[0][n] = ch;      /* must restore string in case of bind */
1613 	        /* try looping over titles */
1614 		for (fore = windows; fore; fore = nw)
1615 		  {
1616 		    nw = fore->w_next;
1617 		    if (strncmp(args[0], fore->w_title, n))
1618 		      continue;
1619 		    debug2("AT window %d(%s)\n", fore->w_number, fore->w_title);
1620 		    /*
1621 		     * consider this a bug or a feature:
1622 		     * while looping through windows, we have fore AND
1623 		     * display context. This will confuse users who try to
1624 		     * set up loops inside of loops, but often allows to do
1625 		     * what you mean, even when you adress your context wrong.
1626 		     */
1627 		    i = 0;
1628 		    /* XXX: other displays? */
1629 		    if (fore->w_layer.l_cvlist)
1630 		      display = fore->w_layer.l_cvlist->c_display;
1631 		    flayer = fore->w_savelayer ? fore->w_savelayer : &fore->w_layer;
1632 		    DoCommand(args + 1, argl + 1);	/* may destroy our display */
1633 		    if (fore && fore->w_layer.l_cvlist)
1634 		      {
1635 		        display = fore->w_layer.l_cvlist->c_display;
1636 		        OutputMsg(0, "command from %s: %s %s",
1637 			    s, args[1], args[2] ? args[2] : "");
1638 		      }
1639 		  }
1640 		display = NULL;
1641 		fore = NULL;
1642 		if (i < 0)
1643 		  OutputMsg(0, "%s: at '%s': no such window.\n", rc_name, args[0]);
1644 		break;
1645 	      }
1646 	    else if (i < maxwin && (fore = wtab[i]))
1647 	      {
1648 	        args[0][n] = ch;      /* must restore string in case of bind */
1649 	        debug2("AT window %d (%s)\n", fore->w_number, fore->w_title);
1650 		if (fore->w_layer.l_cvlist)
1651 		  display = fore->w_layer.l_cvlist->c_display;
1652 		flayer = fore->w_savelayer ? fore->w_savelayer : &fore->w_layer;
1653 		DoCommand(args + 1, argl + 1);
1654 		if (fore && fore->w_layer.l_cvlist)
1655 		  {
1656 		    display = fore->w_layer.l_cvlist->c_display;
1657 		    OutputMsg(0, "command from %s: %s %s",
1658 		        s, args[1], args[2] ? args[2] : "");
1659 		  }
1660 		display = NULL;
1661 		fore = NULL;
1662 	      }
1663 	    else
1664 	      OutputMsg(0, "%s: at [identifier][%%|*|#] command [args]", rc_name);
1665 	    break;
1666 	  }
1667 	}
1668       free(s);
1669 #ifdef MULTIUSER
1670       EffectiveAclUser = NULL;
1671 #endif
1672       break;
1673 
1674 #ifdef COPY_PASTE
1675     case RC_READREG:
1676 #ifdef ENCODINGS
1677       i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
1678       if (args[0] && args[1] && !strcmp(args[0], "-e"))
1679 	{
1680 	  i = FindEncoding(args[1]);
1681 	  if (i == -1)
1682 	    {
1683 	      OutputMsg(0, "%s: readreg: unknown encoding", rc_name);
1684 	      break;
1685 	    }
1686 	  args += 2;
1687 	}
1688 #endif
1689       /*
1690        * Without arguments we prompt for a destination register.
1691        * It will receive the copybuffer contents.
1692        * This is not done by RC_PASTE, as we prompt for source
1693        * (not dest) there.
1694        */
1695       if ((s = *args) == NULL)
1696 	{
1697 	  Input("Copy to register:", 1, INP_RAW, copy_reg_fn, NULL, 0);
1698 	  break;
1699 	}
1700       if (*argl != 1)
1701 	{
1702 	  OutputMsg(0, "%s: copyreg: character, ^x, or (octal) \\032 expected.", rc_name);
1703 	  break;
1704 	}
1705       ch = args[0][0];
1706       /*
1707        * With two arguments we *really* read register contents from file
1708        */
1709       if (args[1])
1710         {
1711 	  if (args[2])
1712 	    {
1713 	      OutputMsg(0, "%s: readreg: too many arguments", rc_name);
1714 	      break;
1715 	    }
1716 	  if ((s = ReadFile(args[1], &n)))
1717 	    {
1718 	      struct plop *pp = plop_tab + (int)(unsigned char)ch;
1719 
1720 	      if (pp->buf)
1721 		free(pp->buf);
1722 	      pp->buf = s;
1723 	      pp->len = n;
1724 #ifdef ENCODINGS
1725 	      pp->enc = i;
1726 #endif
1727 	    }
1728 	}
1729       else
1730         /*
1731 	 * with one argument we copy the copybuffer into a specified register
1732 	 * This could be done with RC_PASTE too, but is here to be consistent
1733 	 * with the zero argument call.
1734 	 */
1735         copy_reg_fn(&ch, 0, NULL);
1736       break;
1737 #endif
1738     case RC_REGISTER:
1739 #ifdef ENCODINGS
1740       i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
1741       if (args[0] && args[1] && !strcmp(args[0], "-e"))
1742 	{
1743 	  i = FindEncoding(args[1]);
1744 	  if (i == -1)
1745 	    {
1746 	      OutputMsg(0, "%s: register: unknown encoding", rc_name);
1747 	      break;
1748 	    }
1749 	  args += 2;
1750 	  argc -= 2;
1751 	}
1752 #endif
1753       if (argc != 2)
1754 	{
1755 	  OutputMsg(0, "%s: register: illegal number of arguments.", rc_name);
1756 	  break;
1757 	}
1758       if (*argl != 1)
1759 	{
1760 	  OutputMsg(0, "%s: register: character, ^x, or (octal) \\032 expected.", rc_name);
1761 	  break;
1762 	}
1763       ch = args[0][0];
1764 #ifdef COPY_PASTE
1765       if (ch == '.')
1766 	{
1767 	  if (user->u_plop.buf != NULL)
1768 	    UserFreeCopyBuffer(user);
1769 	  if (args[1] && args[1][0])
1770 	    {
1771 	      user->u_plop.buf = SaveStrn(args[1], argl[1]);
1772 	      user->u_plop.len = argl[1];
1773 #ifdef ENCODINGS
1774 	      user->u_plop.enc = i;
1775 #endif
1776 	    }
1777 	}
1778       else
1779 #endif
1780 	{
1781 	  struct plop *plp = plop_tab + (int)(unsigned char)ch;
1782 
1783 	  if (plp->buf)
1784 	    free(plp->buf);
1785 	  plp->buf = SaveStrn(args[1], argl[1]);
1786 	  plp->len = argl[1];
1787 #ifdef ENCODINGS
1788 	  plp->enc = i;
1789 #endif
1790 	}
1791       break;
1792     case RC_PROCESS:
1793       if ((s = *args) == NULL)
1794 	{
1795 	  Input("Process register:", 1, INP_RAW, process_fn, NULL, 0);
1796 	  break;
1797 	}
1798       if (*argl != 1)
1799 	{
1800 	  OutputMsg(0, "%s: process: character, ^x, or (octal) \\032 expected.", rc_name);
1801 	  break;
1802 	}
1803       ch = args[0][0];
1804       process_fn(&ch, 0, NULL);
1805       break;
1806     case RC_STUFF:
1807       s = *args;
1808       if (!args[0])
1809 	{
1810 	  Input("Stuff:", 100, INP_COOKED, StuffFin, NULL, 0);
1811 	  break;
1812 	}
1813       n = *argl;
1814       if (args[1])
1815 	{
1816 	  if (strcmp(s, "-k"))
1817 	    {
1818 	      OutputMsg(0, "%s: stuff: invalid option %s", rc_name, s);
1819 	      break;
1820 	    }
1821 	  s = args[1];
1822 	  for (i = T_CAPS; i < T_OCAPS; i++)
1823 	    if (strcmp(term[i].tcname, s) == 0)
1824 	      break;
1825 	  if (i == T_OCAPS)
1826 	    {
1827 	      OutputMsg(0, "%s: stuff: unknown key '%s'", rc_name, s);
1828 	      break;
1829 	    }
1830 #ifdef MAPKEYS
1831 	  if (StuffKey(i - T_CAPS) == 0)
1832 	    break;
1833 #endif
1834 	  s = display ? D_tcs[i].str : 0;
1835 	  if (s == 0)
1836 	    break;
1837 	  n = strlen(s);
1838 	}
1839       while(n)
1840         LayProcess(&s, &n);
1841       break;
1842     case RC_REDISPLAY:
1843       Activate(-1);
1844       break;
1845     case RC_WINDOWS:
1846 			if (args[0]) {
1847 				ShowWindowsX(args[0]);
1848 				break;
1849 			}
1850       ShowWindows(-1);
1851       break;
1852     case RC_VERSION:
1853       OutputMsg(0, "screen %s", version);
1854       break;
1855     case RC_TIME:
1856       if (*args)
1857 	{
1858 	  timestring = SaveStr(*args);
1859 	  break;
1860 	}
1861       OutputMsg(0, "%s", MakeWinMsg(timestring, fore, '%'));
1862       break;
1863     case RC_INFO:
1864       ShowInfo();
1865       break;
1866     case RC_DINFO:
1867       ShowDInfo();
1868       break;
1869     case RC_COMMAND:
1870 	{
1871 	  struct action *ktabp = ktab;
1872 	  if (argc == 2 && !strcmp(*args, "-c"))
1873 	    {
1874 	      if ((ktabp = FindKtab(args[1], 0)) == 0)
1875 		{
1876 		  OutputMsg(0, "Unknown command class '%s'", args[1]);
1877 		  break;
1878 		}
1879 	    }
1880 	  if (D_ESCseen != ktab || ktabp != ktab)
1881 	    {
1882 	      if (D_ESCseen != ktabp)
1883 	        {
1884 	          D_ESCseen = ktabp;
1885 	          WindowChanged(fore, 'E');
1886 	        }
1887 	      break;
1888 	    }
1889 	  if (D_ESCseen)
1890 	    {
1891 	      D_ESCseen = 0;
1892 	      WindowChanged(fore, 'E');
1893 	    }
1894 	}
1895       /* FALLTHROUGH */
1896     case RC_OTHER:
1897       if (MoreWindows())
1898 	SwitchWindow(display && D_other ? D_other->w_number : NextWindow());
1899       break;
1900     case RC_META:
1901       if (user->u_Esc == -1)
1902         break;
1903       ch = user->u_Esc;
1904       s = &ch;
1905       n = 1;
1906       LayProcess(&s, &n);
1907       break;
1908     case RC_XON:
1909       ch = Ctrl('q');
1910       s = &ch;
1911       n = 1;
1912       LayProcess(&s, &n);
1913       break;
1914     case RC_XOFF:
1915       ch = Ctrl('s');
1916       s = &ch;
1917       n = 1;
1918       LayProcess(&s, &n);
1919       break;
1920     case RC_DEFBREAKTYPE:
1921     case RC_BREAKTYPE:
1922 	{
1923 	  static char *types[] = { "TIOCSBRK", "TCSBRK", "tcsendbreak", NULL };
1924 	  extern int breaktype;
1925 
1926 	  if (*args)
1927 	    {
1928 	      if (ParseNum(act, &n))
1929 		for (n = 0; n < (int)(sizeof(types)/sizeof(*types)); n++)
1930 		  {
1931 		    for (i = 0; i < 4; i++)
1932 		      {
1933 			ch = args[0][i];
1934 			if (ch >= 'a' && ch <= 'z')
1935 			  ch -= 'a' - 'A';
1936 			if (ch != types[n][i] && (ch + ('a' - 'A')) != types[n][i])
1937 			  break;
1938 		      }
1939 		    if (i == 4)
1940 		      break;
1941 		  }
1942 	      if (n < 0 || n >= (int)(sizeof(types)/sizeof(*types)))
1943 	        OutputMsg(0, "%s invalid, chose one of %s, %s or %s", *args, types[0], types[1], types[2]);
1944 	      else
1945 	        {
1946 		  breaktype = n;
1947 	          OutputMsg(0, "breaktype set to (%d) %s", n, types[n]);
1948 		}
1949 	    }
1950 	  else
1951 	    OutputMsg(0, "breaktype is (%d) %s", breaktype, types[breaktype]);
1952 	}
1953       break;
1954     case RC_POW_BREAK:
1955     case RC_BREAK:
1956       n = 0;
1957       if (*args && ParseNum(act, &n))
1958 	break;
1959       SendBreak(fore, n, nr == RC_POW_BREAK);
1960       break;
1961 #ifdef LOCK
1962     case RC_LOCKSCREEN:
1963       Detach(D_LOCK);
1964       break;
1965 #endif
1966     case RC_WIDTH:
1967     case RC_HEIGHT:
1968       {
1969 	int w, h;
1970 	int what = 0;
1971 
1972         i = 1;
1973 	if (*args && !strcmp(*args, "-w"))
1974 	  what = 1;
1975 	else if (*args && !strcmp(*args, "-d"))
1976 	  what = 2;
1977 	if (what)
1978 	  args++;
1979 	if (what == 0 && flayer && !display)
1980 	  what = 1;
1981 	if (what == 1)
1982 	  {
1983 	    if (!flayer)
1984 	      {
1985 		OutputMsg(0, "%s: %s: window required", rc_name, comms[nr].name);
1986 		break;
1987 	      }
1988 	    w = flayer->l_width;
1989 	    h = flayer->l_height;
1990 	  }
1991 	else
1992 	  {
1993 	    if (!display)
1994 	      {
1995 		OutputMsg(0, "%s: %s: display required", rc_name, comms[nr].name);
1996 		break;
1997 	      }
1998 	    w = D_width;
1999 	    h = D_height;
2000 	  }
2001         if (*args && args[0][0] == '-')
2002 	  {
2003 	    OutputMsg(0, "%s: %s: unknown option %s", rc_name, comms[nr].name, *args);
2004 	    break;
2005 	  }
2006 	if (nr == RC_HEIGHT)
2007 	  {
2008 	    if (!*args)
2009 	      {
2010 #define H0height 42
2011 #define H1height 24
2012 		if (h == H0height)
2013 		  h = H1height;
2014 		else if (h == H1height)
2015 		  h = H0height;
2016 		else if (h > (H0height + H1height) / 2)
2017 		  h = H0height;
2018 		else
2019 		  h = H1height;
2020 	      }
2021 	    else
2022 	      {
2023 		h = atoi(*args);
2024 		if (args[1])
2025 		  w = atoi(args[1]);
2026 	      }
2027 	  }
2028 	else
2029 	  {
2030 	    if (!*args)
2031 	      {
2032 		if (w == Z0width)
2033 		  w = Z1width;
2034 		else if (w == Z1width)
2035 		  w = Z0width;
2036 		else if (w > (Z0width + Z1width) / 2)
2037 		  w = Z0width;
2038 		else
2039 		  w = Z1width;
2040 	      }
2041 	    else
2042 	      {
2043 		w = atoi(*args);
2044 		if (args[1])
2045 		  h = atoi(args[1]);
2046 	      }
2047 	  }
2048         if (*args && args[1] && args[2])
2049 	  {
2050 	    OutputMsg(0, "%s: %s: too many arguments", rc_name, comms[nr].name);
2051 	    break;
2052 	  }
2053 	if (w <= 0)
2054 	  {
2055 	    OutputMsg(0, "Illegal width");
2056 	    break;
2057 	  }
2058 	if (h <= 0)
2059 	  {
2060 	    OutputMsg(0, "Illegal height");
2061 	    break;
2062 	  }
2063 	if (what == 1)
2064 	  {
2065 	    if (flayer->l_width == w && flayer->l_height == h)
2066 	      break;
2067 	    ResizeLayer(flayer, w, h, (struct display *)0);
2068 	    break;
2069 	  }
2070 	if (D_width == w && D_height == h)
2071 	  break;
2072 	if (what == 2)
2073 	  {
2074 	    ChangeScreenSize(w, h, 1);
2075 	  }
2076 	else
2077 	  {
2078 	    if (ResizeDisplay(w, h) == 0)
2079 	      {
2080 		Activate(D_fore ? D_fore->w_norefresh : 0);
2081 		/* autofit */
2082 		ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, 0);
2083 		break;
2084 	      }
2085 	    if (h == D_height)
2086 	      OutputMsg(0, "Your termcap does not specify how to change the terminal's width to %d.", w);
2087 	    else if (w == D_width)
2088 	      OutputMsg(0, "Your termcap does not specify how to change the terminal's height to %d.", h);
2089 	    else
2090 	      OutputMsg(0, "Your termcap does not specify how to change the terminal's resolution to %dx%d.", w, h);
2091 	  }
2092       }
2093       break;
2094     case RC_DEFDYNAMICTITLE:
2095       (void)ParseOnOff(act, &nwin_default.dynamicaka);
2096       break;
2097     case RC_DYNAMICTITLE:
2098       (void)ParseOnOff(act, &fore->w_dynamicaka);
2099       break;
2100     case RC_TITLE:
2101       if (queryflag >= 0)
2102 	{
2103 	  if (fore)
2104 	    OutputMsg(0, "%s", fore->w_title);
2105 	  else
2106 	    queryflag = -1;
2107 	  break;
2108 	}
2109       if (*args == 0)
2110 	InputAKA();
2111       else
2112 	ChangeAKA(fore, *args, strlen(*args));
2113       break;
2114     case RC_COLON:
2115       Input(":", MAXSTR, INP_EVERY, Colonfin, NULL, 0);
2116       if (*args && **args)
2117 	{
2118 	  s = *args;
2119 	  n = strlen(s);
2120 	  LayProcess(&s, &n);
2121 	}
2122       break;
2123     case RC_LASTMSG:
2124       if (D_status_lastmsg)
2125 	OutputMsg(0, "%s", D_status_lastmsg);
2126       break;
2127     case RC_SCREEN:
2128       DoScreen("key", args);
2129       break;
2130     case RC_WRAP:
2131       if (ParseSwitch(act, &fore->w_wrap) == 0 && msgok)
2132         OutputMsg(0, "%cwrap", fore->w_wrap ? '+' : '-');
2133       break;
2134     case RC_FLOW:
2135       if (*args)
2136 	{
2137 	  if (args[0][0] == 'a')
2138 	    {
2139 	      fore->w_flow = (fore->w_flow & FLOW_AUTO) ? FLOW_AUTOFLAG |FLOW_AUTO|FLOW_NOW : FLOW_AUTOFLAG;
2140 	    }
2141 	  else
2142 	    {
2143 	      if (ParseOnOff(act, &n))
2144 		break;
2145 	      fore->w_flow = (fore->w_flow & FLOW_AUTO) | n;
2146 	    }
2147 	}
2148       else
2149 	{
2150 	  if (fore->w_flow & FLOW_AUTOFLAG)
2151 	    fore->w_flow = (fore->w_flow & FLOW_AUTO) | FLOW_NOW;
2152 	  else if (fore->w_flow & FLOW_NOW)
2153 	    fore->w_flow &= ~FLOW_NOW;
2154 	  else
2155 	    fore->w_flow = fore->w_flow ? FLOW_AUTOFLAG|FLOW_AUTO|FLOW_NOW : FLOW_AUTOFLAG;
2156 	}
2157       SetFlow(fore->w_flow & FLOW_NOW);
2158       if (msgok)
2159 	OutputMsg(0, "%cflow%s", (fore->w_flow & FLOW_NOW) ? '+' : '-',
2160 	    (fore->w_flow & FLOW_AUTOFLAG) ? "(auto)" : "");
2161       break;
2162 #ifdef MULTIUSER
2163     case RC_DEFWRITELOCK:
2164       if (args[0][0] == 'a')
2165 	nwin_default.wlock = WLOCK_AUTO;
2166       else
2167 	{
2168 	  if (ParseOnOff(act, &n))
2169 	    break;
2170 	  nwin_default.wlock = n ? WLOCK_ON : WLOCK_OFF;
2171 	}
2172       break;
2173     case RC_WRITELOCK:
2174       if (*args)
2175 	{
2176 	  if (args[0][0] == 'a')
2177 	    {
2178 	      fore->w_wlock = WLOCK_AUTO;
2179 	    }
2180 	  else
2181 	    {
2182 	      if (ParseOnOff(act, &n))
2183 		break;
2184 	      fore->w_wlock = n ? WLOCK_ON : WLOCK_OFF;
2185 	    }
2186 	  /*
2187 	   * user may have permission to change the writelock setting,
2188 	   * but he may never aquire the lock himself without write permission
2189 	   */
2190 	  if (!AclCheckPermWin(D_user, ACL_WRITE, fore))
2191 	    fore->w_wlockuser = D_user;
2192 	}
2193       OutputMsg(0, "writelock %s", (fore->w_wlock == WLOCK_AUTO) ? "auto" :
2194 	  ((fore->w_wlock == WLOCK_OFF) ? "off" : "on"));
2195       break;
2196 #endif
2197     case RC_CLEAR:
2198       ResetAnsiState(fore);
2199       WriteString(fore, "\033[H\033[J", 6);
2200       break;
2201     case RC_RESET:
2202       ResetAnsiState(fore);
2203 #ifdef ZMODEM
2204       if (fore->w_zdisplay)
2205         zmodem_abort(fore, fore->w_zdisplay);
2206 #endif
2207       WriteString(fore, "\033c", 2);
2208       break;
2209     case RC_MONITOR:
2210       n = fore->w_monitor != MON_OFF;
2211 #ifdef MULTIUSER
2212       if (display)
2213 	n = n && (ACLBYTE(fore->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id));
2214 #endif
2215       if (ParseSwitch(act, &n))
2216 	break;
2217       if (n)
2218 	{
2219 #ifdef MULTIUSER
2220 	  if (display)	/* we tell only this user */
2221 	    ACLBYTE(fore->w_mon_notify, D_user->u_id) |= ACLBIT(D_user->u_id);
2222 	  else
2223 	    for (i = 0; i < maxusercount; i++)
2224 	      ACLBYTE(fore->w_mon_notify, i) |= ACLBIT(i);
2225 #endif
2226 	  if (fore->w_monitor == MON_OFF)
2227 	    fore->w_monitor = MON_ON;
2228 	  OutputMsg(0, "Window %d (%s) is now being monitored for all activity.", fore->w_number, fore->w_title);
2229 	}
2230       else
2231 	{
2232 #ifdef MULTIUSER
2233 	  if (display) /* we remove only this user */
2234 	    ACLBYTE(fore->w_mon_notify, D_user->u_id)
2235 	      &= ~ACLBIT(D_user->u_id);
2236 	  else
2237 	    for (i = 0; i < maxusercount; i++)
2238 	      ACLBYTE(fore->w_mon_notify, i) &= ~ACLBIT(i);
2239 	  for (i = maxusercount - 1; i >= 0; i--)
2240 	    if (ACLBYTE(fore->w_mon_notify, i))
2241 	      break;
2242 	  if (i < 0)
2243 #endif
2244 	    fore->w_monitor = MON_OFF;
2245 	  OutputMsg(0, "Window %d (%s) is no longer being monitored for activity.", fore->w_number, fore->w_title);
2246 	}
2247       break;
2248 #ifdef MULTI
2249     case RC_DISPLAYS:
2250       display_displays();
2251       break;
2252 #endif
2253     case RC_WINDOWLIST:
2254       if (!*args)
2255         display_windows(0, WLIST_NUM, (struct win *)0);
2256       else if (!strcmp(*args, "string"))
2257 	{
2258 	  if (args[1])
2259 	    {
2260 	      if (wliststr)
2261 		free(wliststr);
2262 	      wliststr = SaveStr(args[1]);
2263 	    }
2264 	  if (msgok)
2265 	    OutputMsg(0, "windowlist string is '%s'", wliststr);
2266 	}
2267       else if (!strcmp(*args, "title"))
2268 	{
2269 	  if (args[1])
2270 	    {
2271 	      if (wlisttit)
2272 		free(wlisttit);
2273 	      wlisttit = SaveStr(args[1]);
2274 	    }
2275 	  if (msgok)
2276 	    OutputMsg(0, "windowlist title is '%s'", wlisttit);
2277 	}
2278       else
2279 	{
2280 	  int flag = 0;
2281 	  int blank = 0;
2282 	  for (i = 0; i < argc; i++)
2283 	    if (!args[i])
2284 	      continue;
2285 	    else if (!strcmp(args[i], "-m"))
2286 	      flag |= WLIST_MRU;
2287 	    else if (!strcmp(args[i], "-b"))
2288 	      blank = 1;
2289 	    else if (!strcmp(args[i], "-g"))
2290 	      flag |= WLIST_NESTED;
2291 	    else
2292 	      {
2293 		OutputMsg(0, "usage: windowlist [-b] [-g] [-m] [string [string] | title [title]]");
2294 		break;
2295 	      }
2296 	  if (i == argc)
2297 	    display_windows(blank, flag, (struct win *)0);
2298 	}
2299       break;
2300     case RC_HELP:
2301       if (argc == 2 && !strcmp(*args, "-c"))
2302 	{
2303 	  struct action *ktabp;
2304 	  if ((ktabp = FindKtab(args[1], 0)) == 0)
2305 	    {
2306 	      OutputMsg(0, "Unknown command class '%s'", args[1]);
2307 	      break;
2308 	    }
2309           display_help(args[1], ktabp);
2310 	}
2311       else
2312         display_help((char *)0, ktab);
2313       break;
2314     case RC_LICENSE:
2315       display_copyright();
2316       break;
2317 #ifdef COPY_PASTE
2318     case RC_COPY:
2319       if (flayer->l_layfn != &WinLf)
2320 	{
2321 	  OutputMsg(0, "Must be on a window layer");
2322 	  break;
2323 	}
2324       MarkRoutine();
2325       WindowChanged(fore, 'P');
2326       break;
2327     case RC_HISTORY:
2328       {
2329         static char *pasteargs[] = {".", 0};
2330 	static int pasteargl[] = {1};
2331 
2332 	if (flayer->l_layfn != &WinLf)
2333 	  {
2334 	    OutputMsg(0, "Must be on a window layer");
2335 	    break;
2336 	  }
2337 	if (GetHistory() == 0)
2338 	  break;
2339 	if (user->u_plop.buf == NULL)
2340 	  break;
2341 	args = pasteargs;
2342 	argl = pasteargl;
2343       }
2344       /*FALLTHROUGH*/
2345     case RC_PASTE:
2346       {
2347         char *ss, *dbuf, dch;
2348         int l = 0;
2349 # ifdef ENCODINGS
2350 	int enc = -1;
2351 # endif
2352 
2353 	/*
2354 	 * without args we prompt for one(!) register to be pasted in the window
2355 	 */
2356 	if ((s = *args) == NULL)
2357 	  {
2358 	    Input("Paste from register:", 1, INP_RAW, ins_reg_fn, NULL, 0);
2359 	    break;
2360 	  }
2361 	if (args[1] == 0 && !fore)	/* no window? */
2362 	  break;
2363 	/*
2364 	 * with two arguments we paste into a destination register
2365 	 * (no window needed here).
2366 	 */
2367 	if (args[1] && argl[1] != 1)
2368 	  {
2369 	    OutputMsg(0, "%s: paste destination: character, ^x, or (octal) \\032 expected.",
2370 		rc_name);
2371 	    break;
2372 	  }
2373 # ifdef ENCODINGS
2374         else if (fore)
2375 	  enc = fore->w_encoding;
2376 # endif
2377 
2378 	/*
2379 	 * measure length of needed buffer
2380 	 */
2381         for (ss = s = *args; (ch = *ss); ss++)
2382           {
2383 	    if (ch == '.')
2384 	      {
2385 # ifdef ENCODINGS
2386 		if (enc == -1)
2387 		  enc = user->u_plop.enc;
2388 		if (enc != user->u_plop.enc)
2389 		  l += RecodeBuf((unsigned char *)user->u_plop.buf, user->u_plop.len, user->u_plop.enc, enc, (unsigned char *)0);
2390 		else
2391 # endif
2392 		  l += user->u_plop.len;
2393 	      }
2394 	    else
2395 	      {
2396 # ifdef ENCODINGS
2397 		if (enc == -1)
2398 		  enc = plop_tab[(int)(unsigned char)ch].enc;
2399 		if (enc != plop_tab[(int)(unsigned char)ch].enc)
2400 		  l += RecodeBuf((unsigned char *)plop_tab[(int)(unsigned char)ch].buf, plop_tab[(int)(unsigned char)ch].len, plop_tab[(int)(unsigned char)ch].enc, enc, (unsigned char *)0);
2401 		else
2402 # endif
2403                   l += plop_tab[(int)(unsigned char)ch].len;
2404 	      }
2405           }
2406         if (l == 0)
2407 	  {
2408 	    OutputMsg(0, "empty buffer");
2409 	    break;
2410 	  }
2411 	/*
2412 	 * shortcut:
2413 	 * if there is only one source and the destination is a window, then
2414 	 * pass a pointer rather than duplicating the buffer.
2415 	 */
2416         if (s[1] == 0 && args[1] == 0)
2417 # ifdef ENCODINGS
2418 	  if (enc == (*s == '.' ? user->u_plop.enc : plop_tab[(int)(unsigned char)*s].enc))
2419 # endif
2420             {
2421 	      MakePaster(&fore->w_paster, *s == '.' ? user->u_plop.buf : plop_tab[(int)(unsigned char)*s].buf, l, 0);
2422 	      break;
2423             }
2424 	/*
2425 	 * if no shortcut, we construct a buffer
2426 	 */
2427         if ((dbuf = (char *)malloc(l)) == 0)
2428           {
2429 	    OutputMsg(0, "%s", strnomem);
2430 	    break;
2431           }
2432         l = 0;
2433 	/*
2434 	 * concatenate all sources into our own buffer, copy buffer is
2435 	 * special and is skipped if no display exists.
2436 	 */
2437         for (ss = s; (ch = *ss); ss++)
2438           {
2439 	    struct plop *pp = (ch == '.' ? &user->u_plop : &plop_tab[(int)(unsigned char)ch]);
2440 #ifdef ENCODINGS
2441 	    if (pp->enc != enc)
2442 	      {
2443 		l += RecodeBuf((unsigned char *)pp->buf, pp->len, pp->enc, enc, (unsigned char *)dbuf + l);
2444 		continue;
2445 	      }
2446 #endif
2447 	    bcopy(pp->buf, dbuf + l, pp->len);
2448 	    l += pp->len;
2449           }
2450 	/*
2451 	 * when called with one argument we paste our buffer into the window
2452 	 */
2453 	if (args[1] == 0)
2454 	  {
2455 	    MakePaster(&fore->w_paster, dbuf, l, 1);
2456 	  }
2457 	else
2458 	  {
2459 	    /*
2460 	     * we have two arguments, the second is already in dch.
2461 	     * use this as destination rather than the window.
2462 	     */
2463 	    dch = args[1][0];
2464 	    if (dch == '.')
2465 	      {
2466 	        if (user->u_plop.buf != NULL)
2467 	          UserFreeCopyBuffer(user);
2468 		user->u_plop.buf = dbuf;
2469 		user->u_plop.len = l;
2470 #ifdef ENCODINGS
2471 		user->u_plop.enc = enc;
2472 #endif
2473 	      }
2474 	    else
2475 	      {
2476 		struct plop *pp = plop_tab + (int)(unsigned char)dch;
2477 		if (pp->buf)
2478 		  free(pp->buf);
2479 		pp->buf = dbuf;
2480 		pp->len = l;
2481 #ifdef ENCODINGS
2482 		pp->enc = enc;
2483 #endif
2484 	      }
2485 	  }
2486         break;
2487       }
2488     case RC_WRITEBUF:
2489       if (!user->u_plop.buf)
2490 	{
2491 	  OutputMsg(0, "empty buffer");
2492 	  break;
2493 	}
2494 #ifdef ENCODINGS
2495 	{
2496 	  struct plop oldplop;
2497 
2498 	  oldplop = user->u_plop;
2499 	  if (args[0] && args[1] && !strcmp(args[0], "-e"))
2500 	    {
2501 	      int enc, l;
2502 	      char *newbuf;
2503 
2504 	      enc = FindEncoding(args[1]);
2505 	      if (enc == -1)
2506 		{
2507 		  OutputMsg(0, "%s: writebuf: unknown encoding", rc_name);
2508 		  break;
2509 		}
2510 	      if (enc != oldplop.enc)
2511 		{
2512 		  l = RecodeBuf((unsigned char *)oldplop.buf, oldplop.len, oldplop.enc, enc, (unsigned char *)0);
2513 		  newbuf = malloc(l + 1);
2514 		  if (!newbuf)
2515 		    {
2516 		      OutputMsg(0, "%s", strnomem);
2517 		      break;
2518 		    }
2519 		  user->u_plop.len = RecodeBuf((unsigned char *)oldplop.buf, oldplop.len, oldplop.enc, enc, (unsigned char *)newbuf);
2520 		  user->u_plop.buf = newbuf;
2521 		  user->u_plop.enc = enc;
2522 		}
2523 	      args += 2;
2524 	    }
2525 #endif
2526 	  if (args[0] && args[1])
2527 	    OutputMsg(0, "%s: writebuf: too many arguments", rc_name);
2528 	  else
2529 	    WriteFile(user, args[0], DUMP_EXCHANGE);
2530 #ifdef ENCODINGS
2531 	  if (user->u_plop.buf != oldplop.buf)
2532 	    free(user->u_plop.buf);
2533 	  user->u_plop = oldplop;
2534 	}
2535 #endif
2536       break;
2537     case RC_READBUF:
2538 #ifdef ENCODINGS
2539       i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
2540       if (args[0] && args[1] && !strcmp(args[0], "-e"))
2541 	{
2542 	  i = FindEncoding(args[1]);
2543 	  if (i == -1)
2544 	    {
2545 	      OutputMsg(0, "%s: readbuf: unknown encoding", rc_name);
2546 	      break;
2547 	    }
2548 	  args += 2;
2549 	}
2550 #endif
2551       if (args[0] && args[1])
2552 	{
2553 	  OutputMsg(0, "%s: readbuf: too many arguments", rc_name);
2554 	  break;
2555 	}
2556       if ((s = ReadFile(args[0] ? args[0] : BufferFile, &n)))
2557 	{
2558 	  if (user->u_plop.buf)
2559 	    UserFreeCopyBuffer(user);
2560 	  user->u_plop.len = n;
2561 	  user->u_plop.buf = s;
2562 #ifdef ENCODINGS
2563 	  user->u_plop.enc = i;
2564 #endif
2565 	}
2566       break;
2567     case RC_REMOVEBUF:
2568       KillBuffers();
2569       break;
2570     case RC_IGNORECASE:
2571       (void)ParseSwitch(act, &search_ic);
2572       if (msgok)
2573         OutputMsg(0, "Will %signore case in searches", search_ic ? "" : "not ");
2574       break;
2575 #endif				/* COPY_PASTE */
2576     case RC_ESCAPE:
2577       if (*argl == 0)
2578 	SetEscape(user, -1, -1);
2579       else if (*argl == 2)
2580 	SetEscape(user, (int)(unsigned char)args[0][0], (int)(unsigned char)args[0][1]);
2581       else
2582 	{
2583 	  OutputMsg(0, "%s: two characters required after escape.", rc_name);
2584 	  break;
2585 	}
2586       /* Change defescape if master user. This is because we only
2587        * have one ktab.
2588        */
2589       if (display && user != users)
2590 	break;
2591       /* FALLTHROUGH */
2592     case RC_DEFESCAPE:
2593       if (*argl == 0)
2594 	SetEscape(NULL, -1, -1);
2595       else if (*argl == 2)
2596 	SetEscape(NULL, (int)(unsigned char)args[0][0], (int)(unsigned char)args[0][1]);
2597       else
2598 	{
2599 	  OutputMsg(0, "%s: two characters required after defescape.", rc_name);
2600 	  break;
2601 	}
2602 #ifdef MAPKEYS
2603       CheckEscape();
2604 #endif
2605       break;
2606     case RC_CHDIR:
2607       s = *args ? *args : home;
2608       if (chdir(s) == -1)
2609 	OutputMsg(errno, "%s", s);
2610       break;
2611     case RC_SHELL:
2612     case RC_DEFSHELL:
2613       if (ParseSaveStr(act, &ShellProg) == 0)
2614         ShellArgs[0] = ShellProg;
2615       break;
2616     case RC_HARDCOPYDIR:
2617       if (*args)
2618         (void)ParseSaveStr(act, &hardcopydir);
2619       if (msgok)
2620 	OutputMsg(0, "hardcopydir is %s\n", hardcopydir && *hardcopydir ? hardcopydir : "<cwd>");
2621       break;
2622     case RC_LOGFILE:
2623       if (*args)
2624 	{
2625 	  char buf[1024];
2626 	  if (args[1] && !(strcmp(*args, "flush")))
2627 	    {
2628 	      log_flush = atoi(args[1]);
2629 	      if (msgok)
2630 		OutputMsg(0, "log flush timeout set to %ds\n", log_flush);
2631 	      break;
2632 	    }
2633 	  if (ParseSaveStr(act, &screenlogfile))
2634 	    break;
2635 	  if (fore && fore->w_log)
2636 	    if (DoStartLog(fore, buf, sizeof(buf)))
2637 	      OutputMsg(0, "Error opening logfile \"%s\"", buf);
2638 	  if (!msgok)
2639 	    break;
2640 	}
2641       OutputMsg(0, "logfile is '%s'", screenlogfile);
2642       break;
2643     case RC_LOGTSTAMP:
2644       if (!*args || !strcmp(*args, "on") || !strcmp(*args, "off"))
2645         {
2646 	  if (ParseSwitch(act, &logtstamp_on) == 0 && msgok)
2647             OutputMsg(0, "timestamps turned %s", logtstamp_on ? "on" : "off");
2648         }
2649       else if (!strcmp(*args, "string"))
2650 	{
2651 	  if (args[1])
2652 	    {
2653 	      if (logtstamp_string)
2654 		free(logtstamp_string);
2655 	      logtstamp_string = SaveStr(args[1]);
2656 	    }
2657 	  if (msgok)
2658 	    OutputMsg(0, "logfile timestamp is '%s'", logtstamp_string);
2659 	}
2660       else if (!strcmp(*args, "after"))
2661 	{
2662 	  if (args[1])
2663 	    {
2664 	      logtstamp_after = atoi(args[1]);
2665 	      if (!msgok)
2666 		break;
2667 	    }
2668 	  OutputMsg(0, "timestamp printed after %ds\n", logtstamp_after);
2669 	}
2670       else
2671         OutputMsg(0, "usage: logtstamp [after [n]|string [str]|on|off]");
2672       break;
2673     case RC_SHELLTITLE:
2674       (void)ParseSaveStr(act, &nwin_default.aka);
2675       break;
2676     case RC_TERMCAP:
2677     case RC_TERMCAPINFO:
2678     case RC_TERMINFO:
2679       if (!rc_name || !*rc_name)
2680         OutputMsg(0, "Sorry, too late now. Place that in your .screenrc file.");
2681       break;
2682     case RC_SLEEP:
2683       break;			/* Already handled */
2684     case RC_TERM:
2685       s = NULL;
2686       if (ParseSaveStr(act, &s))
2687 	break;
2688       if (strlen(s) > MAXTERMLEN)
2689 	{
2690 	  OutputMsg(0, "%s: term: argument too long ( < %d)", rc_name, MAXTERMLEN);
2691 	  free(s);
2692 	  break;
2693 	}
2694       strncpy(screenterm, s, MAXTERMLEN);
2695       screenterm[MAXTERMLEN] = '\0';
2696       free(s);
2697       debug1("screenterm set to %s\n", screenterm);
2698       MakeTermcap((display == 0));
2699       debug("new termcap made\n");
2700       break;
2701     case RC_ECHO:
2702       if (!msgok && (!rc_name || strcmp(rc_name, "-X")))
2703 	break;
2704       /*
2705        * user typed ^A:echo... well, echo isn't FinishRc's job,
2706        * but as he wanted to test us, we show good will
2707        */
2708       if (argc > 1 && !strcmp(*args, "-n"))
2709 	{
2710 	  args++;
2711 	  argc--;
2712 	}
2713       s = *args;
2714       if (argc > 1 && !strcmp(*args, "-p"))
2715 	{
2716 	  args++;
2717 	  argc--;
2718 	  s = *args;
2719 	  if (s)
2720 	    s = MakeWinMsg(s, fore, '%');
2721 	}
2722       if (s)
2723 	OutputMsg(0, "%s", s);
2724       else
2725 	{
2726 	  OutputMsg(0, "%s: 'echo [-n] [-p] \"string\"' expected.", rc_name);
2727 	  queryflag = -1;
2728 	}
2729       break;
2730     case RC_BELL:
2731     case RC_BELL_MSG:
2732       if (*args == 0)
2733 	{
2734 	  char buf[256];
2735 	  AddXChars(buf, sizeof(buf), BellString);
2736 	  OutputMsg(0, "bell_msg is '%s'", buf);
2737 	  break;
2738 	}
2739       (void)ParseSaveStr(act, &BellString);
2740       break;
2741 #ifdef COPY_PASTE
2742     case RC_BUFFERFILE:
2743       if (*args == 0)
2744 	BufferFile = SaveStr(DEFAULT_BUFFERFILE);
2745       else if (ParseSaveStr(act, &BufferFile))
2746         break;
2747       if (msgok)
2748         OutputMsg(0, "Bufferfile is now '%s'", BufferFile);
2749       break;
2750 #endif
2751     case RC_ACTIVITY:
2752       (void)ParseSaveStr(act, &ActivityString);
2753       break;
2754 #if defined(DETACH) && defined(POW_DETACH)
2755     case RC_POW_DETACH_MSG:
2756       if (*args == 0)
2757         {
2758 	  char buf[256];
2759           AddXChars(buf, sizeof(buf), PowDetachString);
2760 	  OutputMsg(0, "pow_detach_msg is '%s'", buf);
2761 	  break;
2762 	}
2763       (void)ParseSaveStr(act, &PowDetachString);
2764       break;
2765 #endif
2766 #if defined(UTMPOK) && defined(LOGOUTOK)
2767     case RC_LOGIN:
2768       n = fore->w_slot != (slot_t)-1;
2769       if (*args && !strcmp(*args, "always"))
2770 	{
2771 	  fore->w_lflag = 3;
2772 	  if (!displays && n)
2773 	    SlotToggle(n);
2774 	  break;
2775 	}
2776       if (*args && !strcmp(*args, "attached"))
2777 	{
2778 	  fore->w_lflag = 1;
2779 	  if (!displays && n)
2780 	    SlotToggle(0);
2781 	  break;
2782 	}
2783       if (ParseSwitch(act, &n) == 0)
2784         SlotToggle(n);
2785       break;
2786     case RC_DEFLOGIN:
2787       if (!strcmp(*args, "always"))
2788 	nwin_default.lflag |= 2;
2789       else if (!strcmp(*args, "attached"))
2790 	nwin_default.lflag &= ~2;
2791       else
2792         (void)ParseOnOff(act, &nwin_default.lflag);
2793       break;
2794 #endif
2795     case RC_DEFFLOW:
2796       if (args[0] && args[1] && args[1][0] == 'i')
2797 	{
2798 	  iflag = 1;
2799 	  for (display = displays; display; display = display->d_next)
2800 	    {
2801 	      if (!D_flow)
2802 		continue;
2803 #if defined(TERMIO) || defined(POSIX)
2804 	      D_NewMode.tio.c_cc[VINTR] = D_OldMode.tio.c_cc[VINTR];
2805 	      D_NewMode.tio.c_lflag |= ISIG;
2806 #else /* TERMIO || POSIX */
2807 	      D_NewMode.m_tchars.t_intrc = D_OldMode.m_tchars.t_intrc;
2808 #endif /* TERMIO || POSIX */
2809 	      SetTTY(D_userfd, &D_NewMode);
2810 	    }
2811 	}
2812       if (args[0] && args[0][0] == 'a')
2813 	nwin_default.flowflag = FLOW_AUTOFLAG;
2814       else
2815 	(void)ParseOnOff(act, &nwin_default.flowflag);
2816       break;
2817     case RC_DEFWRAP:
2818       (void)ParseOnOff(act, &nwin_default.wrap);
2819       break;
2820     case RC_DEFC1:
2821       (void)ParseOnOff(act, &nwin_default.c1);
2822       break;
2823 #ifdef COLOR
2824     case RC_DEFBCE:
2825       (void)ParseOnOff(act, &nwin_default.bce);
2826       break;
2827 #endif
2828     case RC_DEFGR:
2829       (void)ParseOnOff(act, &nwin_default.gr);
2830       break;
2831     case RC_DEFMONITOR:
2832       if (ParseOnOff(act, &n) == 0)
2833         nwin_default.monitor = (n == 0) ? MON_OFF : MON_ON;
2834       break;
2835     case RC_DEFMOUSETRACK:
2836       if (ParseOnOff(act, &n) == 0)
2837 	defmousetrack = (n == 0) ? 0 : 1000;
2838       break;
2839     case RC_MOUSETRACK:
2840       if (!args[0])
2841 	{
2842 	  OutputMsg(0, "Mouse tracking for this display is turned %s", D_mousetrack ? "on" : "off");
2843 	}
2844       else if (ParseOnOff(act, &n) == 0)
2845 	{
2846 	  D_mousetrack = n == 0 ? 0 : 1000;
2847 	  if (D_fore)
2848 	    MouseMode(D_fore->w_mouse);
2849 	}
2850       break;
2851     case RC_DEFSILENCE:
2852       if (ParseOnOff(act, &n) == 0)
2853         nwin_default.silence = (n == 0) ? SILENCE_OFF : SILENCE_ON;
2854       break;
2855     case RC_VERBOSE:
2856       if (!*args)
2857 	OutputMsg(0, "W%s echo command when creating windows.",
2858 	  VerboseCreate ? "ill" : "on't");
2859       else if (ParseOnOff(act, &n) == 0)
2860         VerboseCreate = n;
2861       break;
2862     case RC_HARDSTATUS:
2863       if (display)
2864 	{
2865 	  OutputMsg(0, "%s", "");	/* wait till mintime (keep gcc quiet) */
2866           RemoveStatus();
2867 	}
2868       if (args[0] && strcmp(args[0], "on") && strcmp(args[0], "off"))
2869 	{
2870           struct display *olddisplay = display;
2871 	  int old_use, new_use = -1;
2872 
2873 	  s = args[0];
2874 	  if (!strncmp(s, "always", 6))
2875 	    s += 6;
2876 	  if (!strcmp(s, "firstline"))
2877 	    new_use = HSTATUS_FIRSTLINE;
2878 	  else if (!strcmp(s, "lastline"))
2879 	    new_use = HSTATUS_LASTLINE;
2880 	  else if (!strcmp(s, "ignore"))
2881 	    new_use = HSTATUS_IGNORE;
2882 	  else if (!strcmp(s, "message"))
2883 	    new_use = HSTATUS_MESSAGE;
2884 	  else if (!strcmp(args[0], "string"))
2885 	    {
2886 	      if (!args[1])
2887 		{
2888 		  char buf[256];
2889 		  AddXChars(buf, sizeof(buf), hstatusstring);
2890 		  OutputMsg(0, "hardstatus string is '%s'", buf);
2891 		  break;
2892 		}
2893 	    }
2894 	  else
2895 	    {
2896 	      OutputMsg(0, "%s: usage: hardstatus [always]lastline|ignore|message|string [string]", rc_name);
2897 	      break;
2898 	    }
2899 	  if (new_use != -1)
2900 	    {
2901 	      hardstatusemu = new_use | (s == args[0] ? 0 : HSTATUS_ALWAYS);
2902 	      for (display = displays; display; display = display->d_next)
2903 		{
2904 		  RemoveStatus();
2905 		  new_use = hardstatusemu & ~HSTATUS_ALWAYS;
2906 		  if (D_HS && s == args[0])
2907 		    new_use = HSTATUS_HS;
2908 		  ShowHStatus((char *)0);
2909 		  old_use = D_has_hstatus;
2910 		  D_has_hstatus = new_use;
2911 		  if ((new_use == HSTATUS_LASTLINE && old_use != HSTATUS_LASTLINE) || (new_use != HSTATUS_LASTLINE && old_use == HSTATUS_LASTLINE))
2912 		    ChangeScreenSize(D_width, D_height, 1);
2913 		  if ((new_use == HSTATUS_FIRSTLINE && old_use != HSTATUS_FIRSTLINE) || (new_use != HSTATUS_FIRSTLINE && old_use == HSTATUS_FIRSTLINE))
2914 		    ChangeScreenSize(D_width, D_height, 1);
2915 		  RefreshHStatus();
2916 		}
2917 	    }
2918 	  if (args[1])
2919 	    {
2920 	      if (hstatusstring)
2921 		free(hstatusstring);
2922 	      hstatusstring = SaveStr(args[1]);
2923 	      for (display = displays; display; display = display->d_next)
2924 	        RefreshHStatus();
2925 	    }
2926 	  display = olddisplay;
2927 	  break;
2928 	}
2929       (void)ParseSwitch(act, &use_hardstatus);
2930       if (msgok)
2931         OutputMsg(0, "messages displayed on %s", use_hardstatus ? "hardstatus line" : "window");
2932       break;
2933     case RC_CAPTION:
2934       if (strcmp(args[0], "always") == 0 || strcmp(args[0], "splitonly") == 0)
2935 	{
2936 	  struct display *olddisplay = display;
2937 
2938 	  captionalways = args[0][0] == 'a';
2939 	  for (display = displays; display; display = display->d_next)
2940 	    ChangeScreenSize(D_width, D_height, 1);
2941 	  display = olddisplay;
2942 	}
2943       else if (strcmp(args[0], "string") == 0)
2944 	{
2945 	  if (!args[1])
2946 	    {
2947 	      char buf[256];
2948 	      AddXChars(buf, sizeof(buf), captionstring);
2949 	      OutputMsg(0, "caption string is '%s'", buf);
2950 	      break;
2951 	    }
2952 	}
2953       else
2954 	{
2955 	  OutputMsg(0, "%s: usage: caption always|splitonly|string <string>", rc_name);
2956 	  break;
2957 	}
2958       if (!args[1])
2959 	break;
2960       if (captionstring)
2961 	free(captionstring);
2962       captionstring = SaveStr(args[1]);
2963       RedisplayDisplays(0);
2964       break;
2965     case RC_CONSOLE:
2966       n = (console_window != 0);
2967       if (ParseSwitch(act, &n))
2968         break;
2969       if (TtyGrabConsole(fore->w_ptyfd, n, rc_name))
2970 	break;
2971       if (n == 0)
2972 	  OutputMsg(0, "%s: releasing console %s", rc_name, HostName);
2973       else if (console_window)
2974 	  OutputMsg(0, "%s: stealing console %s from window %d (%s)", rc_name,
2975 	      HostName, console_window->w_number, console_window->w_title);
2976       else
2977 	  OutputMsg(0, "%s: grabbing console %s", rc_name, HostName);
2978       console_window = n ? fore : 0;
2979       break;
2980     case RC_ALLPARTIAL:
2981       if (ParseOnOff(act, &all_norefresh))
2982 	break;
2983       if (!all_norefresh && fore)
2984 	Activate(-1);
2985       if (msgok)
2986         OutputMsg(0, all_norefresh ? "No refresh on window change!\n" :
2987 			       "Window specific refresh\n");
2988       break;
2989     case RC_PARTIAL:
2990       (void)ParseSwitch(act, &n);
2991       fore->w_norefresh = n;
2992       break;
2993     case RC_VBELL:
2994       if (ParseSwitch(act, &visual_bell) || !msgok)
2995         break;
2996       if (visual_bell == 0)
2997         OutputMsg(0, "switched to audible bell.");
2998       else
2999         OutputMsg(0, "switched to visual bell.");
3000       break;
3001     case RC_VBELLWAIT:
3002       if (ParseNum1000(act, &VBellWait) == 0 && msgok)
3003         OutputMsg(0, "vbellwait set to %.10g seconds", VBellWait/1000.);
3004       break;
3005     case RC_MSGWAIT:
3006       if (ParseNum1000(act, &MsgWait) == 0 && msgok)
3007         OutputMsg(0, "msgwait set to %.10g seconds", MsgWait/1000.);
3008       break;
3009     case RC_MSGMINWAIT:
3010       if (ParseNum1000(act, &MsgMinWait) == 0 && msgok)
3011         OutputMsg(0, "msgminwait set to %.10g seconds", MsgMinWait/1000.);
3012       break;
3013     case RC_SILENCEWAIT:
3014       if (ParseNum(act, &SilenceWait))
3015 	break;
3016       if (SilenceWait < 1)
3017 	SilenceWait = 1;
3018       for (p = windows; p; p = p->w_next)
3019 	p->w_silencewait = SilenceWait;
3020       if (msgok)
3021 	OutputMsg(0, "silencewait set to %d seconds", SilenceWait);
3022       break;
3023     case RC_BUMPRIGHT:
3024       if (fore->w_number < NextWindow())
3025         WindowChangeNumber(fore->w_number, NextWindow());
3026       break;
3027     case RC_BUMPLEFT:
3028       if (fore->w_number > PreviousWindow())
3029         WindowChangeNumber(fore->w_number, PreviousWindow());
3030       break;
3031     case RC_COLLAPSE:
3032       CollapseWindowlist();
3033       break;
3034     case RC_NUMBER:
3035       if (*args == 0)
3036         OutputMsg(0, queryflag >= 0 ? "%d (%s)" : "This is window %d (%s).", fore->w_number, fore->w_title);
3037       else
3038         {
3039 	  int old = fore->w_number;
3040 	  int rel = 0, parse;
3041 	  if (args[0][0] == '+')
3042 	    rel = 1;
3043 	  else if (args[0][0] == '-')
3044 	    rel = -1;
3045 	  if (rel)
3046 	    ++act->args[0];
3047 	  parse = ParseNum(act, &n);
3048 	  if (rel)
3049 	    --act->args[0];
3050 	  if (parse)
3051 	    break;
3052 	  if (rel > 0)
3053 	    n += old;
3054 	  else if (rel < 0)
3055 	    n = old - n;
3056 	  if (!WindowChangeNumber(old, n))
3057 	    {
3058 	      /* Window number could not be changed. */
3059 	      queryflag = -1;
3060 	      return;
3061 	    }
3062 	}
3063       break;
3064 
3065 		case RC_ZOMBIE_TIMEOUT:
3066 			if (argc != 1) {
3067 				Msg(0, "Setting zombie polling needs a timeout arg\n");
3068 				break;
3069 			}
3070 
3071 			nwin_default.poll_zombie_timeout = atoi(args[0]);
3072 			if (fore)
3073 				fore->w_poll_zombie_timeout = nwin_default.poll_zombie_timeout;
3074 			debug1("Setting zombie polling to %d\n", nwin_default.poll_zombie_timeout);
3075 			break;
3076 
3077 		case RC_SORT:
3078 			if (fore) {
3079 			/* Better do not allow this. Not sure what the utmp stuff in number
3080 			* command above is for (you get four entries in e.g. /var/log/wtmp
3081 			* per number switch). But I don't know enough about this.
3082 			*/
3083 				Msg(0, "Sorting inside a window is not allowed. Push CTRL-a \" "
3084 					"and try again\n");
3085 				break;
3086 			}
3087 			/*
3088 			* Simple sort algorithm: Look out for the smallest, put it
3089 			* to the first place, look out for the 2nd smallest, ...
3090 			*/
3091 			for (i = 0; i < maxwin ; i++) {
3092 				if (wtab[i] == NULL)
3093 					continue;
3094 				n = i;
3095 
3096 				for (nr = i + 1; nr < maxwin; nr++) {
3097 					if (wtab[nr] == NULL)
3098 						continue;
3099 					debug2("Testing window %d and %d.\n", nr, n);
3100 					if (strcmp(wtab[nr]->w_title,wtab[n]->w_title) < 0)
3101 						n = nr;
3102 				}
3103 
3104 				if (n != i) {
3105 					debug2("Exchange window %d and %d.\n", i, n);
3106 					p = wtab[n];
3107 					wtab[n] = wtab[i];
3108 					wtab[i] = p;
3109 					wtab[n]->w_number = n;
3110 					wtab[i]->w_number = i;
3111 #ifdef MULTIUSER
3112 					/* exchange the acls for these windows. */
3113 					AclWinSwap(i, n);
3114 #endif
3115 				}
3116 			}
3117 			WindowChanged((struct win *)0, 0);
3118 			break;
3119 
3120     case RC_SILENCE:
3121       n = fore->w_silence != 0;
3122       i = fore->w_silencewait;
3123       if (args[0] && (args[0][0] == '-' || (args[0][0] >= '0' && args[0][0] <= '9')))
3124         {
3125 	  if (ParseNum(act, &i))
3126 	    break;
3127 	  n = i > 0;
3128 	}
3129       else if (ParseSwitch(act, &n))
3130         break;
3131       if (n)
3132         {
3133 #ifdef MULTIUSER
3134 	  if (display)	/* we tell only this user */
3135 	    ACLBYTE(fore->w_lio_notify, D_user->u_id) |= ACLBIT(D_user->u_id);
3136 	  else
3137 	    for (n = 0; n < maxusercount; n++)
3138 	      ACLBYTE(fore->w_lio_notify, n) |= ACLBIT(n);
3139 #endif
3140 	  fore->w_silencewait = i;
3141 	  fore->w_silence = SILENCE_ON;
3142 	  SetTimeout(&fore->w_silenceev, fore->w_silencewait * 1000);
3143 	  evenq(&fore->w_silenceev);
3144 
3145 	  if (!msgok)
3146 	    break;
3147 	  OutputMsg(0, "The window is now being monitored for %d sec. silence.", fore->w_silencewait);
3148 	}
3149       else
3150         {
3151 #ifdef MULTIUSER
3152 	  if (display) /* we remove only this user */
3153 	    ACLBYTE(fore->w_lio_notify, D_user->u_id)
3154 	      &= ~ACLBIT(D_user->u_id);
3155 	  else
3156 	    for (n = 0; n < maxusercount; n++)
3157 	      ACLBYTE(fore->w_lio_notify, n) &= ~ACLBIT(n);
3158 	  for (i = maxusercount - 1; i >= 0; i--)
3159 	    if (ACLBYTE(fore->w_lio_notify, i))
3160 	      break;
3161 	  if (i < 0)
3162 #endif
3163 	    {
3164 	      fore->w_silence = SILENCE_OFF;
3165 	      evdeq(&fore->w_silenceev);
3166 	    }
3167 	  if (!msgok)
3168 	    break;
3169 	  OutputMsg(0, "The window is no longer being monitored for silence.");
3170 	}
3171       break;
3172 #ifdef COPY_PASTE
3173     case RC_DEFSCROLLBACK:
3174       (void)ParseNum(act, &nwin_default.histheight);
3175       break;
3176     case RC_SCROLLBACK:
3177       if (flayer->l_layfn == &MarkLf)
3178 	{
3179 	  OutputMsg(0, "Cannot resize scrollback buffer in copy/scrollback mode.");
3180 	  break;
3181 	}
3182       (void)ParseNum(act, &n);
3183       ChangeWindowSize(fore, fore->w_width, fore->w_height, n);
3184       if (msgok)
3185 	OutputMsg(0, "scrollback set to %d", fore->w_histheight);
3186       break;
3187 #endif
3188     case RC_SESSIONNAME:
3189       if (*args == 0)
3190 	OutputMsg(0, "This session is named '%s'\n", SockName);
3191       else
3192 	{
3193 	  char buf[MAXPATHLEN];
3194 
3195 	  s = 0;
3196 	  if (ParseSaveStr(act, &s))
3197 	    break;
3198 	  if (!*s || strlen(s) + (SockName - SockPath) > MAXPATHLEN - 13 || index(s, '/'))
3199 	    {
3200 	      OutputMsg(0, "%s: bad session name '%s'\n", rc_name, s);
3201 	      free(s);
3202 	      break;
3203 	    }
3204 	  strncpy(buf, SockPath, SockName - SockPath);
3205 	  sprintf(buf + (SockName - SockPath), "%d.%s", (int)getpid(), s);
3206 	  free(s);
3207 	  if ((access(buf, F_OK) == 0) || (errno != ENOENT))
3208 	    {
3209 	      OutputMsg(0, "%s: inappropriate path: '%s'.", rc_name, buf);
3210 	      break;
3211 	    }
3212 	  if (rename(SockPath, buf))
3213 	    {
3214 	      OutputMsg(errno, "%s: failed to rename(%s, %s)", rc_name, SockPath, buf);
3215 	      break;
3216 	    }
3217 	  debug2("rename(%s, %s) done\n", SockPath, buf);
3218 	  strcpy(SockPath, buf);
3219 	  MakeNewEnv();
3220 	  WindowChanged((struct win *)0, 'S');
3221 	}
3222       break;
3223     case RC_SETENV:
3224       if (!args[0] || !args[1])
3225         {
3226 	  debug1("RC_SETENV arguments missing: %s\n", args[0] ? args[0] : "");
3227           InputSetenv(args[0]);
3228 	}
3229       else
3230         {
3231           xsetenv(args[0], args[1]);
3232           MakeNewEnv();
3233 	}
3234       break;
3235     case RC_UNSETENV:
3236       unsetenv(*args);
3237       MakeNewEnv();
3238       break;
3239 #ifdef COPY_PASTE
3240     case RC_DEFSLOWPASTE:
3241       (void)ParseNum(act, &nwin_default.slow);
3242       break;
3243     case RC_SLOWPASTE:
3244       if (*args == 0)
3245 	OutputMsg(0, fore->w_slowpaste ?
3246                "Slowpaste in window %d is %d milliseconds." :
3247                "Slowpaste in window %d is unset.",
3248 	    fore->w_number, fore->w_slowpaste);
3249       else if (ParseNum(act, &fore->w_slowpaste) == 0 && msgok)
3250 	OutputMsg(0, fore->w_slowpaste ?
3251                "Slowpaste in window %d set to %d milliseconds." :
3252                "Slowpaste in window %d now unset.",
3253 	    fore->w_number, fore->w_slowpaste);
3254       break;
3255     case RC_MARKKEYS:
3256       if (CompileKeys(*args, *argl, mark_key_tab))
3257 	{
3258 	  OutputMsg(0, "%s: markkeys: syntax error.", rc_name);
3259 	  break;
3260 	}
3261       debug1("markkeys %s\n", *args);
3262       break;
3263 # ifdef FONT
3264     case RC_PASTEFONT:
3265       if (ParseSwitch(act, &pastefont) == 0 && msgok)
3266         OutputMsg(0, "Will %spaste font settings", pastefont ? "" : "not ");
3267       break;
3268 # endif
3269     case RC_CRLF:
3270       (void)ParseSwitch(act, &join_with_cr);
3271       break;
3272     case RC_COMPACTHIST:
3273       if (ParseSwitch(act, &compacthist) == 0 && msgok)
3274 	OutputMsg(0, "%scompacting history lines", compacthist ? "" : "not ");
3275       break;
3276 #endif
3277 #ifdef NETHACK
3278     case RC_NETHACK:
3279       (void)ParseOnOff(act, &nethackflag);
3280       break;
3281 #else
3282     case RC_NETHACK:
3283       Msg(0, "nethack disabled at build time");
3284       break;
3285 #endif
3286     case RC_HARDCOPY_APPEND:
3287       (void)ParseOnOff(act, &hardcopy_append);
3288       break;
3289     case RC_VBELL_MSG:
3290       if (*args == 0)
3291         {
3292 	  char buf[256];
3293           AddXChars(buf, sizeof(buf), VisualBellString);
3294 	  OutputMsg(0, "vbell_msg is '%s'", buf);
3295 	  break;
3296 	}
3297       (void)ParseSaveStr(act, &VisualBellString);
3298       debug1(" new vbellstr '%s'\n", VisualBellString);
3299       break;
3300     case RC_DEFMODE:
3301       if (ParseBase(act, *args, &n, 8, "octal"))
3302         break;
3303       if (n < 0 || n > 0777)
3304 	{
3305 	  OutputMsg(0, "%s: mode: Invalid tty mode %o", rc_name, n);
3306           break;
3307 	}
3308       TtyMode = n;
3309       if (msgok)
3310 	OutputMsg(0, "Ttymode set to %03o", TtyMode);
3311       break;
3312     case RC_AUTODETACH:
3313       (void)ParseOnOff(act, &auto_detach);
3314       break;
3315     case RC_STARTUP_MESSAGE:
3316       (void)ParseOnOff(act, &default_startup);
3317       break;
3318 #ifdef PASSWORD
3319     case RC_PASSWORD:
3320       if (*args)
3321 	{
3322 	  n = (*user->u_password) ? 1 : 0;
3323 	  if (user->u_password != NullStr) free((char *)user->u_password);
3324 	  user->u_password = SaveStr(*args);
3325 	  if (!strcmp(user->u_password, "none"))
3326 	    {
3327 	      if (n)
3328 	        OutputMsg(0, "Password checking disabled");
3329 	      free(user->u_password);
3330 	      user->u_password = NullStr;
3331 	    }
3332 	}
3333       else
3334 	{
3335 	  if (!fore)
3336 	    {
3337 	      OutputMsg(0, "%s: password: window required", rc_name);
3338 	      break;
3339 	    }
3340 	  Input("New screen password:", 100, INP_NOECHO, pass1, display ? (char *)D_user : (char *)users, 0);
3341 	}
3342       break;
3343 #endif				/* PASSWORD */
3344     case RC_BIND:
3345 	{
3346 	  struct action *ktabp = ktab;
3347 	  int kflag = 0;
3348 
3349 	  for (;;)
3350 	    {
3351 	      if (argc > 2 && !strcmp(*args, "-c"))
3352 		{
3353 		  ktabp = FindKtab(args[1], 1);
3354 		  if (ktabp == 0)
3355 		    break;
3356 		  args += 2;
3357 		  argl += 2;
3358 		  argc -= 2;
3359 		}
3360 	      else if (argc > 1 && !strcmp(*args, "-k"))
3361 	        {
3362 		  kflag = 1;
3363 		  args++;
3364 		  argl++;
3365 		  argc--;
3366 		}
3367 	      else
3368 	        break;
3369 	    }
3370 #ifdef MAPKEYS
3371           if (kflag)
3372 	    {
3373 	      for (n = 0; n < KMAP_KEYS; n++)
3374 		if (strcmp(term[n + T_CAPS].tcname, *args) == 0)
3375 		  break;
3376 	      if (n == KMAP_KEYS)
3377 		{
3378 		  OutputMsg(0, "%s: bind: unknown key '%s'", rc_name, *args);
3379 		  break;
3380 		}
3381 	      n += 256;
3382 	    }
3383 	  else
3384 #endif
3385 	  if (*argl != 1)
3386 	    {
3387 	      OutputMsg(0, "%s: bind: character, ^x, or (octal) \\032 expected.", rc_name);
3388 	      break;
3389 	    }
3390 	  else
3391 	    n = (unsigned char)args[0][0];
3392 
3393 	  if (args[1])
3394 	    {
3395 	      if ((i = FindCommnr(args[1])) == RC_ILLEGAL)
3396 		{
3397 		  OutputMsg(0, "%s: bind: unknown command '%s'", rc_name, args[1]);
3398 		  break;
3399 		}
3400 	      if (CheckArgNum(i, args + 2) < 0)
3401 		break;
3402 	      ClearAction(&ktabp[n]);
3403 	      SaveAction(ktabp + n, i, args + 2, argl + 2);
3404 	    }
3405 	  else
3406 	    ClearAction(&ktabp[n]);
3407 	}
3408       break;
3409 #ifdef MAPKEYS
3410     case RC_BINDKEY:
3411 	{
3412 	  struct action *newact;
3413           int newnr, fl = 0, kf = 0, af = 0, df = 0, mf = 0;
3414 	  struct display *odisp = display;
3415 	  int used = 0;
3416           struct kmap_ext *kme = NULL;
3417 
3418 	  for (; *args && **args == '-'; args++, argl++)
3419 	    {
3420 	      if (strcmp(*args, "-t") == 0)
3421 		fl = KMAP_NOTIMEOUT;
3422 	      else if (strcmp(*args, "-k") == 0)
3423 		kf = 1;
3424 	      else if (strcmp(*args, "-a") == 0)
3425 		af = 1;
3426 	      else if (strcmp(*args, "-d") == 0)
3427 		df = 1;
3428 	      else if (strcmp(*args, "-m") == 0)
3429 		mf = 1;
3430 	      else if (strcmp(*args, "--") == 0)
3431 		{
3432 		  args++;
3433 		  argl++;
3434 		  break;
3435 		}
3436 	      else
3437 		{
3438 	          OutputMsg(0, "%s: bindkey: invalid option %s", rc_name, *args);
3439 		  return;
3440 		}
3441 	    }
3442 	  if (df && mf)
3443 	    {
3444 	      OutputMsg(0, "%s: bindkey: -d does not work with -m", rc_name);
3445 	      break;
3446 	    }
3447 	  if (*args == 0)
3448 	    {
3449 	      if (mf)
3450 		display_bindkey("Edit mode", mmtab);
3451 	      else if (df)
3452 		display_bindkey("Default", dmtab);
3453 	      else
3454 		display_bindkey("User", umtab);
3455 	      break;
3456 	    }
3457 	  if (kf == 0)
3458 	    {
3459 	      if (af)
3460 		{
3461 		  OutputMsg(0, "%s: bindkey: -a only works with -k", rc_name);
3462 		  break;
3463 		}
3464 	      if (*argl == 0)
3465 		{
3466 		  OutputMsg(0, "%s: bindkey: empty string makes no sense", rc_name);
3467 		  break;
3468 		}
3469 	      for (i = 0, kme = kmap_exts; i < kmap_extn; i++, kme++)
3470 		if (kme->str == 0)
3471 		  {
3472 		    if (args[1])
3473 		      break;
3474 		  }
3475 		else
3476 		  if (*argl == (kme->fl & ~KMAP_NOTIMEOUT) && bcmp(kme->str, *args, *argl) == 0)
3477 		      break;
3478 	      if (i == kmap_extn)
3479 		{
3480 		  if (!args[1])
3481 		    {
3482 		      OutputMsg(0, "%s: bindkey: keybinding not found", rc_name);
3483 		      break;
3484 		    }
3485 		  kmap_extn += 8;
3486 		  kmap_exts = (struct kmap_ext *)xrealloc((char *)kmap_exts, kmap_extn * sizeof(*kmap_exts));
3487 		  kme = kmap_exts + i;
3488 		  bzero((char *)kme, 8 * sizeof(*kmap_exts));
3489 		  for (; i < kmap_extn; i++, kme++)
3490 		    {
3491 		      kme->str = 0;
3492 		      kme->dm.nr = kme->mm.nr = kme->um.nr = RC_ILLEGAL;
3493 		      kme->dm.args = kme->mm.args = kme->um.args = noargs;
3494 		      kme->dm.argl = kme->mm.argl = kme->um.argl = 0;
3495 		    }
3496 		  i -= 8;
3497 		  kme -= 8;
3498 		}
3499 	      if (df == 0 && kme->dm.nr != RC_ILLEGAL)
3500 		used = 1;
3501 	      if (mf == 0 && kme->mm.nr != RC_ILLEGAL)
3502 		used = 1;
3503 	      if ((df || mf) && kme->um.nr != RC_ILLEGAL)
3504 		used = 1;
3505 	      i += KMAP_KEYS + KMAP_AKEYS;
3506 	      newact = df ? &kme->dm : mf ? &kme->mm : &kme->um;
3507 	    }
3508 	  else
3509 	    {
3510 	      for (i = T_CAPS; i < T_OCAPS; i++)
3511 		if (strcmp(term[i].tcname, *args) == 0)
3512 		  break;
3513 	      if (i == T_OCAPS)
3514 		{
3515 		  OutputMsg(0, "%s: bindkey: unknown key '%s'", rc_name, *args);
3516 		  break;
3517 		}
3518 	      if (af && i >= T_CURSOR && i < T_OCAPS)
3519 	        i -=  T_CURSOR - KMAP_KEYS;
3520 	      else
3521 	        i -=  T_CAPS;
3522 	      newact = df ? &dmtab[i] : mf ? &mmtab[i] : &umtab[i];
3523 	    }
3524 	  if (args[1])
3525 	    {
3526 	      if ((newnr = FindCommnr(args[1])) == RC_ILLEGAL)
3527 		{
3528 		  OutputMsg(0, "%s: bindkey: unknown command '%s'", rc_name, args[1]);
3529 		  break;
3530 		}
3531 	      if (CheckArgNum(newnr, args + 2) < 0)
3532 		break;
3533 	      ClearAction(newact);
3534 	      SaveAction(newact, newnr, args + 2, argl + 2);
3535 	      if (kf == 0 && args[1])
3536 		{
3537 		  if (kme->str)
3538 		    free(kme->str);
3539 		  kme->str = SaveStrn(*args, *argl);
3540 		  kme->fl = fl | *argl;
3541 		}
3542 	    }
3543 	  else
3544 	    ClearAction(newact);
3545 	  for (display = displays; display; display = display->d_next)
3546 	    remap(i, args[1] ? 1 : 0);
3547 	  if (kf == 0 && !args[1])
3548 	    {
3549 	      if (!used && kme->str)
3550 		{
3551 		  free(kme->str);
3552 		  kme->str = 0;
3553 		  kme->fl = 0;
3554 		}
3555 	    }
3556 	  display = odisp;
3557 	}
3558       break;
3559     case RC_MAPTIMEOUT:
3560       if (*args)
3561 	{
3562           if (ParseNum(act, &n))
3563 	    break;
3564 	  if (n < 0)
3565 	    {
3566 	      OutputMsg(0, "%s: maptimeout: illegal time %d", rc_name, n);
3567 	      break;
3568 	    }
3569 	  maptimeout = n;
3570 	}
3571       if (*args == 0 || msgok)
3572         OutputMsg(0, "maptimeout is %dms", maptimeout);
3573       break;
3574     case RC_MAPNOTNEXT:
3575       D_dontmap = 1;
3576       break;
3577     case RC_MAPDEFAULT:
3578       D_mapdefault = 1;
3579       break;
3580 #endif
3581 #ifdef MULTIUSER
3582     case RC_ACLCHG:
3583     case RC_ACLADD:
3584     case RC_ADDACL:
3585     case RC_CHACL:
3586       UsersAcl(NULL, argc, args);
3587       break;
3588     case RC_ACLDEL:
3589       if (UserDel(args[0], NULL))
3590 	break;
3591       if (msgok)
3592 	OutputMsg(0, "%s removed from acl database", args[0]);
3593       break;
3594     case RC_ACLGRP:
3595       /*
3596        * modify a user to gain or lose rights granted to a group.
3597        * This group is actually a normal user whose rights were defined
3598        * with chacl in the usual way.
3599        */
3600       if (args[1])
3601         {
3602 	  if (strcmp(args[1], "none"))	/* link a user to another user */
3603 	    {
3604 	      if (AclLinkUser(args[0], args[1]))
3605 		break;
3606 	      if (msgok)
3607 		OutputMsg(0, "User %s joined acl-group %s", args[0], args[1]);
3608 	    }
3609 	  else				/* remove all groups from user */
3610 	    {
3611 	      struct acluser *u;
3612 	      struct aclusergroup *g;
3613 
3614 	      if (!(u = *FindUserPtr(args[0])))
3615 	        break;
3616 	      while ((g = u->u_group))
3617 	        {
3618 		  u->u_group = g->next;
3619 	  	  free((char *)g);
3620 	        }
3621 	    }
3622 	}
3623       else				/* show all groups of user */
3624 	{
3625 	  char buf[256], *p = buf;
3626 	  int ngroups = 0;
3627 	  struct acluser *u;
3628 	  struct aclusergroup *g;
3629 
3630 	  if (!(u = *FindUserPtr(args[0])))
3631 	    {
3632 	      if (msgok)
3633 		OutputMsg(0, "User %s does not exist.", args[0]);
3634 	      break;
3635 	    }
3636 	  g = u->u_group;
3637 	  while (g)
3638 	    {
3639 	      ngroups++;
3640 	      sprintf(p, "%s ", g->u->u_name);
3641 	      p += strlen(p);
3642 	      if (p > buf+200)
3643 		break;
3644 	      g = g->next;
3645 	    }
3646 	  if (ngroups)
3647 	    *(--p) = '\0';
3648 	  OutputMsg(0, "%s's group%s: %s.", args[0], (ngroups == 1) ? "" : "s",
3649 	      (ngroups == 0) ? "none" : buf);
3650 	}
3651       break;
3652     case RC_ACLUMASK:
3653     case RC_UMASK:
3654       while ((s = *args++))
3655         {
3656 	  char *err = 0;
3657 
3658 	  if (AclUmask(display ? D_user : users, s, &err))
3659 	    OutputMsg(0, "umask: %s\n", err);
3660 	}
3661       break;
3662     case RC_MULTIUSER:
3663       if (ParseOnOff(act, &n))
3664 	break;
3665       multi = n ? "" : 0;
3666       chsock();
3667       if (msgok)
3668 	OutputMsg(0, "Multiuser mode %s", multi ? "enabled" : "disabled");
3669       break;
3670 #endif /* MULTIUSER */
3671 #ifdef PSEUDOS
3672     case RC_EXEC:
3673       winexec(args);
3674       break;
3675 #endif
3676 #ifdef MULTI
3677     case RC_NONBLOCK:
3678       i = D_nonblock >= 0;
3679       if (*args && ((args[0][0] >= '0' && args[0][0] <= '9') || args[0][0] == '.'))
3680 	{
3681           if (ParseNum1000(act, &i))
3682 	    break;
3683 	}
3684       else if (!ParseSwitch(act, &i))
3685 	i = i == 0 ? -1 : 1000;
3686       else
3687 	break;
3688       if (msgok && i == -1)
3689         OutputMsg(0, "display set to blocking mode");
3690       else if (msgok && i == 0)
3691         OutputMsg(0, "display set to nonblocking mode, no timeout");
3692       else if (msgok)
3693         OutputMsg(0, "display set to nonblocking mode, %.10gs timeout", i/1000.);
3694       D_nonblock = i;
3695       if (D_nonblock <= 0)
3696 	evdeq(&D_blockedev);
3697       break;
3698     case RC_DEFNONBLOCK:
3699       if (*args && ((args[0][0] >= '0' && args[0][0] <= '9') || args[0][0] == '.'))
3700 	{
3701           if (ParseNum1000(act, &defnonblock))
3702 	    break;
3703 	}
3704       else if (!ParseOnOff(act, &defnonblock))
3705         defnonblock = defnonblock == 0 ? -1 : 1000;
3706       else
3707 	break;
3708       if (display && *rc_name)
3709 	{
3710 	  D_nonblock = defnonblock;
3711           if (D_nonblock <= 0)
3712 	    evdeq(&D_blockedev);
3713 	}
3714       break;
3715 #endif
3716     case RC_GR:
3717 #ifdef ENCODINGS
3718       if (fore->w_gr == 2)
3719 	fore->w_gr = 0;
3720 #endif
3721       if (ParseSwitch(act, &fore->w_gr) == 0 && msgok)
3722         OutputMsg(0, "Will %suse GR", fore->w_gr ? "" : "not ");
3723 #ifdef ENCODINGS
3724       if (fore->w_gr == 0 && fore->w_FontE)
3725 	fore->w_gr = 2;
3726 #endif
3727       break;
3728     case RC_C1:
3729       if (ParseSwitch(act, &fore->w_c1) == 0 && msgok)
3730         OutputMsg(0, "Will %suse C1", fore->w_c1 ? "" : "not ");
3731       break;
3732 #ifdef COLOR
3733     case RC_BCE:
3734       if (ParseSwitch(act, &fore->w_bce) == 0 && msgok)
3735         OutputMsg(0, "Will %serase with background color", fore->w_bce ? "" : "not ");
3736       break;
3737 #endif
3738 #ifdef ENCODINGS
3739     case RC_KANJI:
3740     case RC_ENCODING:
3741 #ifdef UTF8
3742       if (*args && !strcmp(args[0], "-d"))
3743 	{
3744 	  if (!args[1])
3745 	    OutputMsg(0, "encodings directory is %s", screenencodings ? screenencodings : "<unset>");
3746 	  else
3747 	    {
3748 	      free(screenencodings);
3749 	      screenencodings = SaveStr(args[1]);
3750 	    }
3751 	  break;
3752 	}
3753       if (*args && !strcmp(args[0], "-l"))
3754 	{
3755 	  if (!args[1])
3756 	    OutputMsg(0, "encoding: -l: argument required");
3757 	  else if (LoadFontTranslation(-1, args[1]))
3758 	    OutputMsg(0, "encoding: could not load utf8 encoding file");
3759 	  else if (msgok)
3760 	    OutputMsg(0, "encoding: utf8 encoding file loaded");
3761 	  break;
3762 	}
3763 #else
3764       if (*args && (!strcmp(args[0], "-l") || !strcmp(args[0], "-d")))
3765 	{
3766 	  if (msgok)
3767 	    OutputMsg(0, "encoding: screen is not compiled for UTF-8.");
3768 	  break;
3769 	}
3770 #endif
3771       for (i = 0; i < 2; i++)
3772 	{
3773 	  if (args[i] == 0)
3774 	    break;
3775 	  if (!strcmp(args[i], "."))
3776 	    continue;
3777 	  n = FindEncoding(args[i]);
3778 	  if (n == -1)
3779 	    {
3780 	      OutputMsg(0, "encoding: unknown encoding '%s'", args[i]);
3781 	      break;
3782 	    }
3783 	  if (i == 0 && fore)
3784 	    {
3785 	      WinSwitchEncoding(fore, n);
3786 	      ResetCharsets(fore);
3787 	    }
3788 	  else if (i && display)
3789 	    D_encoding  = n;
3790 	}
3791       break;
3792     case RC_DEFKANJI:
3793     case RC_DEFENCODING:
3794       n = FindEncoding(*args);
3795       if (n == -1)
3796 	{
3797 	  OutputMsg(0, "defencoding: unknown encoding '%s'", *args);
3798 	  break;
3799 	}
3800       nwin_default.encoding = n;
3801       break;
3802 #endif
3803 
3804 #ifdef UTF8
3805     case RC_DEFUTF8:
3806       n = nwin_default.encoding == UTF8;
3807       if (ParseSwitch(act, &n) == 0)
3808 	{
3809 	  nwin_default.encoding = n ? UTF8 : 0;
3810 	  if (msgok)
3811             OutputMsg(0, "Will %suse UTF-8 encoding for new windows", n ? "" : "not ");
3812 	}
3813       break;
3814     case RC_UTF8:
3815       for (i = 0; i < 2; i++)
3816 	{
3817 	  if (i && args[i] == 0)
3818 	    break;
3819 	  if (args[i] == 0)
3820 	    n = fore->w_encoding != UTF8;
3821 	  else if (strcmp(args[i], "off") == 0)
3822 	    n = 0;
3823 	  else if (strcmp(args[i], "on") == 0)
3824 	    n = 1;
3825 	  else
3826 	    {
3827 	      OutputMsg(0, "utf8: illegal argument (%s)", args[i]);
3828 	      break;
3829 	    }
3830 	  if (i == 0)
3831 	    {
3832 	      WinSwitchEncoding(fore, n ? UTF8 : 0);
3833 	      if (msgok)
3834 		OutputMsg(0, "Will %suse UTF-8 encoding", n ? "" : "not ");
3835 	    }
3836 	  else if (display)
3837 	    D_encoding = n ? UTF8 : 0;
3838 	  if (args[i] == 0)
3839 	    break;
3840 	}
3841       break;
3842 #endif
3843 
3844     case RC_PRINTCMD:
3845       if (*args)
3846 	{
3847 	  if (printcmd)
3848 	    free(printcmd);
3849 	  printcmd = 0;
3850 	  if (**args)
3851 	    printcmd = SaveStr(*args);
3852 	}
3853       if (*args == 0 || msgok)
3854 	{
3855 	  if (printcmd)
3856 	    OutputMsg(0, "using '%s' as print command", printcmd);
3857 	  else
3858 	    OutputMsg(0, "using termcap entries for printing");
3859 	    break;
3860 	}
3861       break;
3862 
3863     case RC_DIGRAPH:
3864       if (argl && argl[0] > 0 && args[1] && argl[1] > 0)
3865 	{
3866 	  if (argl[0] != 2)
3867 	    {
3868 	      OutputMsg(0, "Two characters expected to define a digraph");
3869 	      break;
3870 	    }
3871 	  i = digraph_find(args[0]);
3872 	  digraphs[i].d[0] = args[0][0];
3873 	  digraphs[i].d[1] = args[0][1];
3874 	  if (!parse_input_int(args[1], argl[1], &digraphs[i].value))
3875 	    {
3876 	      if (!(digraphs[i].value = atoi(args[1])))
3877 		{
3878 		  if (!args[1][1])
3879 		    digraphs[i].value = (int)args[1][0];
3880 #ifdef UTF8
3881 		  else
3882 		    {
3883 		      int t;
3884 		      unsigned char *s = (unsigned char *)args[1];
3885 		      digraphs[i].value = 0;
3886 		      while (*s)
3887 			{
3888 			  t = FromUtf8(*s++, &digraphs[i].value);
3889 			  if (t == -1)
3890 			    continue;
3891 			  if (t == -2)
3892 			    digraphs[i].value = 0;
3893 			  else
3894 			    digraphs[i].value = t;
3895 			  break;
3896 			}
3897 		    }
3898 #endif
3899 		}
3900 	    }
3901 	  break;
3902 	}
3903       Input("Enter digraph: ", 10, INP_EVERY, digraph_fn, NULL, 0);
3904       if (*args && **args)
3905 	{
3906 	  s = *args;
3907 	  n = strlen(s);
3908 	  LayProcess(&s, &n);
3909 	}
3910       break;
3911 
3912     case RC_DEFHSTATUS:
3913       if (*args == 0)
3914 	{
3915 	  char buf[256];
3916           *buf = 0;
3917 	  if (nwin_default.hstatus)
3918             AddXChars(buf, sizeof(buf), nwin_default.hstatus);
3919 	  OutputMsg(0, "default hstatus is '%s'", buf);
3920 	  break;
3921         }
3922       (void)ParseSaveStr(act, &nwin_default.hstatus);
3923       if (*nwin_default.hstatus == 0)
3924 	{
3925 	  free(nwin_default.hstatus);
3926 	  nwin_default.hstatus = 0;
3927 	}
3928       break;
3929     case RC_HSTATUS:
3930       (void)ParseSaveStr(act, &fore->w_hstatus);
3931       if (*fore->w_hstatus == 0)
3932 	{
3933 	  free(fore->w_hstatus);
3934 	  fore->w_hstatus = 0;
3935 	}
3936       WindowChanged(fore, 'h');
3937       break;
3938 
3939 #ifdef FONT
3940     case RC_DEFCHARSET:
3941     case RC_CHARSET:
3942       if (*args == 0)
3943         {
3944 	  char buf[256];
3945           *buf = 0;
3946 	  if (nwin_default.charset)
3947             AddXChars(buf, sizeof(buf), nwin_default.charset);
3948 	  OutputMsg(0, "default charset is '%s'", buf);
3949 	  break;
3950         }
3951       n = strlen(*args);
3952       if (n == 0 || n > 6)
3953 	{
3954 	  OutputMsg(0, "%s: %s: string has illegal size.", rc_name, comms[nr].name);
3955 	  break;
3956 	}
3957       if (n > 4 && (
3958         ((args[0][4] < '0' || args[0][4] > '3') && args[0][4] != '.') ||
3959         ((args[0][5] < '0' || args[0][5] > '3') && args[0][5] && args[0][5] != '.')))
3960 	{
3961 	  OutputMsg(0, "%s: %s: illegal mapping number.", rc_name, comms[nr].name);
3962 	  break;
3963 	}
3964       if (nr == RC_CHARSET)
3965 	{
3966 	  SetCharsets(fore, *args);
3967 	  break;
3968 	}
3969       if (nwin_default.charset)
3970 	free(nwin_default.charset);
3971       nwin_default.charset = SaveStr(*args);
3972       break;
3973 #endif
3974 #ifdef COLOR
3975     case RC_ATTRCOLOR:
3976       s = args[0];
3977       if (*s >= '0' && *s <= '9')
3978         i = *s - '0';
3979       else
3980 	for (i = 0; i < 8; i++)
3981 	  if (*s == "dubrsBiI"[i])
3982 	    break;
3983       s++;
3984       nr = 0;
3985       if (*s && s[1] && !s[2])
3986 	{
3987 	  if (*s == 'd' && s[1] == 'd')
3988 	    nr = 3;
3989 	  else if (*s == '.' && s[1] == 'd')
3990 	    nr = 2;
3991 	  else if (*s == 'd' && s[1] == '.')
3992 	    nr = 1;
3993 	  else if (*s != '.' || s[1] != '.')
3994 	    s--;
3995 	  s += 2;
3996 	}
3997       if (*s || i < 0 || i >= 8)
3998 	{
3999 	  OutputMsg(0, "%s: attrcolor: unknown attribute '%s'.", rc_name, args[0]);
4000 	  break;
4001 	}
4002       n = 0;
4003       if (args[1])
4004         n = ParseAttrColor(args[1], args[2], 1);
4005       if (n == -1)
4006 	break;
4007       attr2color[i][nr] = n;
4008       n = 0;
4009       for (i = 0; i < 8; i++)
4010 	if (attr2color[i][0] || attr2color[i][1] || attr2color[i][2] || attr2color[i][3])
4011 	  n |= 1 << i;
4012       nattr2color = n;
4013       break;
4014 #endif
4015     case RC_RENDITION:
4016       i = -1;
4017       if (strcmp(args[0], "bell") == 0)
4018 	{
4019 	  i = REND_BELL;
4020 	}
4021       else if (strcmp(args[0], "monitor") == 0)
4022 	{
4023 	  i = REND_MONITOR;
4024 	}
4025       else if (strcmp(args[0], "silence") == 0)
4026 	{
4027 	  i = REND_SILENCE;
4028 	}
4029       else if (strcmp(args[0], "so") != 0)
4030 	{
4031 	  OutputMsg(0, "Invalid option '%s' for rendition", args[0]);
4032 	  break;
4033 	}
4034 
4035       ++args;
4036       ++argl;
4037 
4038       if (i != -1)
4039 	{
4040 	  renditions[i] = ParseAttrColor(args[0], args[1], 1);
4041 	  WindowChanged((struct win *)0, 'w');
4042 	  WindowChanged((struct win *)0, 'W');
4043 	  WindowChanged((struct win *)0, 0);
4044 	  break;
4045 	}
4046 
4047       /* We are here, means we want to set the sorendition. */
4048       /* FALLTHROUGH*/
4049     case RC_SORENDITION:
4050       i = 0;
4051       if (*args)
4052 	{
4053           i = ParseAttrColor(*args, args[1], 1);
4054 	  if (i == -1)
4055 	    break;
4056 	  ApplyAttrColor(i, &mchar_so);
4057 	  WindowChanged((struct win *)0, 0);
4058 	  debug2("--> %x %x\n", mchar_so.attr, mchar_so.color);
4059 	}
4060       if (msgok)
4061 #ifdef COLOR
4062         OutputMsg(0, "Standout attributes 0x%02x  color 0x%02x", (unsigned char)mchar_so.attr, 0x99 ^ (unsigned char)mchar_so.color);
4063 #else
4064         OutputMsg(0, "Standout attributes 0x%02x ", (unsigned char)mchar_so.attr);
4065 #endif
4066       break;
4067 
4068       case RC_SOURCE:
4069 	do_source(*args);
4070 	break;
4071 
4072 #ifdef MULTIUSER
4073     case RC_SU:
4074       s = NULL;
4075       if (!*args)
4076         {
4077 	  OutputMsg(0, "%s:%s screen login", HostName, SockPath);
4078           InputSu(D_fore, &D_user, NULL);
4079 	}
4080       else if (!args[1])
4081         InputSu(D_fore, &D_user, args[0]);
4082       else if (!args[2])
4083         s = DoSu(&D_user, args[0], args[1], "\377");
4084       else
4085         s = DoSu(&D_user, args[0], args[1], args[2]);
4086       if (s)
4087         OutputMsg(0, "%s", s);
4088       break;
4089 #endif /* MULTIUSER */
4090     case RC_SPLIT:
4091       s = args[0];
4092       if (s && !strcmp(s, "-v"))
4093         AddCanvas(SLICE_HORI);
4094       else
4095         AddCanvas(SLICE_VERT);
4096       Activate(-1);
4097       break;
4098     case RC_REMOVE:
4099       RemCanvas();
4100       Activate(-1);
4101       break;
4102     case RC_ONLY:
4103       OneCanvas();
4104       Activate(-1);
4105       break;
4106     case RC_FIT:
4107       D_forecv->c_xoff = D_forecv->c_xs;
4108       D_forecv->c_yoff = D_forecv->c_ys;
4109       RethinkViewportOffsets(D_forecv);
4110       ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, 0);
4111       flayer = D_forecv->c_layer;
4112       LaySetCursor();
4113       break;
4114     case RC_FOCUS:
4115       {
4116 	struct canvas *cv = 0;
4117 	if (!*args || !strcmp(*args, "next"))
4118 	  cv = D_forecv->c_next ? D_forecv->c_next : D_cvlist;
4119 	else if (!strcmp(*args, "prev"))
4120 	  {
4121 	    for (cv = D_cvlist; cv->c_next && cv->c_next != D_forecv; cv = cv->c_next)
4122 	      ;
4123 	  }
4124 	else if (!strcmp(*args, "top"))
4125 	  cv = D_cvlist;
4126 	else if (!strcmp(*args, "bottom"))
4127 	  {
4128 	    for (cv = D_cvlist; cv->c_next; cv = cv->c_next)
4129 	      ;
4130 	  }
4131 	else if (!strcmp(*args, "up"))
4132 	  cv = FindCanvas(D_forecv->c_xs, D_forecv->c_ys - 1);
4133 	else if (!strcmp(*args, "down"))
4134 	  cv = FindCanvas(D_forecv->c_xs, D_forecv->c_ye + 2);
4135 	else if (!strcmp(*args, "left"))
4136 	  cv = FindCanvas(D_forecv->c_xs - 1, D_forecv->c_ys);
4137 	else if (!strcmp(*args, "right"))
4138 	  cv = FindCanvas(D_forecv->c_xe + 1, D_forecv->c_ys);
4139 	else
4140 	  {
4141 	    OutputMsg(0, "%s: usage: focus [next|prev|up|down|left|right|top|bottom]", rc_name);
4142 	    break;
4143 	  }
4144 	SetForeCanvas(display, cv);
4145       }
4146       break;
4147     case RC_RESIZE:
4148       i = 0;
4149       if (D_forecv->c_slorient == SLICE_UNKN)
4150 	{
4151 	  OutputMsg(0, "resize: need more than one region");
4152 	  break;
4153 	}
4154       for (; *args; args++)
4155 	{
4156 	  if (!strcmp(*args, "-h"))
4157 	    i |= RESIZE_FLAG_H;
4158 	  else if (!strcmp(*args, "-v"))
4159 	    i |= RESIZE_FLAG_V;
4160 	  else if (!strcmp(*args, "-b"))
4161 	    i |= RESIZE_FLAG_H | RESIZE_FLAG_V;
4162 	  else if (!strcmp(*args, "-p"))
4163 	    i |= D_forecv->c_slorient == SLICE_VERT ? RESIZE_FLAG_H : RESIZE_FLAG_V;
4164 	  else if (!strcmp(*args, "-l"))
4165 	    i |= RESIZE_FLAG_L;
4166 	  else
4167 	    break;
4168 	}
4169       if (*args && args[1])
4170 	{
4171 	  OutputMsg(0, "%s: usage: resize [-h] [-v] [-l] [num]\n", rc_name);
4172 	  break;
4173 	}
4174       if (*args)
4175 	ResizeRegions(*args, i);
4176       else
4177 	Input(resizeprompts[i], 20, INP_EVERY, ResizeFin, (char*)0, i);
4178       break;
4179     case RC_SETSID:
4180       (void)ParseSwitch(act, &separate_sids);
4181       break;
4182     case RC_EVAL:
4183       args = SaveArgs(args);
4184       for (i = 0; args[i]; i++)
4185 	{
4186 	  if (args[i][0])
4187 	    Colonfin(args[i], strlen(args[i]), (char *)0);
4188 	  free(args[i]);
4189 	}
4190       free(args);
4191       break;
4192     case RC_ALTSCREEN:
4193       (void)ParseSwitch(act, &use_altscreen);
4194       if (msgok)
4195         OutputMsg(0, "Will %sdo alternate screen switching", use_altscreen ? "" : "not ");
4196       break;
4197     case RC_MAXWIN:
4198       if (!args[0])
4199 	{
4200 	  OutputMsg(0, "maximum windows allowed: %d", maxwin);
4201 	  break;
4202 	}
4203       if (ParseNum(act, &n))
4204 	break;
4205       if (n < 1)
4206         OutputMsg(0, "illegal maxwin number specified");
4207       else if (n > 2048)
4208 	OutputMsg(0, "maximum 2048 windows allowed");
4209       else if (n > maxwin && windows)
4210 	OutputMsg(0, "may increase maxwin only when there's no window");
4211       else
4212 	{
4213 	  if (!windows)
4214             {
4215 	      wtab = realloc(wtab, n * sizeof(struct win *));
4216               bzero(wtab, n * sizeof(struct win *));
4217             }
4218 	  maxwin = n;
4219 	}
4220       break;
4221     case RC_BACKTICK:
4222       if (ParseBase(act, *args, &n, 10, "decimal"))
4223 	break;
4224       if (!args[1])
4225         setbacktick(n, 0, 0, (char **)0);
4226       else
4227 	{
4228 	  int lifespan, tick;
4229 	  if (argc < 4)
4230 	    {
4231 	      OutputMsg(0, "%s: usage: backtick num [lifespan tick cmd args...]", rc_name);
4232 	      break;
4233 	    }
4234 	  if (ParseBase(act, args[1], &lifespan, 10, "decimal"))
4235 	    break;
4236 	  if (ParseBase(act, args[2], &tick, 10, "decimal"))
4237 	    break;
4238 	  setbacktick(n, lifespan, tick, SaveArgs(args + 3));
4239 	}
4240       WindowChanged(0, '`');
4241       break;
4242     case RC_BLANKER:
4243 #ifdef BLANKER_PRG
4244       if (blankerprg)
4245 	{
4246           RunBlanker(blankerprg);
4247 	  break;
4248 	}
4249 #endif
4250       ClearAll();
4251       CursorVisibility(-1);
4252       D_blocked = 4;
4253       break;
4254 #ifdef BLANKER_PRG
4255     case RC_BLANKERPRG:
4256       if (!args[0])
4257 	{
4258 	  if (blankerprg)
4259 	    {
4260 	      char path[MAXPATHLEN];
4261 	      char *p = path, **pp;
4262 	      for (pp = blankerprg; *pp; pp++)
4263 		p += snprintf(p, sizeof(path) - (p - path) - 1, "%s ", *pp);
4264 	      *(p - 1) = '\0';
4265 	      OutputMsg(0, "blankerprg: %s", path);
4266 	    }
4267 	  else
4268 	    OutputMsg(0, "No blankerprg set.");
4269 	  break;
4270 	}
4271       if (blankerprg)
4272 	{
4273 	  char **pp;
4274 	  for (pp = blankerprg; *pp; pp++)
4275 	    free(*pp);
4276 	  free(blankerprg);
4277 	  blankerprg = 0;
4278 	}
4279       if (args[0][0])
4280 	blankerprg = SaveArgs(args);
4281       break;
4282 #endif
4283     case RC_IDLE:
4284       if (*args)
4285 	{
4286 	  struct display *olddisplay = display;
4287 	  if (!strcmp(*args, "off"))
4288 	    idletimo = 0;
4289 	  else if (args[0][0])
4290 	    idletimo = atoi(*args) * 1000;
4291 	  if (argc > 1)
4292 	    {
4293 	      if ((i = FindCommnr(args[1])) == RC_ILLEGAL)
4294 		{
4295 		  OutputMsg(0, "%s: idle: unknown command '%s'", rc_name, args[1]);
4296 		  break;
4297 		}
4298 	      if (CheckArgNum(i, args + 2) < 0)
4299 		break;
4300 	      ClearAction(&idleaction);
4301 	      SaveAction(&idleaction, i, args + 2, argl + 2);
4302 	    }
4303 	  for (display = displays; display; display = display->d_next)
4304 	    ResetIdle();
4305 	  display = olddisplay;
4306 	}
4307       if (msgok)
4308 	{
4309 	  if (idletimo)
4310 	    OutputMsg(0, "idle timeout %ds, %s", idletimo / 1000, comms[idleaction.nr].name);
4311 	  else
4312 	    OutputMsg(0, "idle off");
4313 	}
4314       break;
4315     case RC_FOCUSMINSIZE:
4316       for (i = 0; i < 2 && args[i]; i++)
4317 	{
4318 	  if (!strcmp(args[i], "max") || !strcmp(args[i], "_"))
4319 	    n = -1;
4320 	  else
4321 	    n = atoi(args[i]);
4322 	  if (i == 0)
4323 	    focusminwidth = n;
4324 	  else
4325             focusminheight = n;
4326 	}
4327       if (msgok)
4328 	{
4329 	  char b[2][20];
4330 	  for (i = 0; i < 2; i++)
4331 	    {
4332 	      n = i == 0 ? focusminwidth : focusminheight;
4333 	      if (n == -1)
4334 		strcpy(b[i], "max");
4335 	      else
4336 		sprintf(b[i], "%d", n);
4337 	    }
4338           OutputMsg(0, "focus min size is %s %s\n", b[0], b[1]);
4339 	}
4340       break;
4341     case RC_GROUP:
4342       if (*args)
4343 	{
4344 	  fore->w_group = 0;
4345 	  if (args[0][0])
4346 	    {
4347 	      fore->w_group = WindowByName(*args);
4348 	      if (fore->w_group == fore || (fore->w_group && fore->w_group->w_type != W_TYPE_GROUP))
4349 		fore->w_group = 0;
4350 	    }
4351 	  WindowChanged((struct win *)0, 'w');
4352 	  WindowChanged((struct win *)0, 'W');
4353 	  WindowChanged((struct win *)0, 0);
4354 	}
4355       if (msgok)
4356 	{
4357 	  if (fore->w_group)
4358 	    OutputMsg(0, "window group is %d (%s)\n", fore->w_group->w_number, fore->w_group->w_title);
4359 	  else
4360 	    OutputMsg(0, "window belongs to no group");
4361 	}
4362       break;
4363     case RC_LAYOUT:
4364       // A number of the subcommands for "layout" are ignored, or not processed correctly when there
4365       // is no attached display.
4366 
4367       if (!strcmp(args[0], "title"))
4368 	{
4369           if (!display)
4370             {
4371 	      if (!args[1])  // There is no display, and there is no new title. Ignore.
4372 		break;
4373 	      if (!layout_attach || layout_attach == &layout_last_marker)
4374 		layout_attach = CreateLayout(args[1], 0);
4375 	      else
4376 		RenameLayout(layout_attach, args[1]);
4377 	      break;
4378 	    }
4379 
4380 	  if (!D_layout)
4381 	    {
4382 	      OutputMsg(0, "not on a layout");
4383 	      break;
4384 	    }
4385 	  if (!args[1])
4386 	    {
4387 	      OutputMsg(0, "current layout is %d (%s)", D_layout->lay_number, D_layout->lay_title);
4388 	      break;
4389 	    }
4390 	  RenameLayout(D_layout, args[1]);
4391 	}
4392       else if (!strcmp(args[0], "number"))
4393 	{
4394 	  if (!display)
4395 	    {
4396 	      if (args[1] && layout_attach && layout_attach != &layout_last_marker)
4397 		RenumberLayout(layout_attach, atoi(args[1]));
4398 	      break;
4399 	    }
4400 
4401 	  if (!D_layout)
4402 	    {
4403 	      OutputMsg(0, "not on a layout");
4404 	      break;
4405 	    }
4406 	  if (!args[1])
4407 	    {
4408 	      OutputMsg(0, "This is layout %d (%s).\n", D_layout->lay_number, D_layout->lay_title);
4409 	      break;
4410 	    }
4411 	   RenumberLayout(D_layout, atoi(args[1]));
4412 	   break;
4413 	}
4414       else if (!strcmp(args[0], "autosave"))
4415 	{
4416 	  if (!display)
4417 	    {
4418 	      if (args[1] && layout_attach && layout_attach != &layout_last_marker)
4419 		{
4420 		  if (!strcmp(args[1], "on"))
4421 		    layout_attach->lay_autosave = 1;
4422 		  else if (!strcmp(args[1], "off"))
4423 		    layout_attach->lay_autosave = 0;
4424 		}
4425 	      break;
4426 	    }
4427 
4428 	  if (!D_layout)
4429 	    {
4430 	      OutputMsg(0, "not on a layout");
4431 	      break;
4432 	    }
4433 	  if (args[1])
4434 	    {
4435 	      if (!strcmp(args[1], "on"))
4436 		D_layout->lay_autosave = 1;
4437 	      else if (!strcmp(args[1], "off"))
4438 		D_layout->lay_autosave = 0;
4439 	      else
4440 		{
4441 		  OutputMsg(0, "invalid argument. Give 'on' or 'off");
4442 		  break;
4443 		}
4444 	    }
4445 	  if (msgok)
4446 	    OutputMsg(0, "autosave is %s", D_layout->lay_autosave ? "on" : "off");
4447 	}
4448       else if (!strcmp(args[0], "new"))
4449 	{
4450 	  char *t = args[1];
4451 	  n = 0;
4452 	  if (t)
4453 	    {
4454 	      while (*t >= '0' && *t <= '9')
4455 		t++;
4456 	      if (t != args[1] && (!*t || *t == ':'))
4457 		{
4458 		  n = atoi(args[1]);
4459 		  if (*t)
4460 		    t++;
4461 		}
4462 	      else
4463 		t = args[1];
4464 	    }
4465 	  if (!t || !*t)
4466 	    t = "layout";
4467           NewLayout(t, n);
4468 	  Activate(-1);
4469 	}
4470       else if (!strcmp(args[0], "save"))
4471 	{
4472 	  if (!args[1])
4473 	    {
4474 	      OutputMsg(0, "usage: layout save <name>");
4475 	      break;
4476 	    }
4477 	  if (display)
4478 	    SaveLayout(args[1], &D_canvas);
4479 	}
4480       else if (!strcmp(args[0], "select"))
4481 	{
4482 	  if (!display)
4483 	    {
4484 	      if (args[1])
4485 		layout_attach = FindLayout(args[1]);
4486 	      break;
4487 	    }
4488           if (!args[1])
4489 	    {
4490 	      Input("Switch to layout: ", 20, INP_COOKED, SelectLayoutFin, NULL, 0);
4491 	      break;
4492 	    }
4493 	  SelectLayoutFin(args[1], strlen(args[1]), (char *)0);
4494 	}
4495       else if (!strcmp(args[0], "next"))
4496 	{
4497 	  if (!display)
4498 	    {
4499 	      if (layout_attach && layout_attach != &layout_last_marker)
4500 		layout_attach = layout_attach->lay_next ? layout_attach->lay_next : layouts;;
4501 	      break;
4502 	    }
4503 	  struct layout *lay = D_layout;
4504 	  if (lay)
4505 	    lay = lay->lay_next ? lay->lay_next : layouts;
4506 	  else
4507 	    lay = layouts;
4508 	  if (!lay)
4509 	    {
4510 	      OutputMsg(0, "no layout defined");
4511 	      break;
4512 	    }
4513 	  if (lay == D_layout)
4514 	    break;
4515 	  LoadLayout(lay, &D_canvas);
4516 	  Activate(-1);
4517 	}
4518       else if (!strcmp(args[0], "prev"))
4519 	{
4520 	  struct layout *lay = display ? D_layout : layout_attach;
4521 	  struct layout *target = lay;
4522 	  if (lay)
4523 	    {
4524 	      for (lay = layouts; lay->lay_next && lay->lay_next != target; lay = lay->lay_next)
4525 		;
4526 	    }
4527 	  else
4528 	    lay = layouts;
4529 
4530 	  if (!display)
4531 	    {
4532 	      layout_attach = lay;
4533 	      break;
4534 	    }
4535 
4536 	  if (!lay)
4537 	    {
4538 	      OutputMsg(0, "no layout defined");
4539 	      break;
4540 	    }
4541 	  if (lay == D_layout)
4542 	    break;
4543 	  LoadLayout(lay, &D_canvas);
4544 	  Activate(-1);
4545 	}
4546       else if (!strcmp(args[0], "attach"))
4547 	{
4548 	  if (!args[1])
4549 	    {
4550 	      if (!layout_attach)
4551 	        OutputMsg(0, "no attach layout set");
4552 	      else if (layout_attach == &layout_last_marker)
4553 	        OutputMsg(0, "will attach to last layout");
4554 	      else
4555 	        OutputMsg(0, "will attach to layout %d (%s)", layout_attach->lay_number, layout_attach->lay_title);
4556 	      break;
4557 	    }
4558 	  if (!strcmp(args[1], ":last"))
4559 	    layout_attach = &layout_last_marker;
4560 	  else if (!args[1][0])
4561 	    layout_attach = 0;
4562 	  else
4563 	    {
4564 	      struct layout *lay;
4565 	      lay = FindLayout(args[1]);
4566 	      if (!lay)
4567 		{
4568 		  OutputMsg(0, "unknown layout '%s'", args[1]);
4569 		  break;
4570 		}
4571 	      layout_attach = lay;
4572 	    }
4573 	}
4574       else if (!strcmp(args[0], "show"))
4575 	{
4576 	  ShowLayouts(-1);
4577 	}
4578       else if (!strcmp(args[0], "remove"))
4579 	{
4580 	  struct layout *lay = display ? D_layout : layouts;
4581 	  if (args[1])
4582 	    {
4583 	      lay = layouts ? FindLayout(args[1]) : (struct layout *)0;
4584 	      if (!lay)
4585 		{
4586 		  OutputMsg(0, "unknown layout '%s'", args[1]);
4587 		  break;
4588 		}
4589 	    }
4590 	  if (lay)
4591 	    RemoveLayout(lay);
4592 	}
4593       else if (!strcmp(args[0], "dump"))
4594 	{
4595 	  if (!display)
4596 	    OutputMsg(0, "Must have a display for 'layout dump'.");
4597 	  else if (!LayoutDumpCanvas(&D_canvas, args[1] ? args[1] : "layout-dump"))
4598 	    OutputMsg(errno, "Error dumping layout.");
4599 	  else
4600 	    OutputMsg(0, "Layout dumped to \"%s\"", args[1] ? args[1] : "layout-dump");
4601 	}
4602       else
4603 	OutputMsg(0, "unknown layout subcommand");
4604       break;
4605 #ifdef DW_CHARS
4606     case RC_CJKWIDTH:
4607       if(ParseSwitch(act, &cjkwidth) == 0)
4608       {
4609         if(msgok)
4610           OutputMsg(0, "Treat ambiguous width characters as %s width", cjkwidth ? "full" : "half");
4611       }
4612       break;
4613 #endif
4614     default:
4615 #ifdef HAVE_BRAILLE
4616       /* key == -2: input from braille keybord, msgok always 0 */
4617       DoBrailleAction(act, key == -2 ? 0 : msgok);
4618 #endif
4619       break;
4620     }
4621   if (display != odisplay)
4622     {
4623       for (display = displays; display; display = display->d_next)
4624         if (display == odisplay)
4625 	  break;
4626     }
4627 }
4628 #undef OutputMsg
4629 
4630 void
CollapseWindowlist()4631 CollapseWindowlist()
4632 /* renumber windows from 0, leaving no gaps */
4633 {
4634   int pos, moveto=0;
4635 
4636   for (pos = 1; pos < MAXWIN; pos++)
4637     if (wtab[pos])
4638       for (; moveto < pos; moveto++)
4639         if (!wtab[moveto])
4640           {
4641           WindowChangeNumber(pos, moveto);
4642           break;
4643           }
4644 }
4645 
4646 void
DoCommand(argv,argl)4647 DoCommand(argv, argl)
4648 char **argv;
4649 int *argl;
4650 {
4651   struct action act;
4652   const char *cmd = *argv;
4653 
4654   act.quiet = 0;
4655   /* For now, we actually treat both 'supress error' and 'suppress normal message' as the
4656    * same, and ignore all messages on either flag. If we wanted to do otherwise, we would
4657    * need to change the definition of 'OutputMsg' slightly. */
4658   if (*cmd == '@')	/* Suppress error */
4659     {
4660       act.quiet |= 0x01;
4661       cmd++;
4662     }
4663   if (*cmd == '-')	/* Suppress normal message */
4664     {
4665       act.quiet |= 0x02;
4666       cmd++;
4667     }
4668 
4669   if ((act.nr = FindCommnr(cmd)) == RC_ILLEGAL)
4670     {
4671       Msg(0, "%s: unknown command '%s'", rc_name, cmd);
4672       return;
4673     }
4674   act.args = argv + 1;
4675   act.argl = argl + 1;
4676   DoAction(&act, -1);
4677 }
4678 
4679 static void
SaveAction(act,nr,args,argl)4680 SaveAction(act, nr, args, argl)
4681 struct action *act;
4682 int nr;
4683 char **args;
4684 int *argl;
4685 {
4686   register int argc = 0;
4687   char **pp;
4688   int *lp;
4689 
4690   if (args)
4691     while (args[argc])
4692       argc++;
4693   if (argc == 0)
4694     {
4695       act->nr = nr;
4696       act->args = noargs;
4697       act->argl = 0;
4698       return;
4699     }
4700   if ((pp = (char **)malloc((unsigned)(argc + 1) * sizeof(char *))) == 0)
4701     Panic(0, "%s", strnomem);
4702   if ((lp = (int *)malloc((unsigned)(argc) * sizeof(int))) == 0)
4703     Panic(0, "%s", strnomem);
4704   act->nr = nr;
4705   act->args = pp;
4706   act->argl = lp;
4707   while (argc--)
4708     {
4709       *lp = argl ? *argl++ : (int)strlen(*args);
4710       *pp++ = SaveStrn(*args++, *lp++);
4711     }
4712   *pp = 0;
4713 }
4714 
4715 static char **
SaveArgs(args)4716 SaveArgs(args)
4717 char **args;
4718 {
4719   register char **ap, **pp;
4720   register int argc = 0;
4721 
4722   while (args[argc])
4723     argc++;
4724   if ((pp = ap = (char **)malloc((unsigned)(argc + 1) * sizeof(char **))) == 0)
4725     Panic(0, "%s", strnomem);
4726   while (argc--)
4727     *pp++ = SaveStr(*args++);
4728   *pp = 0;
4729   return ap;
4730 }
4731 
4732 
4733 /*
4734  * buf is split into argument vector args.
4735  * leading whitespace is removed.
4736  * @!| abbreviations are expanded.
4737  * the end of buffer is recognized by '\0' or an un-escaped '#'.
4738  * " and ' are interpreted.
4739  *
4740  * argc is returned.
4741  */
4742 int
Parse(buf,bufl,args,argl)4743 Parse(buf, bufl, args, argl)
4744 char *buf, **args;
4745 int bufl, *argl;
4746 {
4747   register char *p = buf, **ap = args, *pp;
4748   register int delim, argc;
4749   int *lp = argl;
4750 
4751   debug2("Parse %d %s\n", bufl, buf);
4752   argc = 0;
4753   pp = buf;
4754   delim = 0;
4755   for (;;)
4756     {
4757       *lp = 0;
4758       while (*p && (*p == ' ' || *p == '\t'))
4759 	++p;
4760 #ifdef PSEUDOS
4761       if (argc == 0 && *p == '!')
4762 	{
4763 	  *ap++ = "exec";
4764 	  *lp++ = 4;
4765 	  p++;
4766 	  argc++;
4767 	  continue;
4768         }
4769 #endif
4770       if (*p == '\0' || *p == '#' || *p == '\n')
4771 	{
4772 	  *p = '\0';
4773 	  for (delim = 0; delim < argc; delim++)
4774 	    debug1("-- %s\n", args[delim]);
4775 	  args[argc] = 0;
4776 	  return argc;
4777 	}
4778       if (++argc >= MAXARGS)
4779 	{
4780 	  Msg(0, "%s: too many tokens.", rc_name);
4781 	  return 0;
4782 	}
4783       *ap++ = pp;
4784 
4785       debug1("- new arg %s\n", p);
4786       while (*p)
4787 	{
4788 	  if (*p == delim)
4789 	    delim = 0;
4790 	  else if (delim != '\'' && *p == '\\' && (p[1] == 'n' || p[1] == 'r' || p[1] == 't' || p[1] == '\'' || p[1] == '"' || p[1] == '\\' || p[1] == '$' || p[1] == '#' || p[1] == '^' || (p[1] >= '0' && p[1] <= '7')))
4791 	    {
4792 	      p++;
4793 	      if (*p >= '0' && *p <= '7')
4794 		{
4795 		  *pp = *p - '0';
4796 		  if (p[1] >= '0' && p[1] <= '7')
4797 		    {
4798 		      p++;
4799 		      *pp = (*pp << 3) | (*p - '0');
4800 		      if (p[1] >= '0' && p[1] <= '7')
4801 			{
4802 			  p++;
4803 			  *pp = (*pp << 3) | (*p - '0');
4804 			}
4805 		    }
4806 		  pp++;
4807 		}
4808 	      else
4809 		{
4810 		  switch (*p)
4811 		    {
4812 		      case 'n': *pp = '\n'; break;
4813 		      case 'r': *pp = '\r'; break;
4814 		      case 't': *pp = '\t'; break;
4815 		      default: *pp = *p; break;
4816 		    }
4817 		  pp++;
4818 		}
4819 	    }
4820 	  else if (delim != '\'' && *p == '$' && (p[1] == '{' || p[1] == ':' || (p[1] >= 'a' && p[1] <= 'z') || (p[1] >= 'A' && p[1] <= 'Z') || (p[1] >= '0' && p[1] <= '9') || p[1] == '_'))
4821 
4822 	    {
4823 	      char *ps, *pe, op, *v, xbuf[11], path[MAXPATHLEN];
4824 	      int vl;
4825 
4826 	      ps = ++p;
4827 	      debug1("- var %s\n", ps);
4828 	      p++;
4829 	      while (*p)
4830 		{
4831 		  if (*ps == '{' && *p == '}')
4832 		    break;
4833 		  if (*ps == ':' && *p == ':')
4834 		    break;
4835 		  if (*ps != '{' && *ps != ':' && (*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z') && (*p < '0' || *p > '9') && *p != '_')
4836 		    break;
4837 		  p++;
4838 		}
4839 	      pe = p;
4840 	      if (*ps == '{' || *ps == ':')
4841 		{
4842 		  if (!*p)
4843 		    {
4844 		      Msg(0, "%s: bad variable name.", rc_name);
4845 		      return 0;
4846 		    }
4847 		  p++;
4848 		}
4849 	      op = *pe;
4850 	      *pe = 0;
4851 	      debug1("- var is '%s'\n", ps);
4852 	      if (*ps == ':')
4853 		v = gettermcapstring(ps + 1);
4854 	      else
4855 		{
4856 		  if (*ps == '{')
4857 		    ps++;
4858 		  v = xbuf;
4859 		  if (!strcmp(ps, "TERM"))
4860 		    v = display ? D_termname : "unknown";
4861 		  else if (!strcmp(ps, "COLUMNS"))
4862 		    sprintf(xbuf, "%d", display ? D_width : -1);
4863 		  else if (!strcmp(ps, "LINES"))
4864 		    sprintf(xbuf, "%d", display ? D_height : -1);
4865 		  else if (!strcmp(ps, "PID"))
4866 		    sprintf(xbuf, "%d", getpid());
4867 		  else if (!strcmp(ps, "PWD"))
4868 		    {
4869 		      if (getcwd(path, sizeof(path) - 1) == 0)
4870 			v = "?";
4871 		      else
4872 			v = path;
4873 		    }
4874 		  else if (!strcmp(ps, "STY"))
4875 		    {
4876 		      if ((v = strchr(SockName, '.')))	/* Skip the PID */
4877 			v++;
4878 		      else
4879 			v = SockName;
4880 		    }
4881 		  else
4882 		    v = getenv(ps);
4883 		}
4884 	      *pe = op;
4885 	      vl = v ? strlen(v) : 0;
4886 	      if (vl)
4887 		{
4888 		  debug1("- sub is '%s'\n", v);
4889 		  if (p - pp < vl)
4890 		    {
4891 		      int right = buf + bufl - (p + strlen(p) + 1);
4892 		      if (right > 0)
4893 			{
4894 			  bcopy(p, p + right, strlen(p) + 1);
4895 			  p += right;
4896 			}
4897 		    }
4898 		  if (p - pp < vl)
4899 		    {
4900 		      Msg(0, "%s: no space left for variable expansion.", rc_name);
4901 		      return 0;
4902 		    }
4903 		  bcopy(v, pp, vl);
4904 		  pp += vl;
4905 		}
4906 	      continue;
4907 	    }
4908 	  else if (delim != '\'' && *p == '^' && p[1])
4909 	    {
4910 	      p++;
4911 	      *pp++ = *p == '?' ? '\177' : *p & 0x1f;
4912 	    }
4913 	  else if (delim == 0 && (*p == '\'' || *p == '"'))
4914 	    delim = *p;
4915 	  else if (delim == 0 && (*p == ' ' || *p == '\t' || *p == '\n'))
4916 	    break;
4917 	  else
4918 	    *pp++ = *p;
4919 	  p++;
4920 	}
4921       if (delim)
4922 	{
4923 	  Msg(0, "%s: Missing %c quote.", rc_name, delim);
4924 	  return 0;
4925 	}
4926       if (*p)
4927 	p++;
4928       *pp = 0;
4929       debug2("- arg done, '%s' rest %s\n", ap[-1], p);
4930       *lp++ = pp - ap[-1];
4931       pp++;
4932     }
4933 }
4934 
4935 void
SetEscape(u,e,me)4936 SetEscape(u, e, me)
4937 struct acluser *u;
4938 int e, me;
4939 {
4940   if (u)
4941     {
4942       u->u_Esc = e;
4943       u->u_MetaEsc = me;
4944     }
4945   else
4946     {
4947       if (users)
4948 	{
4949 	  if (DefaultEsc >= 0)
4950 	    ClearAction(&ktab[DefaultEsc]);
4951 	  if (DefaultMetaEsc >= 0)
4952 	    ClearAction(&ktab[DefaultMetaEsc]);
4953 	}
4954       DefaultEsc = e;
4955       DefaultMetaEsc = me;
4956       if (users)
4957 	{
4958 	  if (DefaultEsc >= 0)
4959 	    {
4960 	      ClearAction(&ktab[DefaultEsc]);
4961 	      ktab[DefaultEsc].nr = RC_OTHER;
4962 	    }
4963 	  if (DefaultMetaEsc >= 0)
4964 	    {
4965 	      ClearAction(&ktab[DefaultMetaEsc]);
4966 	      ktab[DefaultMetaEsc].nr = RC_META;
4967 	    }
4968 	}
4969     }
4970 }
4971 
4972 int
ParseSwitch(act,var)4973 ParseSwitch(act, var)
4974 struct action *act;
4975 int *var;
4976 {
4977   if (*act->args == 0)
4978     {
4979       *var ^= 1;
4980       return 0;
4981     }
4982   return ParseOnOff(act, var);
4983 }
4984 
4985 static int
ParseOnOff(act,var)4986 ParseOnOff(act, var)
4987 struct action *act;
4988 int *var;
4989 {
4990   register int num = -1;
4991   char **args = act->args;
4992 
4993   if (args[1] == 0)
4994     {
4995       if (strcmp(args[0], "on") == 0)
4996 	num = 1;
4997       else if (strcmp(args[0], "off") == 0)
4998 	num = 0;
4999     }
5000   if (num < 0)
5001     {
5002       Msg(0, "%s: %s: invalid argument. Give 'on' or 'off'", rc_name, comms[act->nr].name);
5003       return -1;
5004     }
5005   *var = num;
5006   return 0;
5007 }
5008 
5009 int
ParseSaveStr(act,var)5010 ParseSaveStr(act, var)
5011 struct action *act;
5012 char **var;
5013 {
5014   char **args = act->args;
5015   if (*args == 0 || args[1])
5016     {
5017       Msg(0, "%s: %s: one argument required.", rc_name, comms[act->nr].name);
5018       return -1;
5019     }
5020   if (*var)
5021     free(*var);
5022   *var = SaveStr(*args);
5023   return 0;
5024 }
5025 
5026 int
ParseNum(act,var)5027 ParseNum(act, var)
5028 struct action *act;
5029 int *var;
5030 {
5031   int i;
5032   char *p, **args = act->args;
5033 
5034   p = *args;
5035   if (p == 0 || *p == 0 || args[1])
5036     {
5037       Msg(0, "%s: %s: invalid argument. Give one argument.",
5038           rc_name, comms[act->nr].name);
5039       return -1;
5040     }
5041   i = 0;
5042   while (*p)
5043     {
5044       if (*p >= '0' && *p <= '9')
5045 	i = 10 * i + (*p - '0');
5046       else
5047 	{
5048 	  Msg(0, "%s: %s: invalid argument. Give numeric argument.",
5049 	      rc_name, comms[act->nr].name);
5050 	  return -1;
5051 	}
5052       p++;
5053     }
5054   debug1("ParseNum got %d\n", i);
5055   *var = i;
5056   return 0;
5057 }
5058 
5059 static int
ParseNum1000(act,var)5060 ParseNum1000(act, var)
5061 struct action *act;
5062 int *var;
5063 {
5064   int i;
5065   char *p, **args = act->args;
5066   int dig = 0;
5067 
5068   p = *args;
5069   if (p == 0 || *p == 0 || args[1])
5070     {
5071       Msg(0, "%s: %s: invalid argument. Give one argument.",
5072           rc_name, comms[act->nr].name);
5073       return -1;
5074     }
5075   i = 0;
5076   while (*p)
5077     {
5078       if (*p >= '0' && *p <= '9')
5079 	{
5080 	  if (dig < 4)
5081 	    i = 10 * i + (*p - '0');
5082           else if (dig == 4 && *p >= '5')
5083 	    i++;
5084 	  if (dig)
5085 	    dig++;
5086 	}
5087       else if (*p == '.' && !dig)
5088         dig++;
5089       else
5090 	{
5091 	  Msg(0, "%s: %s: invalid argument. Give floating point argument.",
5092 	      rc_name, comms[act->nr].name);
5093 	  return -1;
5094 	}
5095       p++;
5096     }
5097   if (dig == 0)
5098     i *= 1000;
5099   else
5100     while (dig++ < 4)
5101       i *= 10;
5102   if (i < 0)
5103     i = (int)((unsigned int)~0 >> 1);
5104   debug1("ParseNum1000 got %d\n", i);
5105   *var = i;
5106   return 0;
5107 }
5108 
5109 static struct win *
WindowByName(s)5110 WindowByName(s)
5111 char *s;
5112 {
5113   struct win *p;
5114 
5115   for (p = windows; p; p = p->w_next)
5116     if (!strcmp(p->w_title, s))
5117       return p;
5118   for (p = windows; p; p = p->w_next)
5119     if (!strncmp(p->w_title, s, strlen(s)))
5120       return p;
5121   return 0;
5122 }
5123 
5124 static int
WindowByNumber(str)5125 WindowByNumber(str)
5126 char *str;
5127 {
5128   int i;
5129   char *s;
5130 
5131   for (i = 0, s = str; *s; s++)
5132     {
5133       if (*s < '0' || *s > '9')
5134         break;
5135       i = i * 10 + (*s - '0');
5136     }
5137   return *s ? -1 : i;
5138 }
5139 
5140 /*
5141  * Get window number from Name or Number string.
5142  * Numbers are tried first, then names, a prefix match suffices.
5143  * Be careful when assigning numeric strings as WindowTitles.
5144  */
5145 int
WindowByNoN(str)5146 WindowByNoN(str)
5147 char *str;
5148 {
5149   int i;
5150   struct win *p;
5151 
5152   if ((i = WindowByNumber(str)) < 0 || i >= maxwin)
5153     {
5154       if ((p = WindowByName(str)))
5155 	return p->w_number;
5156       return -1;
5157     }
5158   return i;
5159 }
5160 
5161 static int
ParseWinNum(act,var)5162 ParseWinNum(act, var)
5163 struct action *act;
5164 int *var;
5165 {
5166   char **args = act->args;
5167   int i = 0;
5168 
5169   if (*args == 0 || args[1])
5170     {
5171       Msg(0, "%s: %s: one argument required.", rc_name, comms[act->nr].name);
5172       return -1;
5173     }
5174 
5175   i = WindowByNoN(*args);
5176   if (i < 0)
5177     {
5178       Msg(0, "%s: %s: invalid argument. Give window number or name.",
5179           rc_name, comms[act->nr].name);
5180       return -1;
5181     }
5182   debug1("ParseWinNum got %d\n", i);
5183   *var = i;
5184   return 0;
5185 }
5186 
5187 static int
ParseBase(act,p,var,base,bname)5188 ParseBase(act, p, var, base, bname)
5189 struct action *act;
5190 char *p;
5191 int *var;
5192 int base;
5193 char *bname;
5194 {
5195   int i = 0;
5196   int c;
5197 
5198   if (*p == 0)
5199     {
5200       Msg(0, "%s: %s: empty argument.", rc_name, comms[act->nr].name);
5201       return -1;
5202     }
5203   while ((c = *p++))
5204     {
5205       if (c >= 'a' && c <= 'z')
5206 	c -= 'a' - 'A';
5207       if (c >= 'A' && c <= 'Z')
5208 	c -= 'A' - ('0' + 10);
5209       c -= '0';
5210       if (c < 0 || c >= base)
5211 	{
5212 	  Msg(0, "%s: %s: argument is not %s.", rc_name, comms[act->nr].name, bname);
5213 	  return -1;
5214 	}
5215       i = base * i + c;
5216     }
5217   debug1("ParseBase got %d\n", i);
5218   *var = i;
5219   return 0;
5220 }
5221 
5222 static int
IsNum(s,base)5223 IsNum(s, base)
5224 register char *s;
5225 register int base;
5226 {
5227   for (base += '0'; *s; ++s)
5228     if (*s < '0' || *s > base)
5229       return 0;
5230   return 1;
5231 }
5232 
5233 int
IsNumColon(s,base,p,psize)5234 IsNumColon(s, base, p, psize)
5235 int base, psize;
5236 char *s, *p;
5237 {
5238   char *q;
5239   if ((q = rindex(s, ':')) != 0)
5240     {
5241       strncpy(p, q + 1, psize - 1);
5242       p[psize - 1] = '\0';
5243       *q = '\0';
5244     }
5245   else
5246     *p = '\0';
5247   return IsNum(s, base);
5248 }
5249 
5250 void
SwitchWindow(n)5251 SwitchWindow(n)
5252 int n;
5253 {
5254   struct win *p;
5255 
5256   debug1("SwitchWindow %d\n", n);
5257   if (n < 0 || n >= maxwin)
5258     {
5259       ShowWindows(-1);
5260       return;
5261     }
5262   if ((p = wtab[n]) == 0)
5263     {
5264       ShowWindows(n);
5265       return;
5266     }
5267   if (display == 0)
5268     {
5269       fore = p;
5270       return;
5271     }
5272   if (p == D_fore)
5273     {
5274       Msg(0, "This IS window %d (%s).", n, p->w_title);
5275       return;
5276     }
5277 #ifdef MULTIUSER
5278   if (AclCheckPermWin(D_user, ACL_READ, p))
5279     {
5280       Msg(0, "Access to window %d denied.", p->w_number);
5281       return;
5282     }
5283 #endif
5284   SetForeWindow(p);
5285   Activate(fore->w_norefresh);
5286 }
5287 
5288 /*
5289  * SetForeWindow changes the window in the input focus of the display.
5290  * Puts window wi in canvas display->d_forecv.
5291  */
5292 void
SetForeWindow(wi)5293 SetForeWindow(wi)
5294 struct win *wi;
5295 {
5296   struct win *p;
5297   if (display == 0)
5298     {
5299       fore = wi;
5300       return;
5301     }
5302   p = Layer2Window(D_forecv->c_layer);
5303   SetCanvasWindow(D_forecv, wi);
5304   if (p)
5305     WindowChanged(p, 'u');
5306   if (wi)
5307     WindowChanged(wi, 'u');
5308   flayer = D_forecv->c_layer;
5309   /* Activate called afterwards, so no RefreshHStatus needed */
5310 }
5311 
5312 
5313 /*****************************************************************/
5314 
5315 /*
5316  *  Activate - make fore window active
5317  *  norefresh = -1 forces a refresh, disregard all_norefresh then.
5318  */
5319 void
Activate(norefresh)5320 Activate(norefresh)
5321 int norefresh;
5322 {
5323   debug1("Activate(%d)\n", norefresh);
5324   if (display == 0)
5325     return;
5326   if (D_status)
5327     {
5328       Msg(0, "%s", "");	/* wait till mintime (keep gcc quiet) */
5329       RemoveStatus();
5330     }
5331 
5332   if (MayResizeLayer(D_forecv->c_layer))
5333     ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, display);
5334 
5335   fore = D_fore;
5336   if (fore)
5337     {
5338       /* XXX ? */
5339       if (fore->w_monitor != MON_OFF)
5340 	fore->w_monitor = MON_ON;
5341       fore->w_bell = BELL_ON;
5342       WindowChanged(fore, 'f');
5343 
5344 #if 0
5345       if (ResizeDisplay(fore->w_width, fore->w_height))
5346 	{
5347 	  debug2("Cannot resize from (%d,%d)", D_width, D_height);
5348 	  debug2(" to (%d,%d) -> resize window\n", fore->w_width, fore->w_height);
5349 	  DoResize(D_width, D_height);
5350 	}
5351 #endif
5352     }
5353   Redisplay(norefresh + all_norefresh);
5354 }
5355 
5356 
5357 static int
NextWindow()5358 NextWindow()
5359 {
5360   register struct win **pp;
5361   int n = fore ? fore->w_number : maxwin;
5362   struct win *group = fore ? fore->w_group : 0;
5363 
5364   for (pp = fore ? wtab + n + 1 : wtab; pp != wtab + n; pp++)
5365     {
5366       if (pp == wtab + maxwin)
5367 	pp = wtab;
5368       if (*pp)
5369 	{
5370 	  if (!fore || group == (*pp)->w_group)
5371 	    break;
5372 	}
5373     }
5374   if (pp == wtab + n)
5375     return -1;
5376   return pp - wtab;
5377 }
5378 
5379 static int
PreviousWindow()5380 PreviousWindow()
5381 {
5382   register struct win **pp;
5383   int n = fore ? fore->w_number : -1;
5384   struct win *group = fore ? fore->w_group : 0;
5385 
5386   for (pp = wtab + n - 1; pp != wtab + n; pp--)
5387     {
5388       if (pp == wtab - 1)
5389 	pp = wtab + maxwin - 1;
5390       if (*pp)
5391 	{
5392 	  if (!fore || group == (*pp)->w_group)
5393 	    break;
5394 	}
5395     }
5396   if (pp == wtab + n)
5397     return -1;
5398   return pp - wtab;
5399 }
5400 
5401 static int
MoreWindows()5402 MoreWindows()
5403 {
5404   char *m = "No other window.";
5405   if (windows && (fore == 0 || windows->w_next))
5406     return 1;
5407   if (fore == 0)
5408     {
5409       Msg(0, "No window available");
5410       return 0;
5411     }
5412   Msg(0, m, fore->w_number);	/* other arg for nethack */
5413   return 0;
5414 }
5415 
5416 void
KillWindow(wi)5417 KillWindow(wi)
5418 struct win *wi;
5419 {
5420   struct win **pp, *p;
5421   struct canvas *cv;
5422   int gotone;
5423   struct layout *lay;
5424 
5425   /*
5426    * Remove window from linked list.
5427    */
5428   for (pp = &windows; (p = *pp); pp = &p->w_next)
5429     if (p == wi)
5430       break;
5431   ASSERT(p);
5432   *pp = p->w_next;
5433   wi->w_inlen = 0;
5434   wtab[wi->w_number] = 0;
5435 
5436   if (windows == 0)
5437     {
5438       FreeWindow(wi);
5439       Finit(0);
5440     }
5441 
5442   /*
5443    * switch to different window on all canvases
5444    */
5445   for (display = displays; display; display = display->d_next)
5446     {
5447       gotone = 0;
5448       for (cv = D_cvlist; cv; cv = cv->c_next)
5449 	{
5450 	  if (Layer2Window(cv->c_layer) != wi)
5451 	    continue;
5452 	  /* switch to other window */
5453 	  SetCanvasWindow(cv, FindNiceWindow(D_other, 0));
5454 	  gotone = 1;
5455 	}
5456       if (gotone)
5457 	{
5458 #ifdef ZMODEM
5459 	  if (wi->w_zdisplay == display)
5460 	    {
5461 	      D_blocked = 0;
5462 	      D_readev.condpos = D_readev.condneg = 0;
5463 	    }
5464 #endif
5465 	  Activate(-1);
5466 	}
5467     }
5468 
5469   /* do the same for the layouts */
5470   for (lay = layouts; lay; lay = lay->lay_next)
5471     UpdateLayoutCanvas(&lay->lay_canvas, wi);
5472 
5473   FreeWindow(wi);
5474   WindowChanged((struct win *)0, 'w');
5475   WindowChanged((struct win *)0, 'W');
5476   WindowChanged((struct win *)0, 0);
5477 }
5478 
5479 static void
LogToggle(on)5480 LogToggle(on)
5481 int on;
5482 {
5483   char buf[1024];
5484 
5485   if ((fore->w_log != 0) == on)
5486     {
5487       if (display && !*rc_name)
5488 	Msg(0, "You are %s logging.", on ? "already" : "not");
5489       return;
5490     }
5491   if (fore->w_log != 0)
5492     {
5493       Msg(0, "Logfile \"%s\" closed.", fore->w_log->name);
5494       logfclose(fore->w_log);
5495       fore->w_log = 0;
5496       WindowChanged(fore, 'f');
5497       return;
5498     }
5499   if (DoStartLog(fore, buf, sizeof(buf)))
5500     {
5501       Msg(errno, "Error opening logfile \"%s\"", buf);
5502       return;
5503     }
5504   if (ftell(fore->w_log->fp) == 0)
5505     Msg(0, "Creating logfile \"%s\".", fore->w_log->name);
5506   else
5507     Msg(0, "Appending to logfile \"%s\".", fore->w_log->name);
5508   WindowChanged(fore, 'f');
5509 }
5510 
5511 char *
AddWindows(buf,len,flags,where)5512 AddWindows(buf, len, flags, where)
5513 char *buf;
5514 int len;
5515 int flags;
5516 int where;
5517 {
5518   register char *s, *ss;
5519   register struct win **pp, *p;
5520   register char *cmd;
5521   int l;
5522 
5523   s = ss = buf;
5524   if ((flags & 8) && where < 0)
5525     {
5526       *s = 0;
5527       return ss;
5528     }
5529   for (pp = ((flags & 4) && where >= 0) ? wtab + where + 1: wtab; pp < wtab + maxwin; pp++)
5530     {
5531       int rend = -1;
5532       if (pp - wtab == where && ss == buf)
5533         ss = s;
5534       if ((p = *pp) == 0)
5535 	continue;
5536       if ((flags & 1) && display && p == D_fore)
5537 	continue;
5538       if (display && D_fore && D_fore->w_group != p->w_group)
5539 	continue;
5540 
5541       cmd = p->w_title;
5542       l = strlen(cmd);
5543       if (l > 20)
5544         l = 20;
5545       if (s - buf + l > len - 24)
5546 	break;
5547       if (s > buf || (flags & 4))
5548 	{
5549 	  *s++ = ' ';
5550 	  *s++ = ' ';
5551 	}
5552       if (p->w_number == where)
5553         {
5554           ss = s;
5555           if (flags & 8)
5556             break;
5557         }
5558       if (!(flags & 4) || where < 0 || ((flags & 4) && where < p->w_number))
5559 	{
5560 	  if (p->w_monitor == MON_DONE && renditions[REND_MONITOR] != -1)
5561 	    rend = renditions[REND_MONITOR];
5562 	  else if ((p->w_bell == BELL_DONE || p->w_bell == BELL_FOUND) && renditions[REND_BELL] != -1)
5563 	    rend = renditions[REND_BELL];
5564 	  else if ((p->w_silence == SILENCE_FOUND || p->w_silence == SILENCE_DONE) && renditions[REND_SILENCE] != -1)
5565 	    rend = renditions[REND_SILENCE];
5566 	}
5567       if (rend != -1)
5568 	AddWinMsgRend(s, rend);
5569       sprintf(s, "%d", p->w_number);
5570       s += strlen(s);
5571       if (display && p == D_fore)
5572 	*s++ = '*';
5573       if (!(flags & 2))
5574 	{
5575           if (display && p == D_other)
5576 	    *s++ = '-';
5577           s = AddWindowFlags(s, len, p);
5578 	}
5579       *s++ = ' ';
5580       strncpy(s, cmd, l);
5581       s += l;
5582       if (rend != -1)
5583 	AddWinMsgRend(s, -1);
5584     }
5585   *s = 0;
5586   return ss;
5587 }
5588 
5589 char *
AddWindowFlags(buf,len,p)5590 AddWindowFlags(buf, len, p)
5591 char *buf;
5592 int len;
5593 struct win *p;
5594 {
5595   char *s = buf;
5596   if (p == 0 || len < 12)
5597     {
5598       *s = 0;
5599       return s;
5600     }
5601 #if 0
5602   if (display && p == D_fore)
5603     *s++ = '*';
5604   if (display && p == D_other)
5605     *s++ = '-';
5606 #endif
5607   if (p->w_layer.l_cvlist && p->w_layer.l_cvlist->c_lnext)
5608     *s++ = '&';
5609   if (p->w_monitor == MON_DONE
5610 #ifdef MULTIUSER
5611       && display && (ACLBYTE(p->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id))
5612 #endif
5613      )
5614     *s++ = '@';
5615   if (p->w_bell == BELL_DONE)
5616     *s++ = '!';
5617 #ifdef UTMPOK
5618   if (p->w_slot != (slot_t) 0 && p->w_slot != (slot_t) -1)
5619     *s++ = '$';
5620 #endif
5621   if (p->w_log != 0)
5622     {
5623       strcpy(s, "(L)");
5624       s += 3;
5625     }
5626   if (p->w_ptyfd < 0 && p->w_type != W_TYPE_GROUP)
5627     *s++ = 'Z';
5628   *s = 0;
5629   return s;
5630 }
5631 
5632 char *
AddOtherUsers(buf,len,p)5633 AddOtherUsers(buf, len, p)
5634 char *buf;
5635 int len;
5636 struct win *p;
5637 {
5638   struct display *d, *olddisplay = display;
5639   struct canvas *cv;
5640   char *s;
5641   int l;
5642 
5643   s = buf;
5644   for (display = displays; display; display = display->d_next)
5645     {
5646       if (olddisplay && D_user == olddisplay->d_user)
5647 	continue;
5648       for (cv = D_cvlist; cv; cv = cv->c_next)
5649 	if (Layer2Window(cv->c_layer) == p)
5650 	  break;
5651       if (!cv)
5652 	continue;
5653       for (d = displays; d && d != display; d = d->d_next)
5654 	if (D_user == d->d_user)
5655 	  break;
5656       if (d && d != display)
5657 	continue;
5658       if (len > 1 && s != buf)
5659 	{
5660 	  *s++ = ',';
5661 	  len--;
5662 	}
5663       l = strlen(D_user->u_name);
5664       if (l + 1 > len)
5665 	break;
5666       strcpy(s, D_user->u_name);
5667       s += l;
5668       len -= l;
5669     }
5670   *s = 0;
5671   display = olddisplay;
5672   return s;
5673 }
5674 
5675 void
ShowWindows(where)5676 ShowWindows(where)
5677 int where;
5678 {
5679   char buf[1024];
5680   char *s, *ss;
5681 
5682   if (display && where == -1 && D_fore)
5683     where = D_fore->w_number;
5684   ss = AddWindows(buf, sizeof(buf), 0, where);
5685   s = buf + strlen(buf);
5686   if (display && ss - buf > D_width / 2)
5687     {
5688       ss -= D_width / 2;
5689       if (s - ss < D_width)
5690 	{
5691 	  ss = s - D_width;
5692 	  if (ss < buf)
5693 	    ss = buf;
5694 	}
5695     }
5696   else
5697     ss = buf;
5698   Msg(0, "%s", ss);
5699 }
5700 
5701 /*
5702 * String Escape based windows listing
5703 * mls: currently does a Msg() call for each(!) window, dunno why
5704 */
5705 static void
ShowWindowsX(str)5706 ShowWindowsX(str)
5707 char *str;
5708 {
5709 	int i;
5710 	debug1("ShowWindowsX: string [%s]", str);
5711 	for (i = 0; i < maxwin ; i++) {
5712 		if (!wtab[i])
5713 			continue;
5714 		Msg(0, "%s", MakeWinMsg(str, wtab[i], '%'));
5715 	}
5716 }
5717 
5718 
5719 static void
ShowInfo()5720 ShowInfo()
5721 {
5722   char buf[512], *p;
5723   register struct win *wp = fore;
5724   register int i;
5725 
5726   if (wp == 0)
5727     {
5728       Msg(0, "(%d,%d)/(%d,%d) no window", D_x + 1, D_y + 1, D_width, D_height);
5729       return;
5730     }
5731   p = buf;
5732   if (buf < (p += GetAnsiStatus(wp, p)))
5733     *p++ = ' ';
5734   sprintf(p, "(%d,%d)/(%d,%d)",
5735     wp->w_x + 1, wp->w_y + 1, wp->w_width, wp->w_height);
5736 #ifdef COPY_PASTE
5737   sprintf(p += strlen(p), "+%d", wp->w_histheight);
5738 #endif
5739   sprintf(p += strlen(p), " %c%sflow",
5740   	  (wp->w_flow & FLOW_NOW) ? '+' : '-',
5741 	  (wp->w_flow & FLOW_AUTOFLAG) ? "" :
5742 	   ((wp->w_flow & FLOW_AUTO) ? "(+)" : "(-)"));
5743   if (!wp->w_wrap) sprintf(p += strlen(p), " -wrap");
5744   if (wp->w_insert) sprintf(p += strlen(p), " ins");
5745   if (wp->w_origin) sprintf(p += strlen(p), " org");
5746   if (wp->w_keypad) sprintf(p += strlen(p), " app");
5747   if (wp->w_log)    sprintf(p += strlen(p), " log");
5748   if (wp->w_monitor != MON_OFF
5749 #ifdef MULTIUSER
5750       && (ACLBYTE(wp->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id))
5751 #endif
5752      )
5753     sprintf(p += strlen(p), " mon");
5754   if (wp->w_mouse) sprintf(p += strlen(p), " mouse");
5755 #ifdef COLOR
5756   if (wp->w_bce) sprintf(p += strlen(p), " bce");
5757 #endif
5758   if (!wp->w_c1) sprintf(p += strlen(p), " -c1");
5759   if (wp->w_norefresh) sprintf(p += strlen(p), " nored");
5760 
5761   p += strlen(p);
5762 #ifdef FONT
5763 # ifdef ENCODINGS
5764   if (wp->w_encoding && (display == 0 || D_encoding != wp->w_encoding || EncodingDefFont(wp->w_encoding) <= 0))
5765     {
5766       *p++ = ' ';
5767       strcpy(p, EncodingName(wp->w_encoding));
5768       p += strlen(p);
5769     }
5770 #  ifdef UTF8
5771   if (wp->w_encoding != UTF8)
5772 #  endif
5773 # endif
5774     if (display && (D_CC0 || (D_CS0 && *D_CS0)))
5775       {
5776 	if (wp->w_gr == 2)
5777 	  {
5778 	    sprintf(p, " G%c", wp->w_Charset + '0');
5779 	    if (wp->w_FontE >= ' ')
5780 	      p[3] = wp->w_FontE;
5781 	    else
5782 	      {
5783 	        p[3] = '^';
5784 	        p[4] = wp->w_FontE ^ 0x40;
5785 		p++;
5786 	      }
5787 	    p[4] = '[';
5788 	    p++;
5789 	  }
5790 	else if (wp->w_gr)
5791 	  sprintf(p++, " G%c%c[", wp->w_Charset + '0', wp->w_CharsetR + '0');
5792 	else
5793 	  sprintf(p, " G%c[", wp->w_Charset + '0');
5794 	p += 4;
5795 	for (i = 0; i < 4; i++)
5796 	  {
5797 	    if (wp->w_charsets[i] == ASCII)
5798 	      *p++ = 'B';
5799 	    else if (wp->w_charsets[i] >= ' ')
5800 	      *p++ = wp->w_charsets[i];
5801 	    else
5802 	      {
5803 		*p++ = '^';
5804 		*p++ = wp->w_charsets[i] ^ 0x40;
5805 	      }
5806 	  }
5807 	*p++ = ']';
5808 	*p = 0;
5809       }
5810 #endif
5811 
5812   if (wp->w_type == W_TYPE_PLAIN)
5813     {
5814       /* add info about modem control lines */
5815       *p++ = ' ';
5816       TtyGetModemStatus(wp->w_ptyfd, p);
5817     }
5818 #ifdef BUILTIN_TELNET
5819   else if (wp->w_type == W_TYPE_TELNET)
5820     {
5821       *p++ = ' ';
5822       TelStatus(wp, p, sizeof(buf) - 1 - (p - buf));
5823     }
5824 #endif
5825   Msg(0, "%s %d(%s)", buf, wp->w_number, wp->w_title);
5826 }
5827 
5828 static void
ShowDInfo()5829 ShowDInfo()
5830 {
5831   char buf[512], *p;
5832   if (display == 0)
5833     return;
5834   p = buf;
5835   sprintf(p, "(%d,%d)", D_width, D_height),
5836   p += strlen(p);
5837 #ifdef ENCODINGS
5838   if (D_encoding)
5839     {
5840       *p++ = ' ';
5841       strcpy(p, EncodingName(D_encoding));
5842       p += strlen(p);
5843     }
5844 #endif
5845   if (D_CXT)
5846     {
5847       strcpy(p, " xterm");
5848       p += strlen(p);
5849     }
5850 #ifdef COLOR
5851   if (D_hascolor)
5852     {
5853       strcpy(p, " color");
5854       p += strlen(p);
5855     }
5856 #endif
5857 #ifdef FONT
5858   if (D_CG0)
5859     {
5860       strcpy(p, " iso2022");
5861       p += strlen(p);
5862     }
5863   else if (D_CS0 && *D_CS0)
5864     {
5865       strcpy(p, " altchar");
5866       p += strlen(p);
5867     }
5868 #endif
5869   Msg(0, "%s", buf);
5870 }
5871 
5872 static void
AKAfin(buf,len,data)5873 AKAfin(buf, len, data)
5874 char *buf;
5875 int len;
5876 char *data;	/* dummy */
5877 {
5878   ASSERT(display);
5879   if (len && fore)
5880     ChangeAKA(fore, buf, strlen(buf));
5881 
5882   enter_window_name_mode = 0;
5883 }
5884 
5885 static void
InputAKA()5886 InputAKA()
5887 {
5888   char *s, *ss;
5889   int n;
5890 
5891   if (enter_window_name_mode == 1) return;
5892 
5893   enter_window_name_mode = 1;
5894 
5895   Input("Set window's title to: ", sizeof(fore->w_akabuf) - 1, INP_COOKED, AKAfin, NULL, 0);
5896   s = fore->w_title;
5897   if (!s)
5898     return;
5899   for (; *s; s++)
5900     {
5901       if ((*(unsigned char *)s & 0x7f) < 0x20 || *s == 0x7f)
5902 	continue;
5903       ss = s;
5904       n = 1;
5905       LayProcess(&ss, &n);
5906     }
5907 }
5908 
5909 static void
Colonfin(buf,len,data)5910 Colonfin(buf, len, data)
5911 char *buf;
5912 int len;
5913 char *data;	/* dummy */
5914 {
5915   char mbuf[256];
5916 
5917   RemoveStatus();
5918   if (buf[len] == '\t')
5919     {
5920       int m, x;
5921       int l = 0, r = RC_LAST;
5922       int showmessage = 0;
5923       char *s = buf;
5924 
5925       while (*s && s - buf < len)
5926 	if (*s++ == ' ')
5927 	  return;
5928 
5929       /* Showing a message when there's no hardstatus or caption cancels the input */
5930       if (display &&
5931 	  (captionalways || D_has_hstatus == HSTATUS_LASTLINE || (D_canvas.c_slperp && D_canvas.c_slperp->c_slnext)))
5932 	showmessage = 1;
5933 
5934       while (l <= r)
5935 	{
5936 	  m = (l + r) / 2;
5937 	  x = strncmp(buf, comms[m].name, len);
5938 	  if (x > 0)
5939 	    l = m + 1;
5940 	  else if (x < 0)
5941 	    r = m - 1;
5942 	  else
5943 	    {
5944 	      s = mbuf;
5945 	      for (l = m - 1; l >= 0 && strncmp(buf, comms[l].name, len) == 0; l--)
5946 		;
5947 	      for (m = ++l; m <= r && strncmp(buf, comms[m].name, len) == 0 && s - mbuf < sizeof(mbuf); m++)
5948 		s += snprintf(s, sizeof(mbuf) - (s - mbuf), " %s", comms[m].name);
5949 	      if (l < m - 1)
5950 		{
5951 		  if (showmessage)
5952 		    Msg(0, "Possible commands:%s", mbuf);
5953 		}
5954 	      else
5955 		{
5956 		  s = mbuf;
5957 		  len = snprintf(mbuf, sizeof(mbuf), "%s \t", comms[l].name + len);
5958 		  if (len > 0 && len < sizeof(mbuf))
5959 		    LayProcess(&s, &len);
5960 		}
5961 	      break;
5962 	    }
5963 	}
5964       if (l > r && showmessage)
5965 	Msg(0, "No commands matching '%*s'", len, buf);
5966       return;
5967     }
5968 
5969   if (!len || buf[len])
5970     return;
5971 
5972   len = strlen(buf) + 1;
5973   if (len > (int)sizeof(mbuf))
5974     RcLine(buf, len);
5975   else
5976     {
5977       bcopy(buf, mbuf, len);
5978       RcLine(mbuf, sizeof mbuf);
5979     }
5980 }
5981 
5982 static void
SelectFin(buf,len,data)5983 SelectFin(buf, len, data)
5984 char *buf;
5985 int len;
5986 char *data;	/* dummy */
5987 {
5988   int n;
5989 
5990   if (!len || !display)
5991     return;
5992   if (len == 1 && *buf == '-')
5993     {
5994       SetForeWindow((struct win *)0);
5995       Activate(0);
5996       return;
5997     }
5998   if ((n = WindowByNoN(buf)) < 0)
5999     return;
6000   SwitchWindow(n);
6001 }
6002 
6003 static void
SelectLayoutFin(buf,len,data)6004 SelectLayoutFin(buf, len, data)
6005 char *buf;
6006 int len;
6007 char *data;	/* dummy */
6008 {
6009   struct layout *lay;
6010 
6011   if (!len || !display)
6012     return;
6013   if (len == 1 && *buf == '-')
6014     {
6015       LoadLayout((struct layout *)0, (struct canvas *)0);
6016       Activate(0);
6017       return;
6018     }
6019   lay = FindLayout(buf);
6020   if (!lay)
6021     Msg(0, "No such layout\n");
6022   else if (lay == D_layout)
6023     Msg(0, "This IS layout %d (%s).\n", lay->lay_number, lay->lay_title);
6024   else
6025     {
6026       LoadLayout(lay, &D_canvas);
6027       Activate(0);
6028     }
6029 }
6030 
6031 
6032 static void
InputSelect()6033 InputSelect()
6034 {
6035   Input("Switch to window: ", 20, INP_COOKED, SelectFin, NULL, 0);
6036 }
6037 
6038 static char setenv_var[31];
6039 
6040 
6041 static void
SetenvFin1(buf,len,data)6042 SetenvFin1(buf, len, data)
6043 char *buf;
6044 int len;
6045 char *data;	/* dummy */
6046 {
6047   if (!len || !display)
6048     return;
6049   InputSetenv(buf);
6050 }
6051 
6052 static void
SetenvFin2(buf,len,data)6053 SetenvFin2(buf, len, data)
6054 char *buf;
6055 int len;
6056 char *data;	/* dummy */
6057 {
6058   if (!len || !display)
6059     return;
6060   debug2("SetenvFin2: setenv '%s' '%s'\n", setenv_var, buf);
6061   xsetenv(setenv_var, buf);
6062   MakeNewEnv();
6063 }
6064 
6065 static void
InputSetenv(arg)6066 InputSetenv(arg)
6067 char *arg;
6068 {
6069   static char setenv_buf[50 + sizeof(setenv_var)];	/* need to be static here, cannot be freed */
6070 
6071   if (arg)
6072     {
6073       strncpy(setenv_var, arg, sizeof(setenv_var) - 1);
6074       sprintf(setenv_buf, "Enter value for %s: ", setenv_var);
6075       Input(setenv_buf, 30, INP_COOKED, SetenvFin2, NULL, 0);
6076     }
6077   else
6078     Input("Setenv: Enter variable name: ", 30, INP_COOKED, SetenvFin1, NULL, 0);
6079 }
6080 
6081 /*
6082  * the following options are understood by this parser:
6083  * -f, -f0, -f1, -fy, -fa
6084  * -t title, -T terminal-type, -h height-of-scrollback,
6085  * -ln, -l0, -ly, -l1, -l
6086  * -a, -M, -L
6087  */
6088 void
DoScreen(fn,av)6089 DoScreen(fn, av)
6090 char *fn, **av;
6091 {
6092   struct NewWindow nwin;
6093   register int num;
6094   char buf[20];
6095 
6096   nwin = nwin_undef;
6097   while (av && *av && av[0][0] == '-')
6098     {
6099       if (av[0][1] == '-')
6100 	{
6101 	  av++;
6102 	  break;
6103 	}
6104       switch (av[0][1])
6105 	{
6106 	case 'f':
6107 	  switch (av[0][2])
6108 	    {
6109 	    case 'n':
6110 	    case '0':
6111 	      nwin.flowflag = FLOW_NOW * 0;
6112 	      break;
6113 	    case 'y':
6114 	    case '1':
6115 	    case '\0':
6116 	      nwin.flowflag = FLOW_NOW * 1;
6117 	      break;
6118 	    case 'a':
6119 	      nwin.flowflag = FLOW_AUTOFLAG;
6120 	      break;
6121 	    default:
6122 	      break;
6123 	    }
6124 	  break;
6125 	case 't':	/* no more -k */
6126 	  if (av[0][2])
6127 	    nwin.aka = &av[0][2];
6128 	  else if (*++av)
6129 	    nwin.aka = *av;
6130 	  else
6131 	    --av;
6132 	  break;
6133 	case 'T':
6134 	  if (av[0][2])
6135 	    nwin.term = &av[0][2];
6136 	  else if (*++av)
6137 	    nwin.term = *av;
6138 	  else
6139 	    --av;
6140 	  break;
6141 	case 'h':
6142 	  if (av[0][2])
6143 	    nwin.histheight = atoi(av[0] + 2);
6144 	  else if (*++av)
6145 	    nwin.histheight = atoi(*av);
6146 	  else
6147 	    --av;
6148 	  break;
6149 #ifdef LOGOUTOK
6150 	case 'l':
6151 	  switch (av[0][2])
6152 	    {
6153 	    case 'n':
6154 	    case '0':
6155 	      nwin.lflag = 0;
6156 	      break;
6157 	    case 'y':
6158 	    case '1':
6159 	    case '\0':
6160 	      nwin.lflag = 1;
6161 	      break;
6162 	    case 'a':
6163 	      nwin.lflag = 3;
6164 	      break;
6165 	    default:
6166 	      break;
6167 	    }
6168 	  break;
6169 #endif
6170 	case 'a':
6171 	  nwin.aflag = 1;
6172 	  break;
6173 	case 'M':
6174 	  nwin.monitor = MON_ON;
6175 	  break;
6176 	case 'L':
6177 	  nwin.Lflag = 1;
6178 	  break;
6179 	default:
6180 	  Msg(0, "%s: screen: invalid option -%c.", fn, av[0][1]);
6181 	  break;
6182 	}
6183       ++av;
6184     }
6185   if (av && *av && IsNumColon(*av, 10, buf, sizeof(buf)))
6186     {
6187       if (*buf != '\0')
6188 	nwin.aka = buf;
6189       num = atoi(*av);
6190       if (num < 0 || (maxwin && num > maxwin - 1) || (!maxwin && num > MAXWIN - 1))
6191 	{
6192 	  Msg(0, "%s: illegal screen number %d.", fn, num);
6193 	  num = 0;
6194 	}
6195       nwin.StartAt = num;
6196       ++av;
6197     }
6198   if (av && *av)
6199     {
6200       nwin.args = av;
6201       if (!nwin.aka)
6202         nwin.aka = Filename(*av);
6203     }
6204   MakeWindow(&nwin);
6205 }
6206 
6207 #ifdef COPY_PASTE
6208 /*
6209  * CompileKeys must be called before Markroutine is first used.
6210  * to initialise the keys with defaults, call CompileKeys(NULL, mark_key_tab);
6211  *
6212  * s is an ascii string in a termcap-like syntax. It looks like
6213  *   "j=u:k=d:l=r:h=l: =.:" and so on...
6214  * this example rebinds the cursormovement to the keys u (up), d (down),
6215  * l (left), r (right). placing a mark will now be done with ".".
6216  */
6217 int
CompileKeys(s,sl,array)6218 CompileKeys(s, sl, array)
6219 char *s;
6220 int sl;
6221 unsigned char *array;
6222 {
6223   int i;
6224   unsigned char key, value;
6225 
6226   if (sl == 0)
6227     {
6228       for (i = 0; i < 256; i++)
6229         array[i] = i;
6230       return 0;
6231     }
6232   debug1("CompileKeys: '%s'\n", s);
6233   while (sl)
6234     {
6235       key = *(unsigned char *)s++;
6236       if (*s != '=' || sl < 3)
6237 	return -1;
6238       sl--;
6239       do
6240 	{
6241 	  s++;
6242 	  sl -= 2;
6243 	  value = *(unsigned char *)s++;
6244 	  array[value] = key;
6245 	}
6246       while (*s == '=' && sl >= 2);
6247       if (sl == 0)
6248 	break;
6249       if (*s++ != ':')
6250 	return -1;
6251       sl--;
6252     }
6253   return 0;
6254 }
6255 #endif /* COPY_PASTE */
6256 
6257 /*
6258  *  Asynchronous input functions
6259  */
6260 
6261 #if defined(DETACH) && defined(POW_DETACH)
6262 static void
pow_detach_fn(buf,len,data)6263 pow_detach_fn(buf, len, data)
6264 char *buf;
6265 int len;
6266 char *data;	/* dummy */
6267 {
6268   debug("pow_detach_fn called\n");
6269   if (len)
6270     {
6271       memset(buf, 0, len);
6272       return;
6273     }
6274   if (ktab[(int)(unsigned char)*buf].nr != RC_POW_DETACH)
6275     {
6276       if (display)
6277         write(D_userfd, "\007", 1);
6278       Msg(0, "Detach aborted.");
6279     }
6280   else
6281     Detach(D_POWER);
6282 }
6283 #endif /* POW_DETACH */
6284 
6285 #ifdef COPY_PASTE
6286 static void
copy_reg_fn(buf,len,data)6287 copy_reg_fn(buf, len, data)
6288 char *buf;
6289 int len;
6290 char *data;	/* dummy */
6291 {
6292   struct plop *pp = plop_tab + (int)(unsigned char)*buf;
6293 
6294   if (len)
6295     {
6296       memset(buf, 0, len);
6297       return;
6298     }
6299   if (pp->buf)
6300     free(pp->buf);
6301   pp->buf = 0;
6302   pp->len = 0;
6303   if (D_user->u_plop.len)
6304     {
6305       if ((pp->buf = (char *)malloc(D_user->u_plop.len)) == NULL)
6306 	{
6307 	  Msg(0, "%s", strnomem);
6308 	  return;
6309 	}
6310       bcopy(D_user->u_plop.buf, pp->buf, D_user->u_plop.len);
6311     }
6312   pp->len = D_user->u_plop.len;
6313 #ifdef ENCODINGS
6314   pp->enc = D_user->u_plop.enc;
6315 #endif
6316   Msg(0, "Copied %d characters into register %c", D_user->u_plop.len, *buf);
6317 }
6318 
6319 static void
ins_reg_fn(buf,len,data)6320 ins_reg_fn(buf, len, data)
6321 char *buf;
6322 int len;
6323 char *data;	/* dummy */
6324 {
6325   struct plop *pp = plop_tab + (int)(unsigned char)*buf;
6326 
6327   if (len)
6328     {
6329       memset(buf, 0, len);
6330       return;
6331     }
6332   if (!fore)
6333     return;	/* Input() should not call us w/o fore, but you never know... */
6334   if (*buf == '.')
6335     Msg(0, "ins_reg_fn: Warning: pasting real register '.'!");
6336   if (pp->buf)
6337     {
6338       MakePaster(&fore->w_paster, pp->buf, pp->len, 0);
6339       return;
6340     }
6341   Msg(0, "Empty register.");
6342 }
6343 #endif /* COPY_PASTE */
6344 
6345 static void
process_fn(buf,len,data)6346 process_fn(buf, len, data)
6347 char *buf;
6348 int len;
6349 char *data;	/* dummy */
6350 {
6351   struct plop *pp = plop_tab + (int)(unsigned char)*buf;
6352 
6353   if (len)
6354     {
6355       memset(buf, 0, len);
6356       return;
6357     }
6358   if (pp->buf)
6359     {
6360       ProcessInput(pp->buf, pp->len);
6361       return;
6362     }
6363   Msg(0, "Empty register.");
6364 }
6365 
6366 static void
confirm_fn(buf,len,data)6367 confirm_fn(buf, len, data)
6368 char *buf;
6369 int len;
6370 char *data;
6371 {
6372   struct action act;
6373 
6374   if (len || (*buf != 'y' && *buf != 'Y'))
6375     {
6376       memset(buf, 0, len);
6377       return;
6378     }
6379   act.nr = *(int *)data;
6380   act.args = noargs;
6381   act.argl = 0;
6382   act.quiet = 0;
6383   DoAction(&act, -1);
6384 }
6385 
6386 #ifdef MULTIUSER
6387 struct inputsu
6388 {
6389   struct acluser **up;
6390   char name[24];
6391   char pw1[130];	/* FreeBSD crypts to 128 bytes */
6392   char pw2[130];
6393 };
6394 
6395 static void
su_fin(buf,len,data)6396 su_fin(buf, len, data)
6397 char *buf;
6398 int len;
6399 char *data;
6400 {
6401   struct inputsu *i = (struct inputsu *)data;
6402   char *p;
6403   int l;
6404 
6405   if (!*i->name)
6406     { p = i->name; l = sizeof(i->name) - 1; }
6407   else if (!*i->pw1)
6408     { strcpy(p = i->pw1, "\377"); l = sizeof(i->pw1) - 1; }
6409   else
6410     { strcpy(p = i->pw2, "\377"); l = sizeof(i->pw2) - 1; }
6411   if (buf && len)
6412     strncpy(p, buf, 1 + ((l < len) ? l : len));
6413   if (!*i->name)
6414     Input("Screen User: ", sizeof(i->name) - 1, INP_COOKED, su_fin, (char *)i, 0);
6415   else if (!*i->pw1)
6416     Input("User's UNIX Password: ", sizeof(i->pw1)-1, INP_COOKED|INP_NOECHO, su_fin, (char *)i, 0);
6417   else if (!*i->pw2)
6418     Input("User's Screen Password: ", sizeof(i->pw2)-1, INP_COOKED|INP_NOECHO, su_fin, (char *)i, 0);
6419   else
6420     {
6421       if ((p = DoSu(i->up, i->name, i->pw2, i->pw1)))
6422         Msg(0, "%s", p);
6423       free((char *)i);
6424     }
6425 }
6426 
6427 static int
InputSu(w,up,name)6428 InputSu(w, up, name)
6429 struct win *w;
6430 struct acluser **up;
6431 char *name;
6432 {
6433   struct inputsu *i;
6434 
6435   if (!(i = (struct inputsu *)calloc(1, sizeof(struct inputsu))))
6436     return -1;
6437 
6438   i->up = up;
6439   if (name && *name)
6440     su_fin(name, (int)strlen(name), (char *)i); /* can also initialise stuff */
6441   else
6442     su_fin((char *)0, 0, (char *)i);
6443   return 0;
6444 }
6445 #endif	/* MULTIUSER */
6446 
6447 #ifdef PASSWORD
6448 
6449 static void
pass1(buf,len,data)6450 pass1(buf, len, data)
6451 char *buf;
6452 int len;
6453 char *data;
6454 {
6455   struct acluser *u = (struct acluser *)data;
6456 
6457   if (!*buf)
6458     return;
6459   ASSERT(u);
6460   if (u->u_password != NullStr)
6461     free((char *)u->u_password);
6462   u->u_password = SaveStr(buf);
6463   bzero(buf, strlen(buf));
6464   Input("Retype new password:", 100, INP_NOECHO, pass2, data, 0);
6465 }
6466 
6467 static void
pass2(buf,len,data)6468 pass2(buf, len, data)
6469 char *buf;
6470 int len;
6471 char *data;
6472 {
6473   int st;
6474   char salt[3];
6475   struct acluser *u = (struct acluser *)data;
6476 
6477   ASSERT(u);
6478   if (!buf || strcmp(u->u_password, buf))
6479     {
6480       Msg(0, "[ Passwords don't match - checking turned off ]");
6481       if (u->u_password != NullStr)
6482         {
6483           bzero(u->u_password, strlen(u->u_password));
6484           free((char *)u->u_password);
6485 	}
6486       u->u_password = NullStr;
6487     }
6488   else if (u->u_password[0] == '\0')
6489     {
6490       Msg(0, "[ No password - no secure ]");
6491       if (buf)
6492         bzero(buf, strlen(buf));
6493     }
6494 
6495   if (u->u_password != NullStr)
6496     {
6497       for (st = 0; st < 2; st++)
6498 	salt[st] = 'A' + (int)((time(0) >> 6 * st) % 26);
6499       salt[2] = 0;
6500       buf = crypt(u->u_password, salt);
6501       bzero(u->u_password, strlen(u->u_password));
6502       free((char *)u->u_password);
6503       if (!buf)
6504 	{
6505 	  Msg(0, "[ crypt() error - no secure ]");
6506 	  u->u_password = NullStr;
6507 	  return;
6508 	}
6509       u->u_password = SaveStr(buf);
6510       bzero(buf, strlen(buf));
6511 #ifdef COPY_PASTE
6512       if (u->u_plop.buf)
6513 	UserFreeCopyBuffer(u);
6514       u->u_plop.len = strlen(u->u_password);
6515 # ifdef ENCODINGS
6516       u->u_plop.enc = 0;
6517 #endif
6518       if (!(u->u_plop.buf = SaveStr(u->u_password)))
6519 	{
6520 	  Msg(0, "%s", strnomem);
6521           D_user->u_plop.len = 0;
6522 	}
6523       else
6524 	Msg(0, "[ Password moved into copybuffer ]");
6525 #else				/* COPY_PASTE */
6526       Msg(0, "[ Crypted password is \"%s\" ]", u->u_password);
6527 #endif				/* COPY_PASTE */
6528     }
6529 }
6530 #endif /* PASSWORD */
6531 
6532 static int
digraph_find(buf)6533 digraph_find(buf)
6534 const char *buf;
6535 {
6536   int i;
6537   for (i = 0; i < MAX_DIGRAPH && digraphs[i].d[0]; i++)
6538     if ((digraphs[i].d[0] == (unsigned char)buf[0] && digraphs[i].d[1] == (unsigned char)buf[1]) ||
6539 	(digraphs[i].d[0] == (unsigned char)buf[1] && digraphs[i].d[1] == (unsigned char)buf[0]))
6540       break;
6541   return i;
6542 }
6543 
6544 static void
digraph_fn(buf,len,data)6545 digraph_fn(buf, len, data)
6546 char *buf;
6547 int len;
6548 char *data;	/* dummy */
6549 {
6550   int ch, i, x;
6551 
6552   ch = buf[len];
6553   if (ch)
6554     {
6555       buf[len + 1] = ch;		/* so we can restore it later */
6556       if (ch < ' ' || ch == '\177')
6557 	return;
6558       if (len >= 1 && ((*buf == 'U' && buf[1] == '+') || (*buf == '0' && (buf[1] == 'x' || buf[1] == 'X'))))
6559 	{
6560 	  if (len == 1)
6561 	    return;
6562 	  if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f') && (ch < 'A' || ch > 'F'))
6563 	    {
6564 	      buf[len] = '\034';	/* ^] is ignored by Input() */
6565 	      return;
6566 	    }
6567 	  if (len == (*buf == 'U' ? 5 : 3))
6568 	    buf[len] = '\n';
6569 	  return;
6570 	}
6571       if (len && *buf == '0')
6572 	{
6573 	  if (ch < '0' || ch > '7')
6574 	    {
6575 	      buf[len] = '\034';	/* ^] is ignored by Input() */
6576 	      return;
6577 	    }
6578 	  if (len == 3)
6579 	    buf[len] = '\n';
6580 	  return;
6581 	}
6582       if (len == 1)
6583         buf[len] = '\n';
6584       return;
6585     }
6586   if (len < 1)
6587     return;
6588   if (buf[len + 1])
6589     {
6590       buf[len] = buf[len + 1];	/* stored above */
6591       len++;
6592     }
6593   if (len < 2)
6594     return;
6595   if (!parse_input_int(buf, len, &x))
6596     {
6597       i = digraph_find(buf);
6598       if ((x = digraphs[i].value) <= 0)
6599 	{
6600 	  Msg(0, "Unknown digraph");
6601 	  return;
6602 	}
6603     }
6604   i = 1;
6605   *buf = x;
6606 #ifdef UTF8
6607   if (flayer->l_encoding == UTF8)
6608     i = ToUtf8(buf, x);	/* buf is big enough for all UTF-8 codes */
6609 #endif
6610   while(i)
6611     LayProcess(&buf, &i);
6612 }
6613 
6614 #ifdef MAPKEYS
6615 int
StuffKey(i)6616 StuffKey(i)
6617 int i;
6618 {
6619   struct action *act;
6620   int discard = 0;
6621   int keyno = i;
6622 
6623   debug1("StuffKey #%d", i);
6624 #ifdef DEBUG
6625   if (i < KMAP_KEYS)
6626     debug1(" - %s", term[i + T_CAPS].tcname);
6627 #endif
6628 
6629   if (i < KMAP_KEYS && D_ESCseen)
6630     {
6631       struct action *act = &D_ESCseen[i + 256];
6632       if (act->nr != RC_ILLEGAL)
6633 	{
6634 	  D_ESCseen = 0;
6635 	  WindowChanged(fore, 'E');
6636           DoAction(act, i + 256);
6637 	  return 0;
6638 	}
6639       discard = 1;
6640     }
6641 
6642   if (i >= T_CURSOR - T_CAPS && i < T_KEYPAD - T_CAPS && D_cursorkeys)
6643     i += T_OCAPS - T_CURSOR;
6644   else if (i >= T_KEYPAD - T_CAPS && i < T_OCAPS - T_CAPS && D_keypad)
6645     i += T_OCAPS - T_CURSOR;
6646   debug1(" - action %d\n", i);
6647   flayer = D_forecv->c_layer;
6648   fore = D_fore;
6649   act = 0;
6650 #ifdef COPY_PASTE
6651   if (flayer && flayer->l_mode == 1)
6652     act = i < KMAP_KEYS+KMAP_AKEYS ? &mmtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].mm;
6653 #endif
6654   if ((!act || act->nr == RC_ILLEGAL) && !D_mapdefault)
6655     act = i < KMAP_KEYS+KMAP_AKEYS ? &umtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].um;
6656   if (!act || act->nr == RC_ILLEGAL)
6657     act = i < KMAP_KEYS+KMAP_AKEYS ? &dmtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].dm;
6658 
6659   if (discard && (!act || act->nr != RC_COMMAND))
6660     {
6661       /* if the input was just a single byte we let it through */
6662       if (D_tcs[keyno + T_CAPS].str && strlen(D_tcs[keyno + T_CAPS].str) == 1)
6663 	return -1;
6664       if (D_ESCseen)
6665         {
6666           D_ESCseen = 0;
6667           WindowChanged(fore, 'E');
6668         }
6669       return 0;
6670     }
6671   D_mapdefault = 0;
6672 
6673   if (act == 0 || act->nr == RC_ILLEGAL)
6674     return -1;
6675   DoAction(act, 0);
6676   return 0;
6677 }
6678 #endif
6679 
6680 
6681 static int
IsOnDisplay(wi)6682 IsOnDisplay(wi)
6683 struct win *wi;
6684 {
6685   struct canvas *cv;
6686   ASSERT(display);
6687   for (cv = D_cvlist; cv; cv = cv->c_next)
6688     if (Layer2Window(cv->c_layer) == wi)
6689       return 1;
6690   return 0;
6691 }
6692 
6693 struct win *
FindNiceWindow(wi,presel)6694 FindNiceWindow(wi, presel)
6695 struct win *wi;
6696 char *presel;
6697 {
6698   int i;
6699 
6700   debug2("FindNiceWindow %d %s\n", wi ? wi->w_number : -1 , presel ? presel : "NULL");
6701   if (presel)
6702     {
6703       i = WindowByNoN(presel);
6704       if (i >= 0)
6705 	wi = wtab[i];
6706     }
6707   if (!display)
6708     return wi;
6709 #ifdef MULTIUSER
6710   if (wi && AclCheckPermWin(D_user, ACL_READ, wi))
6711     wi = 0;
6712 #endif
6713   if (!wi || (IsOnDisplay(wi) && !presel))
6714     {
6715       /* try to get another window */
6716       wi = 0;
6717 #ifdef MULTIUSER
6718       for (wi = windows; wi; wi = wi->w_next)
6719 	if (!wi->w_layer.l_cvlist && !AclCheckPermWin(D_user, ACL_WRITE, wi))
6720 	  break;
6721       if (!wi)
6722         for (wi = windows; wi; wi = wi->w_next)
6723 	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi) && !AclCheckPermWin(D_user, ACL_WRITE, wi))
6724 	    break;
6725       if (!wi)
6726 	for (wi = windows; wi; wi = wi->w_next)
6727 	  if (!wi->w_layer.l_cvlist && !AclCheckPermWin(D_user, ACL_READ, wi))
6728 	    break;
6729       if (!wi)
6730 	for (wi = windows; wi; wi = wi->w_next)
6731 	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi) && !AclCheckPermWin(D_user, ACL_READ, wi))
6732 	    break;
6733 #endif
6734       if (!wi)
6735 	for (wi = windows; wi; wi = wi->w_next)
6736 	  if (!wi->w_layer.l_cvlist)
6737 	    break;
6738       if (!wi)
6739 	for (wi = windows; wi; wi = wi->w_next)
6740 	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi))
6741 	    break;
6742     }
6743 #ifdef MULTIUSER
6744   if (wi && AclCheckPermWin(D_user, ACL_READ, wi))
6745     wi = 0;
6746 #endif
6747   return wi;
6748 }
6749 
6750 #if 0
6751 
6752 /* sorted list of all commands */
6753 static struct comm **commtab;
6754 static int ncommtab;
6755 
6756 void
6757 AddComms(cos, hand)
6758 struct comm *cos;
6759 void (*hand) __P((struct comm *, char **, int));
6760 {
6761   int n, i, j, r;
6762   for (n = 0; cos[n].name; n++)
6763     ;
6764   if (n == 0)
6765     return;
6766   if (commtab)
6767     commtab = (struct commt *)realloc(commtab, sizeof(*commtab) * (ncommtab + n));
6768   else
6769     commtab = (struct commt *)malloc(sizeof(*commtab) * (ncommtab + n));
6770   if (!commtab)
6771     Panic(0, strnomem);
6772   for (i = 0; i < n; i++)
6773     {
6774       for (j = 0; j < ncommtab; j++)
6775 	{
6776 	  r = strcmp(cos[i].name, commtab[j]->name);
6777 	  if (r == 0)
6778 	    Panic(0, "Duplicate command: %s\n", cos[i].name);
6779 	  if (r < 0)
6780 	    break;
6781 	}
6782       for (r = ncommtab; r > j; r--)
6783 	commtab[r] = commtab[r - 1];
6784       commtab[j] = cos + i;
6785       cos[i].handler = hand;
6786       bzero(cos[i].userbits, sizeof(cos[i].userbits));
6787       ncommtab++;
6788     }
6789 }
6790 
6791 struct comm *
6792 FindComm(str)
6793 char *str;
6794 {
6795   int x, m, l = 0, r = ncommtab - 1;
6796   while (l <= r)
6797     {
6798       m = (l + r) / 2;
6799       x = strcmp(str, commtab[m]->name);
6800       if (x > 0)
6801 	l = m + 1;
6802       else if (x < 0)
6803 	r = m - 1;
6804       else
6805 	return commtab[m];
6806     }
6807   return 0;
6808 }
6809 
6810 #endif
6811 
6812 static int
CalcSlicePercent(cv,percent)6813 CalcSlicePercent(cv, percent)
6814 struct canvas *cv;
6815 int percent;
6816 {
6817   int w, wsum, up;
6818   if (!cv || !cv->c_slback)
6819     return percent;
6820   up = CalcSlicePercent(cv->c_slback->c_slback, percent);
6821   w = cv->c_slweight;
6822   for (cv = cv->c_slback->c_slperp, wsum = 0; cv; cv = cv->c_slnext)
6823     wsum += cv->c_slweight;
6824   if (wsum == 0)
6825     return 0;
6826   return (up * w) / wsum;
6827 }
6828 
6829 static int
ChangeCanvasSize(fcv,abs,diff,gflag,percent)6830 ChangeCanvasSize(fcv, abs, diff, gflag, percent)
6831 struct canvas *fcv;	/* make this canvas bigger */
6832 int abs;		/* mode: 0:rel 1:abs 2:max */
6833 int diff;		/* change this much */
6834 int gflag;		/* go up if neccessary */
6835 int percent;
6836 {
6837   struct canvas *cv;
6838   int done, have, m, dir;
6839 
6840   debug3("ChangeCanvasSize abs %d diff %d percent=%d\n", abs, diff, percent);
6841   if (abs == 0 && diff == 0)
6842     return 0;
6843   if (abs == 2)
6844     {
6845       if (diff == 0)
6846 	  fcv->c_slweight = 0;
6847       else
6848 	{
6849           for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
6850 	    cv->c_slweight = 0;
6851 	  fcv->c_slweight = 1;
6852 	  cv = fcv->c_slback->c_slback;
6853 	  if (gflag && cv && cv->c_slback)
6854 	    ChangeCanvasSize(cv, abs, diff, gflag, percent);
6855 	}
6856       return diff;
6857     }
6858   if (abs)
6859     {
6860       if (diff < 0)
6861 	diff = 0;
6862       if (percent && diff > percent)
6863 	diff = percent;
6864     }
6865   if (percent)
6866     {
6867       int wsum, up;
6868       for (cv = fcv->c_slback->c_slperp, wsum = 0; cv; cv = cv->c_slnext)
6869 	wsum += cv->c_slweight;
6870       if (wsum)
6871 	{
6872 	  up = gflag ? CalcSlicePercent(fcv->c_slback->c_slback, percent) : percent;
6873           debug3("up=%d, wsum=%d percent=%d\n", up, wsum, percent);
6874 	  if (wsum < 1000)
6875 	    {
6876 	      int scale = wsum < 10 ? 1000 : 100;
6877 	      for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
6878 		cv->c_slweight *= scale;
6879 	      wsum *= scale;
6880 	      debug1("scaled wsum to %d\n", wsum);
6881 	    }
6882 	  for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
6883 	    {
6884 	      if (cv->c_slweight)
6885 		{
6886 	          cv->c_slweight = (cv->c_slweight * up) / percent;
6887 		  if (cv->c_slweight == 0)
6888 		    cv->c_slweight = 1;
6889 		}
6890 	      debug1("  - weight %d\n", cv->c_slweight);
6891 	    }
6892 	  diff = (diff * wsum) / percent;
6893 	  percent = wsum;
6894 	}
6895     }
6896   else
6897     {
6898       if (abs && diff == (fcv->c_slorient == SLICE_VERT ? fcv->c_ye - fcv->c_ys + 2 : fcv->c_xe - fcv->c_xs + 2))
6899 	return 0;
6900       /* fix weights to real size (can't be helped, sorry) */
6901       for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
6902 	{
6903 	  cv->c_slweight = cv->c_slorient == SLICE_VERT ? cv->c_ye - cv->c_ys + 2 : cv->c_xe - cv->c_xs + 2;
6904 	  debug1("  - weight %d\n", cv->c_slweight);
6905 	}
6906     }
6907   if (abs)
6908     diff = diff - fcv->c_slweight;
6909   debug1("diff = %d\n", diff);
6910   if (diff == 0)
6911     return 0;
6912   if (diff < 0)
6913     {
6914       cv = fcv->c_slnext ? fcv->c_slnext : fcv->c_slprev;
6915       fcv->c_slweight += diff;
6916       cv->c_slweight -= diff;
6917       return diff;
6918     }
6919   done = 0;
6920   dir = 1;
6921   for (cv = fcv->c_slnext; diff > 0; cv = dir > 0 ? cv->c_slnext : cv->c_slprev)
6922     {
6923       if (!cv)
6924 	{
6925 	  debug1("reached end, dir is %d\n", dir);
6926 	  if (dir == -1)
6927 	    break;
6928 	  dir = -1;
6929 	  cv = fcv;
6930 	  continue;
6931 	}
6932       if (percent)
6933 	m = 1;
6934       else
6935         m = cv->c_slperp ? CountCanvasPerp(cv) * 2 : 2;
6936       debug2("min is %d, have %d\n", m, cv->c_slweight);
6937       if (cv->c_slweight > m)
6938 	{
6939 	  have = cv->c_slweight - m;
6940 	  if (have > diff)
6941 	    have = diff;
6942 	  debug1("subtract %d\n", have);
6943 	  cv->c_slweight -= have;
6944 	  done += have;
6945 	  diff -= have;
6946 	}
6947     }
6948   if (diff && gflag)
6949     {
6950       /* need more room! */
6951       cv = fcv->c_slback->c_slback;
6952       if (cv && cv->c_slback)
6953         done += ChangeCanvasSize(fcv->c_slback->c_slback, 0, diff, gflag, percent);
6954     }
6955   fcv->c_slweight += done;
6956   debug1("ChangeCanvasSize returns %d\n", done);
6957   return done;
6958 }
6959 
6960 static void
ResizeRegions(arg,flags)6961 ResizeRegions(arg, flags)
6962 char *arg;
6963 int flags;
6964 {
6965   struct canvas *cv;
6966   int diff, l;
6967   int gflag = 0, abs = 0, percent = 0;
6968   int orient = 0;
6969 
6970   ASSERT(display);
6971   if (!*arg)
6972     return;
6973   if (D_forecv->c_slorient == SLICE_UNKN)
6974     {
6975       Msg(0, "resize: need more than one region");
6976       return;
6977     }
6978   gflag = flags & RESIZE_FLAG_L ? 0 : 1;
6979   orient |= flags & RESIZE_FLAG_H ? SLICE_HORI : 0;
6980   orient |= flags & RESIZE_FLAG_V ? SLICE_VERT : 0;
6981   if (orient == 0)
6982     orient = D_forecv->c_slorient;
6983   l = strlen(arg);
6984   if (*arg == '=')
6985     {
6986       /* make all regions the same height */
6987       struct canvas *cv = gflag ? &D_canvas : D_forecv->c_slback;
6988       if (cv->c_slperp->c_slorient & orient)
6989 	EqualizeCanvas(cv->c_slperp, gflag);
6990       /* can't use cv->c_slorient directly as it can be D_canvas */
6991       if ((cv->c_slperp->c_slorient ^ (SLICE_HORI ^ SLICE_VERT)) & orient)
6992         {
6993 	  if (cv->c_slback)
6994 	    {
6995 	      cv = cv->c_slback;
6996 	      EqualizeCanvas(cv->c_slperp, gflag);
6997 	    }
6998 	  else
6999 	   EqualizeCanvas(cv, gflag);
7000         }
7001       ResizeCanvas(cv);
7002       RecreateCanvasChain();
7003       RethinkDisplayViewports();
7004       ResizeLayersToCanvases();
7005       return;
7006     }
7007   if (!strcmp(arg, "min") || !strcmp(arg, "0"))
7008     {
7009       abs = 2;
7010       diff = 0;
7011     }
7012   else if (!strcmp(arg, "max") || !strcmp(arg, "_"))
7013     {
7014       abs = 2;
7015       diff = 1;
7016     }
7017   else
7018     {
7019       if (l > 0 && arg[l - 1] == '%')
7020 	percent = 1000;
7021       if (*arg == '+')
7022 	diff = atoi(arg + 1);
7023       else if (*arg == '-')
7024 	diff = -atoi(arg + 1);
7025       else
7026 	{
7027 	  diff = atoi(arg);		/* +1 because of caption line */
7028 	  if (diff < 0)
7029 	    diff = 0;
7030 	  abs = diff == 0 ? 2 : 1;
7031 	}
7032     }
7033   if (!abs && !diff)
7034     return;
7035   if (percent)
7036     diff = diff * percent / 100;
7037   cv = D_forecv;
7038   if (cv->c_slorient & orient)
7039     ChangeCanvasSize(cv, abs, diff, gflag, percent);
7040   if (cv->c_slback->c_slorient & orient)
7041     ChangeCanvasSize(cv->c_slback, abs, diff, gflag, percent);
7042 
7043   ResizeCanvas(&D_canvas);
7044   RecreateCanvasChain();
7045   RethinkDisplayViewports();
7046   ResizeLayersToCanvases();
7047   return;
7048 
7049 #if 0
7050 
7051   if (siz + diff < 1)
7052     diff = 1 - siz;
7053   if (siz + diff > dsize - (nreg - 1) * 2 - 1)
7054     diff = dsize - (nreg - 1) * 2 - 1 - siz;
7055   if (diff == 0 || siz + diff < 1)
7056     return;
7057 
7058   if (diff < 0)
7059     {
7060       if (D_forecv->c_next)
7061 	{
7062 	  D_forecv->c_ye += diff;
7063 	  D_forecv->c_next->c_ys += diff;
7064 	  D_forecv->c_next->c_yoff += diff;
7065 	}
7066       else
7067 	{
7068 	  for (cv = D_cvlist; cv; cv = cv->c_next)
7069 	    if (cv->c_next == D_forecv)
7070 	      break;
7071 	  ASSERT(cv);
7072 	  cv->c_ye -= diff;
7073 	  D_forecv->c_ys -= diff;
7074 	  D_forecv->c_yoff -= diff;
7075 	}
7076     }
7077   else
7078     {
7079       int s, i = 0, found = 0, di = diff, d2;
7080       s = dsize - (nreg - 1) * 2 - 1 - siz;
7081       for (cv = D_cvlist; cv; i = cv->c_ye + 2, cv = cv->c_next)
7082 	{
7083 	  if (cv == D_forecv)
7084 	    {
7085 	      cv->c_ye = i + (cv->c_ye - cv->c_ys) + diff;
7086 	      cv->c_yoff -= cv->c_ys - i;
7087 	      cv->c_ys = i;
7088 	      found = 1;
7089 	      continue;
7090 	    }
7091 	  s -= cv->c_ye - cv->c_ys;
7092 	  if (!found)
7093 	    {
7094 	      if (s >= di)
7095 		continue;
7096 	      d2 = di - s;
7097 	    }
7098 	  else
7099 	    d2 = di > cv->c_ye - cv->c_ys ? cv->c_ye - cv->c_ys : di;
7100 	  di -= d2;
7101 	  cv->c_ye = i + (cv->c_ye - cv->c_ys) - d2;
7102 	  cv->c_yoff -= cv->c_ys - i;
7103 	  cv->c_ys = i;
7104         }
7105     }
7106   RethinkDisplayViewports();
7107   ResizeLayersToCanvases();
7108 #endif
7109 }
7110 
7111 static void
ResizeFin(buf,len,data)7112 ResizeFin(buf, len, data)
7113 char *buf;
7114 int len;
7115 char *data;
7116 {
7117   int ch;
7118   int flags = *(int *)data;
7119   ch = ((unsigned char *)buf)[len];
7120   if (ch == 0)
7121     {
7122       ResizeRegions(buf, flags);
7123       return;
7124     }
7125   if (ch == 'h')
7126     flags ^= RESIZE_FLAG_H;
7127   else if (ch == 'v')
7128     flags ^= RESIZE_FLAG_V;
7129   else if (ch == 'b')
7130     flags |= RESIZE_FLAG_H|RESIZE_FLAG_V;
7131   else if (ch == 'p')
7132     flags ^= D_forecv->c_slorient == SLICE_VERT ? RESIZE_FLAG_H : RESIZE_FLAG_V;
7133   else if (ch == 'l')
7134     flags ^= RESIZE_FLAG_L;
7135   else
7136     return;
7137   inp_setprompt(resizeprompts[flags], NULL);
7138   *(int *)data = flags;
7139   buf[len] = '\034';
7140 }
7141 
7142 void
SetForeCanvas(d,cv)7143 SetForeCanvas(d, cv)
7144 struct display *d;
7145 struct canvas *cv;
7146 {
7147   struct display *odisplay = display;
7148   if (d->d_forecv == cv)
7149     return;
7150 
7151   display = d;
7152   D_forecv = cv;
7153   if ((focusminwidth && (focusminwidth < 0 || D_forecv->c_xe - D_forecv->c_xs + 1 < focusminwidth)) ||
7154       (focusminheight && (focusminheight < 0 || D_forecv->c_ye - D_forecv->c_ys + 1 < focusminheight)))
7155     {
7156       ResizeCanvas(&D_canvas);
7157       RecreateCanvasChain();
7158       RethinkDisplayViewports();
7159       ResizeLayersToCanvases();	/* redisplays */
7160     }
7161   fore = D_fore = Layer2Window(D_forecv->c_layer);
7162   if (D_other == fore)
7163     D_other = 0;
7164   flayer = D_forecv->c_layer;
7165 #ifdef RXVT_OSC
7166   if (D_xtermosc[2] || D_xtermosc[3])
7167     {
7168       Activate(-1);
7169     }
7170   else
7171 #endif
7172     {
7173       RefreshHStatus();
7174 #ifdef RXVT_OSC
7175       RefreshXtermOSC();
7176 #endif
7177       flayer = D_forecv->c_layer;
7178       CV_CALL(D_forecv, LayRestore();LaySetCursor());
7179       WindowChanged(0, 'F');
7180     }
7181 
7182   display = odisplay;
7183 }
7184 
7185 #ifdef RXVT_OSC
7186 void
RefreshXtermOSC()7187 RefreshXtermOSC()
7188 {
7189   int i;
7190   struct win *p;
7191 
7192   p = Layer2Window(D_forecv->c_layer);
7193   for (i = 4; i >=0; i--)
7194     SetXtermOSC(i, p ? p->w_xtermosc[i] : 0, "\a");
7195 }
7196 #endif
7197 
7198 int
ParseAttrColor(s1,s2,msgok)7199 ParseAttrColor(s1, s2, msgok)
7200 char *s1, *s2;
7201 int msgok;
7202 {
7203   int i, n;
7204   char *s, *ss;
7205   int r = 0;
7206 
7207   s = s1;
7208   while (*s == ' ')
7209     s++;
7210   ss = s;
7211   while (*ss && *ss != ' ')
7212     ss++;
7213   while (*ss == ' ')
7214     ss++;
7215   if (*s && (s2 || *ss || !((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '.')))
7216     {
7217       int mode = 0, n = 0;
7218       if (*s == '+')
7219 	{
7220 	  mode = 1;
7221 	  s++;
7222 	}
7223       else if (*s == '-')
7224 	{
7225 	  mode = -1;
7226 	  s++;
7227 	}
7228       else if (*s == '!')
7229 	{
7230 	  mode = 2;
7231 	  s++;
7232 	}
7233       else if (*s == '=')
7234 	s++;
7235       if (*s >= '0' && *s <= '9')
7236 	{
7237 	  n = *s++ - '0';
7238 	  if (*s >= '0' && *s <= '9')
7239 	    n = n * 16 + (*s++ - '0');
7240 	  else if (*s >= 'a' && *s <= 'f')
7241 	    n = n * 16 + (*s++ - ('a' - 10));
7242 	  else if (*s >= 'A' && *s <= 'F')
7243 	    n = n * 16 + (*s++ - ('A' - 10));
7244 	  else if (*s && *s != ' ')
7245 	    {
7246 	      if (msgok)
7247 		Msg(0, "Illegal attribute hexchar '%c'", *s);
7248 	      return -1;
7249 	    }
7250 	}
7251       else
7252 	{
7253 	  while (*s && *s != ' ')
7254 	    {
7255 	      if (*s == 'd')
7256 		n |= A_DI;
7257 	      else if (*s == 'u')
7258 		n |= A_US;
7259 	      else if (*s == 'b')
7260 		n |= A_BD;
7261 	      else if (*s == 'r')
7262 		n |= A_RV;
7263 	      else if (*s == 's')
7264 		n |= A_SO;
7265 	      else if (*s == 'B')
7266 		n |= A_BL;
7267 	      else
7268 		{
7269 		  if (msgok)
7270 		    Msg(0, "Illegal attribute specifier '%c'", *s);
7271 		  return -1;
7272 		}
7273 	      s++;
7274 	    }
7275 	}
7276       if (*s && *s != ' ')
7277 	{
7278 	  if (msgok)
7279 	    Msg(0, "junk after attribute description: '%c'", *s);
7280 	  return -1;
7281 	}
7282       if (mode == -1)
7283 	r = n << 8 | n;
7284       else if (mode == 1)
7285 	r = n << 8;
7286       else if (mode == 2)
7287 	r = n;
7288       else if (mode == 0)
7289 	r = 0xffff ^ n;
7290     }
7291   while (*s && *s == ' ')
7292     s++;
7293 
7294   if (s2)
7295     {
7296       if (*s)
7297 	{
7298 	  if (msgok)
7299 	    Msg(0, "junk after description: '%c'", *s);
7300 	  return -1;
7301 	}
7302       s = s2;
7303       while (*s && *s == ' ')
7304 	s++;
7305     }
7306 
7307 #ifdef COLOR
7308   if (*s)
7309     {
7310       static char costr[] = "krgybmcw d    i.01234567 9     f               FKRGYBMCW      I ";
7311       int numco = 0, j;
7312 
7313       n = 0;
7314       if (*s == '.')
7315 	{
7316 	  numco++;
7317 	  n = 0x0f;
7318 	  s++;
7319 	}
7320       for (j = 0; j < 2 && *s && *s != ' '; j++)
7321 	{
7322 	  for (i = 0; costr[i]; i++)
7323 	    if (*s == costr[i])
7324 	      break;
7325 	  if (!costr[i])
7326 	    {
7327 	      if (msgok)
7328 		Msg(0, "illegal color descriptor: '%c'", *s);
7329 	      return -1;
7330 	    }
7331 	  numco++;
7332 	  n = n << 4 | (i & 15);
7333 #ifdef COLORS16
7334 	  if (i >= 48)
7335 	    n = (n & 0x20ff) | 0x200;
7336 #endif
7337 	  s++;
7338 	}
7339       if ((n & 0xf00) == 0xf00)
7340         n ^= 0xf00;	/* clear superflous bits */
7341 #ifdef COLORS16
7342       if (n & 0x2000)
7343 	n ^= 0x2400;	/* shift bit into right position */
7344 #endif
7345       if (numco == 1)
7346 	n |= 0xf0;	/* don't change bg color */
7347       if (numco != 2 && n != 0xff)
7348 	n |= 0x100;	/* special invert mode */
7349       if (*s && *s != ' ')
7350 	{
7351 	  if (msgok)
7352 	    Msg(0, "junk after color description: '%c'", *s);
7353 	  return -1;
7354 	}
7355       n ^= 0xff;
7356       r |= n << 16;
7357     }
7358 #endif
7359 
7360   while (*s && *s == ' ')
7361     s++;
7362   if (*s)
7363     {
7364       if (msgok)
7365 	Msg(0, "junk after description: '%c'", *s);
7366       return -1;
7367     }
7368   debug1("ParseAttrColor %06x\n", r);
7369   return r;
7370 }
7371 
7372 /*
7373  *  Color coding:
7374  *    0-7 normal colors
7375  *    9   default color
7376  *    e   just set intensity
7377  *    f   don't change anything
7378  *  Intensity is encoded into bits 17(fg) and 18(bg).
7379  */
7380 void
ApplyAttrColor(i,mc)7381 ApplyAttrColor(i, mc)
7382 int i;
7383 struct mchar *mc;
7384 {
7385   debug1("ApplyAttrColor %06x\n", i);
7386   mc->attr |= i >> 8 & 255;
7387   mc->attr ^= i & 255;
7388 #ifdef COLOR
7389   i = (i >> 16) ^ 0xff;
7390   if ((i & 0x100) != 0)
7391     {
7392       i &= 0xeff;
7393       if (mc->attr & (A_SO|A_RV))
7394 # ifdef COLORS16
7395         i = ((i & 0x0f) << 4) | ((i & 0xf0) >> 4) | ((i & 0x200) << 1) | ((i & 0x400) >> 1);
7396 # else
7397         i = ((i & 0x0f) << 4) | ((i & 0xf0) >> 4);
7398 # endif
7399     }
7400 # ifdef COLORS16
7401   if ((i & 0x0f) != 0x0f)
7402     mc->attr = (mc->attr & 0xbf) | ((i >> 3) & 0x40);
7403   if ((i & 0xf0) != 0xf0)
7404     mc->attr = (mc->attr & 0x7f) | ((i >> 3) & 0x80);
7405 # endif
7406   mc->color = 0x99 ^ mc->color;
7407   if ((i & 0x0e) == 0x0e)
7408     i = (i & 0xf0) | (mc->color & 0x0f);
7409   if ((i & 0xe0) == 0xe0)
7410     i = (i & 0x0f) | (mc->color & 0xf0);
7411   mc->color = 0x99 ^ i;
7412   debug2("ApplyAttrColor - %02x %02x\n", mc->attr, i);
7413 #endif
7414 }
7415