Source:NetHack 5.0.0/src/cmd.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to cmd.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/cmd.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	cmd.c	$NHDT-Date: 1762680996 2025/11/09 01:36:36 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.755 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2013. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "func_tab.h"
8. 
9. #ifdef UNIX
10. /*
11.  * Some systems may have getchar() return EOF for various reasons, and
12.  * we should not quit before seeing at least NR_OF_EOFS consecutive EOFs.
13.  */
14. #if defined(SYSV) || defined(DGUX) || defined(HPUX)
15. #define NR_OF_EOFS 20
16. #endif
17. #endif
18. 
19. #ifdef DUMB /* stuff commented out in extern.h, but needed here */
20. extern int doapply(void);            /**/
21. extern int dorub(void);              /**/
22. extern int dojump(void);             /**/
23. extern int doextlist(void);          /**/
24. extern int enter_explore_mode(void); /**/
25. extern int dodrop(void);             /**/
26. extern int doddrop(void);            /**/
27. extern int dodown(void);             /**/
28. extern int doup(void);               /**/
29. extern int donull(void);             /**/
30. extern int dowipe(void);             /**/
31. extern int docallcnd(void);          /**/
32. extern int dotakeoff(void);          /**/
33. extern int doremring(void);          /**/
34. extern int dowear(void);             /**/
35. extern int doputon(void);            /**/
36. extern int doddoremarm(void);        /**/
37. extern int dokick(void);             /**/
38. extern int dofire(void);             /**/
39. extern int dothrow(void);            /**/
40. extern int doeat(void);              /**/
41. extern int done2(void);              /**/
42. extern int dovanquished(void);       /**/
43. extern int doengrave(void);          /**/
44. extern int dopickup(void);           /**/
45. extern int ddoinv(void);             /**/
46. extern int dotypeinv(void);          /**/
47. extern int dolook(void);             /**/
48. extern int doprgold(void);           /**/
49. extern int doprwep(void);            /**/
50. extern int doprarm(void);            /**/
51. extern int doprring(void);           /**/
52. extern int dopramulet(void);         /**/
53. extern int doprtool(void);           /**/
54. extern int dosuspend(void);          /**/
55. extern int doforce(void);            /**/
56. extern int doopen(void);             /**/
57. extern int doclose(void);            /**/
58. extern int dosh(void);               /**/
59. extern int dodiscovered(void);       /**/
60. extern int doclassdisco(void);       /**/
61. extern int doset_simple(void);       /**/
62. extern int doset(void);              /**/
63. extern int dotogglepickup(void);     /**/
64. extern int dowhatis(void);           /**/
65. extern int doquickwhatis(void);      /**/
66. extern int dowhatdoes(void);         /**/
67. extern int dohelp(void);             /**/
68. extern int dohistory(void);          /**/
69. extern int doloot(void);             /**/
70. extern int dodrink(void);            /**/
71. extern int dodip(void);              /**/
72. extern int dosacrifice(void);        /**/
73. extern int dopray(void);             /**/
74. extern int dotip(void);              /**/
75. extern int doturn(void);             /**/
76. extern int doredraw(void);           /**/
77. extern int doread(void);             /**/
78. extern int dosave(void);             /**/
79. extern int dosearch(void);           /**/
80. extern int doidtrap(void);           /**/
81. extern int dopay(void);              /**/
82. extern int dosit(void);              /**/
83. extern int dotalk(void);             /**/
84. extern int docast(void);             /**/
85. extern int dovspell(void);           /**/
86. extern int dotelecmd(void);          /**/
87. extern int dountrap(void);           /**/
88. extern int doversion(void);          /**/
89. extern int doextversion(void);       /**/
90. extern int doswapweapon(void);       /**/
91. extern int dowield(void);            /**/
92. extern int dowieldquiver(void);      /**/
93. extern int dozap(void);              /**/
94. extern int doorganize(void);         /**/
95. #endif /* DUMB */
96. 
97. staticfn struct Cmd_bind *cmdbind_get(uchar);
98. staticfn void cmdbind_add(uchar, const struct ext_func_tab *, boolean);
99. staticfn void cmdbind_remove(uchar);
100. staticfn void cmdbind_swapkeys(uchar, uchar);
101. staticfn int dosuspend_core(void);
102. staticfn int dosh_core(void);
103. staticfn int doherecmdmenu(void);
104. staticfn int dotherecmdmenu(void);
105. staticfn int doprev_message(void);
106. staticfn int timed_occupation(void);
107. staticfn boolean can_do_extcmd(const struct ext_func_tab *);
108. staticfn int dotravel(void);
109. staticfn int dotravel_target(void);
110. staticfn int doclicklook(void);
111. staticfn boolean yn_menuable_resp(const char *);
112. staticfn void yn_func_menu_opt(winid, char, const char *, char);
113. staticfn boolean yn_function_menu(const char *, const char *, char, char *);
114. staticfn int domouseaction(void);
115. staticfn int doterrain(void);
116. staticfn boolean u_have_seen_whole_selection(struct selectionvar *);
117. staticfn boolean u_have_seen_bounds_selection(struct selectionvar *);
118. staticfn boolean u_can_see_whole_selection(struct selectionvar *);
119. staticfn int dolookaround_floodfill_findroom(coordxy, coordxy);
120. staticfn void lookaround_known_room(coordxy, coordxy);
121. 
122. #if defined(__BORLANDC__) && !defined(_WIN32)
123. extern void show_borlandc_stats(winid);
124. #endif
125. staticfn boolean accept_menu_prefix(const struct ext_func_tab *);
126. staticfn void reset_cmd_vars(boolean);
127. 
128. staticfn void mcmd_addmenu(winid, int, const char *);
129. staticfn int there_cmd_menu_self(winid, coordxy, coordxy, int *);
130. staticfn int there_cmd_menu_next2u(winid, coordxy, coordxy, int, int *);
131. staticfn int there_cmd_menu_far(winid, coordxy, coordxy, int);
132. staticfn int there_cmd_menu_common(winid, coordxy, coordxy, int, int *);
133. staticfn void act_on_act(int, coordxy, coordxy);
134. staticfn char there_cmd_menu(coordxy, coordxy, int);
135. staticfn char here_cmd_menu(void);
136. 
137. staticfn char readchar_core(coordxy *, coordxy *, int *);
138. staticfn int parse(void);
139. staticfn void show_direction_keys(winid, char, boolean);
140. staticfn boolean help_dir(char, uchar, const char *);
141. 
142. staticfn void handler_rebind_keys_add(boolean);
143. staticfn boolean bind_key_fn(uchar, int (*)(void));
144. staticfn void commands_init(void);
145. staticfn boolean keylist_func_has_key(const struct ext_func_tab *, boolean *);
146. staticfn int keylist_putcmds(winid, boolean, int, int, boolean *);
147. staticfn const char *spkey_name(int);
148. 
149. staticfn int (*timed_occ_fn)(void);
150. staticfn char *doc_extcmd_flagstr(winid, const struct ext_func_tab *);
151. staticfn int dummyfunction(void);
152. 
153. static const char *readchar_queue = "";
154. 
155. /* for rejecting attempts to use wizard mode commands
156.  * Also used in wizcmds.c  */
157. const char unavailcmd[] = "Unavailable command '%s'.";
158. 
159. /* for rejecting #if !SHELL, !SUSPEND */
160. static const char cmdnotavail[] = "'%s' command not available.";
161. 
162. /* the #prevmsg command */
163. staticfn int
164. doprev_message(void)
165. {
166.     (void) nh_doprev_message();
167.     return ECMD_OK;
168. }
169. 
170. /* Count down by decrementing multi */
171. staticfn int
172. timed_occupation(void)
173. {
174.     (*timed_occ_fn)();
175.     if (gm.multi > 0)
176.         gm.multi--;
177.     return gm.multi > 0;
178. }
179. 
180. /* If you have moved since initially setting some occupations, they
181.  * now shouldn't be able to restart.
182.  *
183.  * The basic rule is that if you are carrying it, you can continue
184.  * since it is with you.  If you are acting on something at a distance,
185.  * your orientation to it must have changed when you moved.
186.  *
187.  * The exception to this is taking off items, since they can be taken
188.  * off in a number of ways in the intervening time, screwing up ordering.
189.  *
190.  *      Currently:      Take off all armor.
191.  *                      Picking Locks / Forcing Chests.
192.  *                      Setting traps.
193.  */
194. void
195. reset_occupations(void)
196. {
197.     reset_remarm();
198.     reset_pick();
199.     reset_trapset();
200. }
201. 
202. /* If a time is given, use it to timeout this function, otherwise the
203.  * function times out by its own means.
204.  */
205. void
206. set_occupation(int (*fn)(void), const char *txt, cmdcount_nht xtime)
207. {
208.     if (xtime) {
209.         go.occupation = timed_occupation;
210.         timed_occ_fn = fn;
211.     } else
212.         go.occupation = fn;
213.     go.occtxt = txt;
214.     go.occtime = 0;
215.     return;
216. }
217. 
218. /*
219. void
220. cmdq_print(int q)
221. {
222.     char buf[QBUFSZ];
223.     struct _cmd_queue *cq = gc.command_queue[q];
224. 
225.     pline("CQ:%i", q);
226.     while (cq) {
227.         switch (cq->typ) {
228.         case CMDQ_KEY:
229.             pline("(key:%s)", key2txt(cq->key, buf));
230.             break;
231.         case CMDQ_EXTCMD:
232.             pline("(extcmd:#%s)", cq->ec_entry->ef_txt);
233.             break;
234.         case CMDQ_DIR:
235.             pline("(dir:%i,%i,%i)", cq->dirx, cq->diry, cq->dirz);
236.             break;
237.         case CMDQ_USER_INPUT:
238.             pline("(userinput)");
239.             break;
240.         case CMDQ_INT:
241.             pline("(int:%i)", cq->intval);
242.             break;
243.         default:
244.             pline("(ERROR:%i)",cq->typ);
245.             break;
246.         }
247.         cq = cq->next;
248.     }
249. }
250. */
251. 
252. /* add extended command function to the command queue */
253. void
254. cmdq_add_ec(int q, int (*fn)(void))
255. {
256.     struct _cmd_queue *tmp = (struct _cmd_queue *) alloc(sizeof *tmp);
257.     struct _cmd_queue *cq = gc.command_queue[q];
258. 
259.     tmp->typ = CMDQ_EXTCMD;
260.     tmp->ec_entry = ext_func_tab_from_func(fn);
261.     tmp->next = NULL;
262. 
263.     while (cq && cq->next)
264.         cq = cq->next;
265. 
266.     if (cq)
267.         cq->next = tmp;
268.     else
269.         gc.command_queue[q] = tmp;
270. }
271. 
272. /* add a key to the command queue */
273. void
274. cmdq_add_key(int q, char key)
275. {
276.     struct _cmd_queue *tmp = (struct _cmd_queue *) alloc(sizeof *tmp);
277.     struct _cmd_queue *cq = gc.command_queue[q];
278. 
279.     tmp->typ = CMDQ_KEY;
280.     tmp->key = key;
281.     tmp->next = NULL;
282. 
283.     while (cq && cq->next)
284.         cq = cq->next;
285. 
286.     if (cq)
287.         cq->next = tmp;
288.     else
289.         gc.command_queue[q] = tmp;
290. }
291. 
292. /* add a direction to the command queue */
293. void
294. cmdq_add_dir(int q, schar dx, schar dy, schar dz)
295. {
296.     struct _cmd_queue *tmp = (struct _cmd_queue *) alloc(sizeof *tmp);
297.     struct _cmd_queue *cq = gc.command_queue[q];
298. 
299.     tmp->typ = CMDQ_DIR;
300.     tmp->dirx = dx;
301.     tmp->diry = dy;
302.     tmp->dirz = dz;
303.     tmp->next = NULL;
304. 
305.     while (cq && cq->next)
306.         cq = cq->next;
307. 
308.     if (cq)
309.         cq->next = tmp;
310.     else
311.         gc.command_queue[q] = tmp;
312. }
313. 
314. /* add placeholder to the command queue, allows user input there */
315. void
316. cmdq_add_userinput(int q)
317. {
318.     struct _cmd_queue *tmp = (struct _cmd_queue *) alloc(sizeof *tmp);
319.     struct _cmd_queue *cq = gc.command_queue[q];
320. 
321.     tmp->typ = CMDQ_USER_INPUT;
322.     tmp->next = NULL;
323. 
324.     while (cq && cq->next)
325.         cq = cq->next;
326. 
327.     if (cq)
328.         cq->next = tmp;
329.     else
330.         gc.command_queue[q] = tmp;
331. }
332. 
333. /* add integer to the command queue */
334. void
335. cmdq_add_int(int q, int val)
336. {
337.     struct _cmd_queue *tmp = (struct _cmd_queue *) alloc(sizeof *tmp);
338.     struct _cmd_queue *cq = gc.command_queue[q];
339. 
340.     tmp->typ = CMDQ_INT;
341.     tmp->intval = val;
342.     tmp->next = NULL;
343. 
344.     while (cq && cq->next)
345.         cq = cq->next;
346. 
347.     if (cq)
348.         cq->next = tmp;
349.     else
350.         gc.command_queue[q] = tmp;
351. }
352. 
353. /* shift the last entry in command queue to first */
354. void
355. cmdq_shift(int q)
356. {
357.     struct _cmd_queue *tmp = NULL;
358.     struct _cmd_queue *cq = gc.command_queue[q];
359. 
360.     while (cq && cq->next && cq->next->next)
361.         cq = cq->next;
362. 
363.     if (cq)
364.         tmp = cq->next;
365.     if (tmp) {
366.         tmp->next = gc.command_queue[q];
367.         gc.command_queue[q] = tmp;
368.         cq->next = NULL;
369.     }
370. }
371. 
372. struct _cmd_queue *
373. cmdq_reverse(struct _cmd_queue *head)
374. {
375.     struct _cmd_queue *prev = NULL, *curr = head, *next;
376. 
377.     while (curr) {
378.         next = curr->next;
379.         curr->next = prev;
380.         prev = curr;
381.         curr = next;
382.     }
383.     return prev;
384. }
385. 
386. struct _cmd_queue *
387. cmdq_copy(int q)
388. {
389.     struct _cmd_queue *tmp = NULL;
390.     struct _cmd_queue *cq = gc.command_queue[q];
391. 
392.     while (cq) {
393.         struct _cmd_queue *tmp2 = (struct _cmd_queue *) alloc(sizeof *tmp2);
394. 
395.         *tmp2 = *cq;
396.         tmp2->next = tmp;
397.         tmp = tmp2;
398.         cq = cq->next;
399.     }
400. 
401.     tmp = cmdq_reverse(tmp);
402. 
403.     return tmp;
404. }
405. 
406. /* pop off the topmost command from the command queue.
407.  * caller is responsible for freeing the returned _cmd_queue.
408.  */
409. struct _cmd_queue *
410. cmdq_pop(void)
411. {
412.     int q = (gi.in_doagain) ? CQ_REPEAT : CQ_CANNED;
413.     struct _cmd_queue *tmp = gc.command_queue[q];
414. 
415.     if (tmp) {
416.         gc.command_queue[q] = tmp->next;
417.         tmp->next = NULL;
418.     }
419.     return tmp;
420. }
421. 
422. /* get the top entry without popping it */
423. struct _cmd_queue *
424. cmdq_peek(int q)
425. {
426.     return gc.command_queue[q];
427. }
428. 
429. /* clear all commands from the command queue */
430. void
431. cmdq_clear(int q)
432. {
433.     struct _cmd_queue *tmp = gc.command_queue[q];
434.     struct _cmd_queue *tmp2;
435. 
436.     while (tmp) {
437.         tmp2 = tmp->next;
438.         free(tmp);
439.         tmp = tmp2;
440.     }
441.     gc.command_queue[q] = NULL;
442. }
443. 
444. char
445. pgetchar(void) /* courtesy of aeb@cwi.nl */
446. {
447.     int ch = '\0';
448. 
449.     if (iflags.debug_fuzzer)
450.         return randomkey();
451.     ch = nhgetch();
452.     return (char) ch;
453. }
454. 
455. /* '#' or whatever has been bound to doextcmd() in its place */
456. char
457. extcmd_initiator(void)
458. {
459.     return gc.Cmd.extcmd_char;
460. }
461. 
462. staticfn boolean
463. can_do_extcmd(const struct ext_func_tab *extcmd)
464. {
465.     int ecflags = extcmd->flags;
466. 
467.     if (gl.luacore && nhcb_counts[NHCB_CMD_BEFORE]) {
468.         lua_getglobal(gl.luacore, "nh_callback_run");
469.         lua_pushstring(gl.luacore, nhcb_name[NHCB_CMD_BEFORE]);
470.         lua_pushstring(gl.luacore, extcmd->ef_txt);
471.         nhl_pcall_handle(gl.luacore, 2, 1, "can_do_extcmd", NHLpa_panic);
472.         if (!lua_toboolean(gl.luacore, -1)) {
473.             lua_settop(gl.luacore, 0);
474.             return FALSE;
475.         }
476.         lua_settop(gl.luacore, 0);
477.     }
478. 
479.     if (!wizard && (ecflags & WIZMODECMD)) {
480.         pline(unavailcmd, extcmd->ef_txt);
481.         return FALSE;
482.     } else if (u.uburied && !(ecflags & IFBURIED)) {
483.         You_cant("do that while you are buried!");
484.         return FALSE;
485.     } else if (iflags.debug_fuzzer && (ecflags & NOFUZZERCMD)) {
486.         return FALSE;
487.     }
488.     return TRUE;
489. }
490. 
491. /* here after # - now read a full-word command */
492. int
493. doextcmd(void)
494. {
495.     int idx, retval;
496.     int (*func)(void);
497. 
498.     /* keep repeating until we don't run help or quit */
499.     do {
500.         idx = get_ext_cmd();
501.         if (idx < 0)
502.             return ECMD_OK; /* quit */
503. 
504.         func = extcmdlist[idx].ef_funct;
505.         if (!can_do_extcmd(&extcmdlist[idx]))
506.             return ECMD_OK;
507.         if (iflags.menu_requested && !accept_menu_prefix(&extcmdlist[idx])) {
508.             pline("'%s' prefix has no effect for the %s command.",
509.                   visctrl(cmd_from_func(do_reqmenu)),
510.                   extcmdlist[idx].ef_txt);
511.             iflags.menu_requested = FALSE;
512.         }
513.         /* tell rhack() what command is actually executing */
514.         ge.ext_tlist = &extcmdlist[idx];
515. 
516.         retval = (*func)();
517.     } while (func == doextlist);
518. 
519.     return retval;
520. }
521. 
522. /* format extended command flags for display */
523. staticfn char *
524. doc_extcmd_flagstr(
525.     winid menuwin,
526.     const struct ext_func_tab *efp) /* if Null, add a footnote to the menu */
527. {
528.     static char Abuf[10]; /* 5 would suffice: {'[','m','A',']','\0'} */
529. 
530.     /* note: tag shown for menu prefix is 'm' even if m-prefix action
531.        has been bound to some other key */
532.     if (!efp) {
533.         char qbuf[QBUFSZ];
534. 
535.         add_menu_str(menuwin, "[A] Command autocompletes");
536.         Sprintf(qbuf, "[m] Command accepts '%s' prefix",
537.                 visctrl(cmd_from_func(do_reqmenu)));
538.         add_menu_str(menuwin, qbuf);
539.         return (char *) 0;
540.     } else {
541.         boolean mprefix = accept_menu_prefix(efp),
542.                 autocomplete = (efp->flags & AUTOCOMPLETE) != 0;
543.         char *p = Abuf;
544. 
545.         /* "" or "[m]" or "[A]" or "[mA]" */
546.         if (mprefix || autocomplete) {
547.             *p++ = '[';
548.             if (mprefix)
549.                 *p++ = 'm';
550.             if (autocomplete)
551.                 *p++ = 'A';
552.             *p++ = ']';
553.         }
554.         *p = '\0';
555.         return Abuf;
556.     }
557. }
558. 
559. /* here after #? - now list all full-word commands and provide
560.    some navigation capability through the long list */
561. int
562. doextlist(void)
563. {
564.     const struct ext_func_tab *efp = (struct ext_func_tab *) 0;
565.     char buf[BUFSZ], searchbuf[BUFSZ], descbuf[BUFSZ], promptbuf[QBUFSZ];
566.     const char *cmd_desc;
567.     winid menuwin;
568.     anything any;
569.     menu_item *selected;
570.     int n, pass;
571.     int menumode = 0, menushown[2], onelist = 0;
572.     boolean redisplay = TRUE, search = FALSE;
573.     static const char *const headings[] = { "Extended commands",
574.                                       "Debugging Extended Commands" };
575.     int clr = NO_COLOR;
576. 
577.     searchbuf[0] = '\0';
578.     menuwin = create_nhwindow(NHW_MENU);
579. 
580.     while (redisplay) {
581.         redisplay = FALSE;
582.         any = cg.zeroany;
583.         start_menu(menuwin, MENU_BEHAVE_STANDARD);
584.         add_menu_str(menuwin, "Extended Commands List");
585.         add_menu_str(menuwin, "");
586. 
587.         Sprintf(buf, "Switch to %s commands that don't autocomplete",
588.                 menumode ? "including" : "excluding");
589.         any.a_int = 1;
590.         add_menu(menuwin, &nul_glyphinfo, &any, 'a', 0, ATR_NONE, clr, buf,
591.                  MENU_ITEMFLAGS_NONE);
592. 
593.         if (!*searchbuf) {
594.             any.a_int = 2;
595.             /* was 's', but then using ':' handling within the interface
596.                would only examine the two or three meta entries, not the
597.                actual list of extended commands shown via separator lines;
598.                having ':' as an explicit selector overrides the default
599.                menu behavior for it; we retain 's' as a group accelerator */
600.             add_menu(menuwin, &nul_glyphinfo, &any, ':', 's', ATR_NONE,
601.                      clr, "Search extended commands",
602.                      MENU_ITEMFLAGS_NONE);
603.         } else {
604.             Strcpy(buf, "Switch back from search");
605.             if (strlen(buf) + strlen(searchbuf) + strlen(" (\"\")") < QBUFSZ)
606.                 Sprintf(eos(buf), " (\"%s\")", searchbuf);
607.             any.a_int = 3;
608.             /* specifying ':' as a group accelerator here is mostly a
609.                statement of intent (we'd like to accept it as a synonym but
610.                also want to hide it from general menu use) because it won't
611.                work for interfaces which support ':' to search; use as a
612.                general menu command takes precedence over group accelerator */
613.             add_menu(menuwin, &nul_glyphinfo, &any, 's', ':', ATR_NONE,
614.                      clr, buf, MENU_ITEMFLAGS_NONE);
615.         }
616.         if (wizard) {
617.             any.a_int = 4;
618.             add_menu(menuwin, &nul_glyphinfo, &any, 'z', 0, ATR_NONE, clr,
619.           onelist ? "Switch to showing debugging commands in separate section"
620.        : "Switch to showing all alphabetically, including debugging commands",
621.                      MENU_ITEMFLAGS_NONE);
622.         }
623.         add_menu_str(menuwin, "");
624.         menushown[0] = menushown[1] = 0;
625.         n = 0;
626.         for (pass = 0; pass <= 1; ++pass) {
627.             /* skip second pass if not in wizard mode or wizard mode
628.                commands are being integrated into a single list */
629.             if (pass == 1 && (onelist || !wizard))
630.                 break;
631.             for (efp = extcmdlist; efp->ef_txt; efp++) {
632.                 int wizc;
633. 
634.                 if ((efp->flags & (CMD_NOT_AVAILABLE | INTERNALCMD)) != 0)
635.                     continue;
636.                 /* if hiding non-autocomplete commands, skip such */
637.                 if (menumode == 1 && (efp->flags & AUTOCOMPLETE) == 0)
638.                     continue;
639.                 /* skip wizard mode commands if not in wizard mode;
640.                    when showing two sections, skip wizard mode commands
641.                    in pass==0 and skip other commands in pass==1 */
642.                 wizc = (efp->flags & WIZMODECMD) != 0;
643.                 if (wizc && !wizard)
644.                     continue;
645.                 if (!onelist && pass != wizc)
646.                     continue;
647.                 /* command description might get modified on the fly */
648.                 cmd_desc = efp->ef_desc;
649.                 /* suppress part of the description for #genocided if it
650.                    doesn't apply during the current game */
651.                 if (!wizard && !discover
652.                     && (efp->flags & GENERALCMD) != 0 /* minor optimization */
653.                     && strstri(cmd_desc, "extinct"))
654.                     cmd_desc = strsubst(strcpy(descbuf, cmd_desc),
655.                                         " been genocided or become extinct",
656.                                         " been genocided");
657.                 /* if searching, skip this command if it doesn't match */
658.                 if (*searchbuf
659.                     /* first try case-insensitive substring match */
660.                     && !strstri(efp->ef_txt, searchbuf)
661.                     && !strstri(cmd_desc, searchbuf)
662.                     /* wildcard support; most interfaces use case-insensitive
663.                        pmatch rather than regexp for menu searching */
664.                     && !pmatchi(searchbuf, efp->ef_txt)
665.                     && !pmatchi(searchbuf, cmd_desc))
666.                     continue;
667. 
668.                 /* We're about to show an item, have we shown the menu yet?
669.                    Doing menu in inner loop like this on demand avoids a
670.                    heading with no subordinate entries on the search
671.                    results menu. */
672.                 if (!menushown[pass]) {
673.                     Strcpy(buf, headings[pass]);
674.                     add_menu_heading(menuwin, buf);
675.                     menushown[pass] = 1;
676.                 }
677.                 /* longest ef_txt at present is "wizrumorcheck" (13 chars);
678.                    2nd field will be "    " or " [A]" or " [m]" or "[mA]" */
679.                 Sprintf(buf, " %-14s %4s %s", efp->ef_txt,
680.                         doc_extcmd_flagstr(menuwin, efp), cmd_desc);
681.                 add_menu_str(menuwin, buf);
682.                 ++n;
683.             }
684.             if (n)
685.                 add_menu_str(menuwin, "");
686.         }
687.         if (*searchbuf && !n)
688.             add_menu_str(menuwin, "no matches");
689.         else
690.             (void) doc_extcmd_flagstr(menuwin, (struct ext_func_tab *) 0);
691. 
692.         end_menu(menuwin, (char *) 0);
693.         n = select_menu(menuwin, PICK_ONE, &selected);
694.         if (n > 0) {
695.             switch (selected[0].item.a_int) {
696.             case 1: /* 'a': toggle show/hide non-autocomplete */
697.                 menumode = 1 - menumode;  /* toggle 0 -> 1, 1 -> 0 */
698.                 redisplay = TRUE;
699.                 break;
700.             case 2: /* ':' when not searching yet: enable search */
701.                 search = TRUE;
702.                 break;
703.             case 3: /* 's' when already searching: disable search */
704.                 search = FALSE;
705.                 searchbuf[0] = '\0';
706.                 redisplay = TRUE;
707.                 break;
708.             case 4: /* 'z': toggle showing wizard mode commands separately */
709.                 search = FALSE;
710.                 searchbuf[0] = '\0';
711.                 onelist = 1 - onelist;  /* toggle 0 -> 1, 1 -> 0 */
712.                 redisplay = TRUE;
713.                 break;
714.             }
715.             free((genericptr_t) selected);
716.         } else {
717.             search = FALSE;
718.             searchbuf[0] = '\0';
719.         }
720.         if (search) {
721.             Strcpy(promptbuf, "Extended command list search phrase");
722.             Strcat(promptbuf, "?");
723.             getlin(promptbuf, searchbuf);
724.             (void) mungspaces(searchbuf);
725.             if (searchbuf[0] == '\033')
726.                 searchbuf[0] = '\0';
727.             if (*searchbuf)
728.                 redisplay = TRUE;
729.             search = FALSE;
730.         }
731.     }
732.     destroy_nhwindow(menuwin);
733.     return ECMD_OK;
734. }
735. 
736. #if defined(TTY_GRAPHICS) || defined(CURSES_GRAPHICS)
737. #define MAX_EXT_CMD 200 /* Change if we ever have more ext cmds */
738. 
739. DISABLE_WARNING_FORMAT_NONLITERAL
740. 
741. /*
742.  * This is currently used only by the tty interface and is
743.  * controlled via runtime option 'extmenu'.  (Most other interfaces
744.  * already use a menu all the time for extended commands.)
745.  *
746.  * ``# ? is counted towards the limit of the number of commands,
747.  * so we actually support MAX_EXT_CMD-1 "real" extended commands.
748.  *
749.  * Here after # - now show pick-list of possible commands.
750.  */
751. int
752. extcmd_via_menu(void)
753. {
754.     const struct ext_func_tab *efp;
755.     menu_item *pick_list = (menu_item *) 0;
756.     winid win;
757.     anything any;
758.     const struct ext_func_tab *choices[MAX_EXT_CMD + 1];
759.     char buf[BUFSZ];
760.     char cbuf[QBUFSZ], prompt[QBUFSZ], fmtstr[20];
761.     int i, n, nchoices, acount;
762.     int ret, len, biggest;
763.     int accelerator, prevaccelerator;
764.     int matchlevel = 0;
765.     boolean wastoolong, one_per_line;
766.     int clr = NO_COLOR;
767. 
768.     ret = 0;
769.     cbuf[0] = '\0';
770.     biggest = 0;
771.     while (!ret) {
772.         i = n = 0;
773.         any = cg.zeroany;
774.         /* populate choices */
775.         for (efp = extcmdlist; efp->ef_txt; efp++) {
776.             if ((efp->flags & (CMD_NOT_AVAILABLE|INTERNALCMD))
777.                 || !(efp->flags & AUTOCOMPLETE)
778.                 || (!wizard && (efp->flags & WIZMODECMD)))
779.                 continue;
780.             if (!matchlevel || !strncmp(efp->ef_txt, cbuf, matchlevel)) {
781.                 choices[i] = efp;
782.                 if ((len = (int) strlen(efp->ef_desc)) > biggest)
783.                     biggest = len;
784.                 if (++i > MAX_EXT_CMD) {
785. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
786.                     impossible(
787.       "Exceeded %d extended commands in doextcmd() menu; 'extmenu' disabled.",
788.                                MAX_EXT_CMD);
789. #endif /* NH_DEVEL_STATUS != NH_STATUS_RELEASED */
790.                     iflags.extmenu = FALSE;
791.                     return -1;
792.                 }
793.             }
794.         }
795.         choices[i] = (struct ext_func_tab *) 0;
796.         nchoices = i;
797.         /* if we're down to one, we have our selection so get out of here */
798.         if (nchoices  <= 1) {
799.             ret = (nchoices == 1) ? (int) (choices[0] - extcmdlist) : -1;
800.             break;
801.         }
802. 
803.         /* otherwise... */
804.         win = create_nhwindow(NHW_MENU);
805.         start_menu(win, MENU_BEHAVE_STANDARD);
806.         Sprintf(fmtstr, "%%-%ds", biggest + 15);
807.         prompt[0] = '\0';
808.         wastoolong = FALSE; /* True => had to wrap due to line width
809.                              * ('w' in wizard mode) */
810.         /* -3: two line menu header, 1 line menu footer (for prompt) */
811.         one_per_line = (nchoices < ROWNO - 3);
812.         prevaccelerator = 0;
813.         acount = 0;
814.         for (i = 0; choices[i]; ++i) {
815.             accelerator = choices[i]->ef_txt[matchlevel];
816.             if (accelerator != prevaccelerator || one_per_line)
817.                 wastoolong = FALSE;
818.             if (accelerator != prevaccelerator || one_per_line
819.                 || (acount >= 2
820.                     /* +4: + sizeof " or " - sizeof "" */
821.                     && (strlen(prompt) + 4 + strlen(choices[i]->ef_txt)
822.                         /* -6: enough room for 1 space left margin
823.                          *   + "%c - " menu selector + 1 space right margin */
824.                         >= min(sizeof prompt, COLNO - 6)))) {
825.                 if (acount) {
826.                     /* flush extended cmds for that letter already in buf */
827.                     Sprintf(buf, fmtstr, prompt);
828.                     any.a_char = prevaccelerator;
829.                     add_menu(win, &nul_glyphinfo, &any, any.a_char,
830.                              0, ATR_NONE, clr, buf, MENU_ITEMFLAGS_NONE);
831.                     acount = 0;
832.                     if (!(accelerator != prevaccelerator || one_per_line))
833.                         wastoolong = TRUE;
834.                 }
835.             }
836.             prevaccelerator = accelerator;
837.             if (!acount || one_per_line) {
838.                 Sprintf(prompt, "%s%s [%s]", wastoolong ? "or " : "",
839.                         choices[i]->ef_txt, choices[i]->ef_desc);
840.             } else if (acount == 1) {
841.                 Sprintf(prompt, "%s%s or %s", wastoolong ? "or " : "",
842.                         choices[i - 1]->ef_txt, choices[i]->ef_txt);
843.             } else {
844.                 Strcat(prompt, " or ");
845.                 Strcat(prompt, choices[i]->ef_txt);
846.             }
847.             ++acount;
848.         }
849.         if (acount) {
850.             /* flush buf */
851.             Sprintf(buf, fmtstr, prompt);
852.             any.a_char = prevaccelerator;
853.             add_menu(win, &nul_glyphinfo, &any, any.a_char, 0,
854.                      ATR_NONE, clr, buf, MENU_ITEMFLAGS_NONE);
855.         }
856.         Snprintf(prompt, sizeof(prompt), "Extended Command: %s", cbuf);
857.         end_menu(win, prompt);
858.         n = select_menu(win, PICK_ONE, &pick_list);
859.         destroy_nhwindow(win);
860.         if (n == 1) {
861.             if (matchlevel > (QBUFSZ - 2)) {
862.                 free((genericptr_t) pick_list);
863. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
864.                 impossible("Too many chars (%d) entered in extcmd_via_menu()",
865.                            matchlevel);
866. #endif
867.                 ret = -1;
868.             } else {
869.                 cbuf[matchlevel++] = pick_list[0].item.a_char;
870.                 cbuf[matchlevel] = '\0';
871.                 free((genericptr_t) pick_list);
872.             }
873.         } else {
874.             if (matchlevel) {
875.                 ret = 0;
876.                 matchlevel = 0;
877.             } else
878.                 ret = -1;
879.         }
880.     }
881.     return ret;
882. }
883. 
884. RESTORE_WARNING_FORMAT_NONLITERAL
885. 
886. #endif /* TTY_GRAPHICS */
887. 
888. /* #monster command - use special monster ability while polymorphed */
889. int
890. domonability(void)
891. {
892.     struct permonst *uptr = gy.youmonst.data;
893.     boolean might_hide = (is_hider(uptr) || hides_under(uptr));
894.     char c = '\0';
895. 
896.     if (might_hide && webmaker(uptr)) {
897.         c = yn_function("Hide [h] or spin a web [s]?",
898.                         hidespinchars, 'q', TRUE);
899.         if (c == 'q' || c == '\033')
900.             return ECMD_OK;
901.     }
902.     if (can_breathe(uptr))
903.         return dobreathe();
904.     else if (attacktype(uptr, AT_SPIT))
905.         return dospit();
906.     else if (uptr->mlet == S_NYMPH)
907.         return doremove();
908.     else if (attacktype(uptr, AT_GAZE))
909.         return dogaze();
910.     else if (is_were(uptr))
911.         return dosummon();
912.     else if (c ? c == 'h' : might_hide)
913.         return dohide();
914.     else if (c ? c == 's' : webmaker(uptr))
915.         return dospinweb();
916.     else if (is_mind_flayer(uptr))
917.         return domindblast();
918.     else if (u.umonnum == PM_GREMLIN) {
919.         if (IS_FOUNTAIN(levl[u.ux][u.uy].typ)) {
920.             if (split_mon(&gy.youmonst, (struct monst *) 0))
921.                 dryup(u.ux, u.uy, TRUE);
922.         } else if (is_pool(u.ux, u.uy)) {
923.             /* is_pool: might be wearing water walking boots or amulet of
924.                magical breathing */
925.             (void) split_mon(&gy.youmonst, (struct monst *) 0);
926.         } else {
927.             There("is no fountain here.");
928.         }
929.     } else if (is_unicorn(uptr)) {
930.         use_unicorn_horn((struct obj **) 0);
931.         return ECMD_TIME;
932.     } else if (uptr->msound == MS_SHRIEK) {
933.         You("shriek.");
934.         if (u.uburied)
935.             pline("Unfortunately sound does not carry well through rock.");
936.         else
937.             aggravate();
938.     } else if (is_vampire(uptr) || is_vampshifter(&gy.youmonst)) {
939.         return dopoly();
940.     } else if (u.usteed && can_breathe(u.usteed->data)) {
941.         (void) pet_ranged_attk(u.usteed, TRUE);
942.         return ECMD_TIME;
943.     } else if (Upolyd) {
944.         pline("Any special ability you may have is purely reflexive.");
945.     } else {
946.         You("don't have a special ability in your normal form!");
947.     }
948.     return ECMD_OK;
949. }
950. 
951. int
952. enter_explore_mode(void)
953. {
954.     if (discover) {
955.         You("are already in explore mode.");
956.     } else {
957.         const char *oldmode = !wizard ? "normal game" : "debug mode";
958. 
959.         if (!authorize_explore_mode()) {
960.             if (!wizard) {
961.                 You("cannot access explore mode.");
962.                 return ECMD_OK;
963.             } else {
964.                 pline(
965.                  "Note: normally you wouldn't be allowed into explore mode.");
966.                 /* keep going */
967.             }
968.         }
969.         pline("Beware!  From explore mode there will be no return to %s,",
970.               oldmode);
971.         if (paranoid_query(ParanoidQuit,
972.                            "Do you want to enter explore mode?")) {
973.             discover = TRUE;
974.             wizard = FALSE;
975.             clear_nhwindow(WIN_MESSAGE);
976.             You("are now in non-scoring explore mode.");
977.         } else {
978.             clear_nhwindow(WIN_MESSAGE);
979.             pline("Continuing with %s.", oldmode);
980.         }
981.     }
982.     return ECMD_OK;
983. }
984. 
985. void
986. makemap_prepost(boolean pre, boolean wiztower)
987. {
988.     NHFILE *tmpnhfp;
989.     struct monst *mtmp;
990. 
991.     if (pre) {
992.         makemap_remove_mons();
993.         rm_mapseen(ledger_no(&u.uz)); /* discard overview info for level */
994.         {
995.             static const char Unachieve[] = "%s achievement revoked.";
996. 
997.             /* achievement tracking; if replacing a level that has a
998.                special prize, lose credit for previously finding it and
999.                reset for the new instance of that prize */
1000.             if (Is_mineend_level(&u.uz)) {
1001.                 if (remove_achievement(ACH_MINE_PRIZE))
1002.                     pline(Unachieve, "Mine's-end");
1003.                 svc.context.achieveo.mines_prize_oid = 0;
1004.             } else if (Is_sokoend_level(&u.uz)) {
1005.                 if (remove_achievement(ACH_SOKO_PRIZE))
1006.                     pline(Unachieve, "Soko-prize");
1007.                 svc.context.achieveo.soko_prize_oid = 0;
1008.             }
1009.         }
1010.         if (Punished) {
1011.             ballrelease(FALSE);
1012.             unplacebc();
1013.         }
1014.         /* reset lock picking unless it's for a carried container */
1015.         maybe_reset_pick((struct obj *) 0);
1016.         /* reset interrupted digging if it was taking place on this level */
1017.         if (on_level(&svc.context.digging.level, &u.uz))
1018.             (void) memset((genericptr_t) &svc.context.digging, 0,
1019.                           sizeof (struct dig_info));
1020.         /* reset cached targets */
1021.         iflags.travelcc.x = iflags.travelcc.y = 0; /* travel destination */
1022.         svc.context.polearm.hitmon = (struct monst *) 0; /* polearm target */
1023.         /* escape from trap */
1024.         reset_utrap(FALSE);
1025.         check_special_room(TRUE); /* room exit */
1026.         (void) memset((genericptr_t) &svd.dndest, 0, sizeof (dest_area));
1027.         (void) memset((genericptr_t) &svu.updest, 0, sizeof (dest_area));
1028.         u.ustuck = (struct monst *) 0;
1029.         u.uswallow = u.uswldtim = 0;
1030.         set_uinwater(0); /* u.uinwater = 0 */
1031.         u.uundetected = 0; /* not hidden, even if means are available */
1032.         dmonsfree(); /* purge dead monsters from 'fmon' */
1033.         dobjsfree();
1034. 
1035.         /* discard current level; "saving" is used to release dynamic data */
1036.         tmpnhfp = get_freeing_nhfile();
1037.         savelev(tmpnhfp, ledger_no(&u.uz));
1038.         close_nhfile(tmpnhfp);
1039.     } else {
1040.         vision_reset();
1041.         gv.vision_full_recalc = 1;
1042.         cls();
1043.         /* was using safe_teleds() but that doesn't honor arrival region
1044.            on levels which have such; we don't force stairs, just area */
1045.         u_on_rndspot((u.uhave.amulet ? 1 : 0) /* 'going up' flag */
1046.                      | (wiztower ? 2 : 0));
1047.         losedogs();
1048.         kill_genocided_monsters();
1049.         /* u_on_rndspot() might pick a spot that has a monster, or losedogs()
1050.            might pick the hero's spot (only if there isn't already a monster
1051.            there), so we might have to move hero or the co-located monster */
1052.         if ((mtmp = m_at(u.ux, u.uy)) != 0)
1053.             u_collide_m(mtmp);
1054.         initrack();
1055.         if (Punished) {
1056.             unplacebc();
1057.             placebc();
1058.         }
1059.         docrt();
1060.         flush_screen(1);
1061.         deliver_splev_message(); /* level entry */
1062.         check_special_room(FALSE); /* room entry */
1063. #ifdef INSURANCE
1064.         save_currentstate();
1065. #endif
1066.     }
1067. }
1068. 
1069. /* temporary? hack, since level type codes aren't the same as screen
1070.    symbols and only the latter have easily accessible descriptions.
1071.    Also used by wizcmds.c */
1072. const char *levltyp[MAX_TYPE + 2] = {
1073.     "stone", "vertical wall", "horizontal wall", "top-left corner wall",
1074.     "top-right corner wall", "bottom-left corner wall",
1075.     "bottom-right corner wall", "cross wall", "tee-up wall", "tee-down wall",
1076.     "tee-left wall", "tee-right wall", "drawbridge wall", "tree",
1077.     "secret door", "secret corridor", "pool", "moat", "water",
1078.     "drawbridge up", "lava pool", "lava wall", "iron bars", "door",
1079.     "corridor", "room", "stairs", "ladder", "fountain", "throne", "sink",
1080.     "grave", "altar", "ice", "drawbridge down", "air", "cloud",
1081.     /* not a real terrain type, but used for undiggable stone
1082.        by wiz_map_levltyp() */
1083.     "unreachable/undiggable",
1084.     /* padding in case the number of entries above is odd */
1085.     ""
1086. };
1087. 
1088. const char *
1089. levltyp_to_name(int typ)
1090. {
1091.     if (typ >= 0 && typ < MAX_TYPE)
1092.         return levltyp[typ];
1093.     return NULL;
1094. }
1095. 
1096. /* #terrain command -- show known map, inspired by crawl's '|' command */
1097. staticfn int
1098. doterrain(void)
1099. {
1100.     winid men;
1101.     menu_item *sel;
1102.     anything any;
1103.     int n;
1104.     int which;
1105.     int clr = NO_COLOR;
1106. 
1107.     /* this used to be done each time vision was recalculated, so would
1108.        always be up to date (hopefully); now we do it on demand instead */
1109.     recalc_mapseen();
1110. 
1111.     /*
1112.      * normal play: choose between known map without mons, obj, and traps
1113.      *  (to see underlying terrain only), or
1114.      *  known map without mons and objs (to see traps under mons and objs), or
1115.      *  known map without mons (to see objects under monsters);
1116.      * explore mode: normal choices plus full map (w/o mons, objs, traps);
1117.      * wizard mode: normal and explore choices plus
1118.      *  a dump of the internal levl[][].typ codes w/ level flags, or
1119.      *  a legend for the levl[][].typ codes dump
1120.      */
1121.     men = create_nhwindow(NHW_MENU);
1122.     start_menu(men, MENU_BEHAVE_STANDARD);
1123.     any = cg.zeroany;
1124.     any.a_int = 1;
1125.     add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE, clr,
1126.              "known map without monsters, objects, and traps",
1127.              MENU_ITEMFLAGS_SELECTED);
1128.     any.a_int = 2;
1129.     add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE,
1130.              clr, "known map without monsters and objects",
1131.              MENU_ITEMFLAGS_NONE);
1132.     any.a_int = 3;
1133.     add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE,
1134.              clr, "known map without monsters",
1135.              MENU_ITEMFLAGS_NONE);
1136.     if (discover || wizard) {
1137.         any.a_int = 4;
1138.         add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE,
1139.                  clr, "full map without monsters, objects, and traps",
1140.                  MENU_ITEMFLAGS_NONE);
1141.         if (wizard) {
1142.             any.a_int = 5;
1143.             add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE,
1144.                      clr, "internal levl[][].typ codes in base-36",
1145.                      MENU_ITEMFLAGS_NONE);
1146.             any.a_int = 6;
1147.             add_menu(men, &nul_glyphinfo, &any, 0, 0, ATR_NONE,
1148.                      clr, "legend of base-36 levl[][].typ codes",
1149.                      MENU_ITEMFLAGS_NONE);
1150.         }
1151.     }
1152.     end_menu(men, "View which?");
1153. 
1154.     n = select_menu(men, PICK_ONE, &sel);
1155.     destroy_nhwindow(men);
1156.     /*
1157.      * n <  0: player used ESC to cancel;
1158.      * n == 0: preselected entry was explicitly chosen and got toggled off;
1159.      * n == 1: preselected entry was implicitly chosen via <space>|<enter>;
1160.      * n == 2: another entry was explicitly chosen, so skip preselected one.
1161.      */
1162.     which = (n < 0) ? -1 : (n == 0) ? 1 : sel[0].item.a_int;
1163.     if (n > 1 && which == 1)
1164.         which = sel[1].item.a_int;
1165.     if (n > 0)
1166.         free((genericptr_t) sel);
1167. 
1168.     switch (which) {
1169.     case 1: /* known map */
1170.         reveal_terrain(TER_MAP);
1171.         break;
1172.     case 2: /* known map with known traps */
1173.         reveal_terrain(TER_MAP | TER_TRP);
1174.         break;
1175.     case 3: /* known map with known traps and objects */
1176.         reveal_terrain(TER_MAP | TER_TRP | TER_OBJ);
1177.         break;
1178.     case 4: /* full map */
1179.         reveal_terrain(TER_MAP | TER_FULL);
1180.         break;
1181.     case 5: /* map internals */
1182.         wiz_map_levltyp();
1183.         break;
1184.     case 6: /* internal details */
1185.         wiz_levltyp_legend();
1186.         break;
1187.     default:
1188.         break;
1189.     }
1190.     return ECMD_OK; /* no time elapses */
1191. }
1192. 
1193. /* has hero seen all locations in selection? */
1194. staticfn boolean
1195. u_have_seen_whole_selection(struct selectionvar *sel)
1196. {
1197.     coordxy x, y;
1198.     NhRect rect = cg.zeroNhRect;
1199. 
1200.     selection_getbounds(sel, &rect);
1201. 
1202.     for (x = rect.lx; x <= rect.hx; x++)
1203.         for (y = rect.ly; y <= rect.hy; y++)
1204.             if (isok(x,y) && selection_getpoint(x, y, sel)
1205.                 && glyph_at(x, y) == GLYPH_UNEXPLORED)
1206.                 return FALSE;
1207. 
1208.     return TRUE;
1209. }
1210. 
1211. /* has hero seen all location of the rectangular outline in the selection */
1212. staticfn boolean
1213. u_have_seen_bounds_selection(struct selectionvar *sel)
1214. {
1215.     coordxy x, y;
1216.     NhRect rect = cg.zeroNhRect;
1217. 
1218.     selection_getbounds(sel, &rect);
1219. 
1220.     for (x = rect.lx; x <= rect.hx; x++) {
1221.         y = rect.ly;
1222.         if (isok(x,y) && selection_getpoint(x, y, sel)
1223.             && glyph_at(x, y) == GLYPH_UNEXPLORED)
1224.             return FALSE;
1225.         y = rect.hy;
1226.         if (isok(x,y) && selection_getpoint(x, y, sel)
1227.             && glyph_at(x, y) == GLYPH_UNEXPLORED)
1228.             return FALSE;
1229.     }
1230.     for (y = rect.ly; y <= rect.hy; y++) {
1231.         x = rect.lx;
1232.         if (isok(x,y) && selection_getpoint(x, y, sel)
1233.             && glyph_at(x, y) == GLYPH_UNEXPLORED)
1234.             return FALSE;
1235.         x = rect.hx;
1236.         if (isok(x,y) && selection_getpoint(x, y, sel)
1237.             && glyph_at(x, y) == GLYPH_UNEXPLORED)
1238.             return FALSE;
1239.     }
1240. 
1241.     return TRUE;
1242. }
1243. 
1244. /* can hero currently see all locations in the selection */
1245. staticfn boolean
1246. u_can_see_whole_selection(struct selectionvar *sel)
1247. {
1248.     coordxy x, y;
1249.     NhRect rect = cg.zeroNhRect;
1250. 
1251.     selection_getbounds(sel, &rect);
1252. 
1253.     for (x = rect.lx; x <= rect.hx; x++)
1254.         for (y = rect.ly; y <= rect.hy; y++)
1255.             if (isok(x,y) && selection_getpoint(x, y, sel) && !cansee(x, y))
1256.                 return FALSE;
1257. 
1258.     return TRUE;
1259. }
1260. 
1261. /* selection_floofill callback to get all locations in a room */
1262. staticfn int
1263. dolookaround_floodfill_findroom(coordxy x, coordxy y)
1264. {
1265.     schar typ = levl[x][y].typ;
1266. 
1267.     if (IS_STWALL(typ) || IS_DOOR(typ) || IS_TREE(typ)
1268.         || IS_WATERWALL(typ) || typ == LAVAWALL || typ == IRONBARS
1269.         || typ == SCORR || typ == SDOOR || typ == DRAWBRIDGE_UP)
1270.         return FALSE;
1271.     return TRUE;
1272. }
1273. 
1274. /* describe the room at x,y */
1275. staticfn void
1276. lookaround_known_room(coordxy x, coordxy y)
1277. {
1278.     struct selectionvar *sel = selection_new();
1279.     int rmno = u.urooms[0] - ROOMOFFSET;
1280.     char qbuf[QBUFSZ];
1281. 
1282.     set_selection_floodfillchk(dolookaround_floodfill_findroom);
1283.     selection_floodfill(sel, x, y, TRUE);
1284. 
1285.     if (!u_at(x, y))
1286.         set_msg_xy(x, y);
1287. 
1288.     if (u_have_seen_whole_selection(sel)) {
1289.         boolean u_in = (boolean) selection_getpoint(x, y, sel);
1290. 
1291.         You("%s %s %s.",
1292.             u_at(x, y) && u_in && u_can_see_whole_selection(sel) ? "are in"
1293.             : (u_at(x, y)) ? "remember this as" : "remember that as",
1294.             an(selection_size_description(sel, qbuf)),
1295.             rmno >= 0 ? "room" : "area");
1296.     } else if (u_have_seen_bounds_selection(sel)) {
1297.         You("guess %s to be %s %s.",
1298.             u_at(x, y) ? "this" : "that",
1299.             an(selection_size_description(sel, qbuf)),
1300.             rmno >= 0 ? "room" : "area");
1301.     } else {
1302.         You("can't guess the size of %s area.",
1303.             u_at(x, y) ? "this" : "that");
1304.     }
1305.     selection_free(sel, TRUE);
1306. }
1307. 
1308. /* #lookaround - describe what the hero can see, in text */
1309. int
1310. dolookaround(void)
1311. {
1312.     coordxy x, y;
1313.     int tmp_getloc_filter = iflags.getloc_filter;
1314.     boolean tmp_accessiblemsg = a11y.accessiblemsg;
1315.     boolean corr_next2u = FALSE;
1316. 
1317.     a11y.accessiblemsg = TRUE;
1318.     if (levl[u.ux][u.uy].typ == CORR) {
1319.         /* In a corridor, mention corridors next to you. */
1320.         corr_next2u = TRUE;
1321.         /* TODO: if we know, describe where the corridor goes,
1322.            perhaps by describing the rooms? */
1323.     } else if (IS_DOOR(levl[u.ux][u.uy].typ)) {
1324.         /* In a doorway, describe the rooms next to you */
1325.         int i;
1326. 
1327.         for (i = DIR_W; i < N_DIRS; i += 2) {
1328.             x = u.ux + xdir[i];
1329.             y = u.uy + ydir[i];
1330.             if (isok(x, y) && IS_ROOM(levl[x][y].typ))
1331.                 lookaround_known_room(x, y);
1332.         }
1333.         corr_next2u = TRUE;
1334.     } else {
1335.         lookaround_known_room(u.ux, u.uy);
1336.     }
1337. 
1338.     /* TODO: maybe describe stuff outside the current room differently? */
1339. 
1340.     iflags.getloc_filter = GFILTER_VIEW;
1341.     for (y = 0; y < ROWNO; y++)
1342.         for (x = 1; x < COLNO; x++) {
1343.             int glyph, mapsym;
1344.             boolean iscorr = (corr_next2u
1345.                               && (glyph = glyph_at(x, y)) >= 0
1346.                               && glyph_is_cmap(glyph)
1347.                               && ((mapsym = glyph_to_cmap(glyph)) == S_corr
1348.                                    || mapsym == S_litcorr));
1349. 
1350.             if (!u_at(x, y)
1351.                 && (gather_locs_interesting(x, y, GLOC_INTERESTING)
1352.                     /* note: GLOC_INTERESTING catches S_engrcorr */
1353.                     || iscorr)) {
1354.                 char buf[BUFSZ];
1355.                 coord cc;
1356.                 int sym = 0;
1357.                 const char *firstmatch = 0;
1358. 
1359.                 cc.x = x, cc.y = y;
1360.                 do_screen_description(cc, TRUE, sym, buf, &firstmatch, NULL);
1361.                 pline_xy(x, y, "%s.", firstmatch);
1362.             }
1363.         }
1364. 
1365.     iflags.getloc_filter = tmp_getloc_filter;
1366.     a11y.accessiblemsg = tmp_accessiblemsg;
1367. 
1368.     return ECMD_OK;
1369. }
1370. 
1371. /* #toggle extended command
1372. 
1373.    BIND=':toggle(price_quotes)
1374.    BIND=@:toggle(autopickup) */
1375. int
1376. dotoggleoption(void)
1377. {
1378.     if (gc.cmd_bind && gc.cmd_bind->param) {
1379.         return toggle_bool_option(gc.cmd_bind->param);
1380.     } else {
1381.         pline("Use #optionsfull to set any option instead.");
1382.         return ECMD_OK;
1383.     }
1384. }
1385. 
1386. void
1387. set_move_cmd(int dir, int run)
1388. {
1389.     u.dz = zdir[dir];
1390.     u.dx = xdir[dir];
1391.     u.dy = ydir[dir];
1392.     /* #reqmenu -prefix disables autopickup during movement */
1393.     if (iflags.menu_requested)
1394.         svc.context.nopick = 1;
1395.     svc.context.travel = svc.context.travel1 = 0;
1396.     if (!gd.domove_attempting && !u.dz) {
1397.         svc.context.run = run;
1398.         gd.domove_attempting |= (!run ? DOMOVE_WALK : DOMOVE_RUSH);
1399.     }
1400. }
1401. 
1402. /* move or attack */
1403. int
1404. do_move_west(void)
1405. {
1406.     set_move_cmd(DIR_W, 0);
1407.     return ECMD_TIME;
1408. }
1409. 
1410. int
1411. do_move_northwest(void)
1412. {
1413.     set_move_cmd(DIR_NW, 0);
1414.     return ECMD_TIME;
1415. }
1416. 
1417. int
1418. do_move_north(void)
1419. {
1420.     set_move_cmd(DIR_N, 0);
1421.     return ECMD_TIME;
1422. }
1423. 
1424. int
1425. do_move_northeast(void)
1426. {
1427.     set_move_cmd(DIR_NE, 0);
1428.     return ECMD_TIME;
1429. }
1430. 
1431. int
1432. do_move_east(void)
1433. {
1434.     set_move_cmd(DIR_E, 0);
1435.     return ECMD_TIME;
1436. }
1437. 
1438. int
1439. do_move_southeast(void)
1440. {
1441.     set_move_cmd(DIR_SE, 0);
1442.     return ECMD_TIME;
1443. }
1444. 
1445. int
1446. do_move_south(void)
1447. {
1448.     set_move_cmd(DIR_S, 0);
1449.     return ECMD_TIME;
1450. }
1451. 
1452. int
1453. do_move_southwest(void)
1454. {
1455.     set_move_cmd(DIR_SW, 0);
1456.     return ECMD_TIME;
1457. }
1458. 
1459. /* rush */
1460. int
1461. do_rush_west(void)
1462. {
1463.     set_move_cmd(DIR_W, 3);
1464.     return ECMD_TIME;
1465. }
1466. 
1467. int
1468. do_rush_northwest(void)
1469. {
1470.     set_move_cmd(DIR_NW, 3);
1471.     return ECMD_TIME;
1472. }
1473. 
1474. int
1475. do_rush_north(void)
1476. {
1477.     set_move_cmd(DIR_N, 3);
1478.     return ECMD_TIME;
1479. }
1480. 
1481. int
1482. do_rush_northeast(void)
1483. {
1484.     set_move_cmd(DIR_NE, 3);
1485.     return ECMD_TIME;
1486. }
1487. 
1488. int
1489. do_rush_east(void)
1490. {
1491.     set_move_cmd(DIR_E, 3);
1492.     return ECMD_TIME;
1493. }
1494. 
1495. int
1496. do_rush_southeast(void)
1497. {
1498.     set_move_cmd(DIR_SE, 3);
1499.     return ECMD_TIME;
1500. }
1501. 
1502. int
1503. do_rush_south(void)
1504. {
1505.     set_move_cmd(DIR_S, 3);
1506.     return ECMD_TIME;
1507. }
1508. 
1509. int
1510. do_rush_southwest(void)
1511. {
1512.     set_move_cmd(DIR_SW, 3);
1513.     return ECMD_TIME;
1514. }
1515. 
1516. /* run */
1517. int
1518. do_run_west(void)
1519. {
1520.     set_move_cmd(DIR_W, 1);
1521.     return ECMD_TIME;
1522. }
1523. 
1524. int
1525. do_run_northwest(void)
1526. {
1527.     set_move_cmd(DIR_NW, 1);
1528.     return ECMD_TIME;
1529. }
1530. 
1531. int
1532. do_run_north(void)
1533. {
1534.     set_move_cmd(DIR_N, 1);
1535.     return ECMD_TIME;
1536. }
1537. 
1538. int
1539. do_run_northeast(void)
1540. {
1541.     set_move_cmd(DIR_NE, 1);
1542.     return ECMD_TIME;
1543. }
1544. 
1545. int
1546. do_run_east(void)
1547. {
1548.     set_move_cmd(DIR_E, 1);
1549.     return ECMD_TIME;
1550. }
1551. 
1552. int
1553. do_run_southeast(void)
1554. {
1555.     set_move_cmd(DIR_SE, 1);
1556.     return ECMD_TIME;
1557. }
1558. 
1559. int
1560. do_run_south(void)
1561. {
1562.     set_move_cmd(DIR_S, 1);
1563.     return ECMD_TIME;
1564. }
1565. 
1566. int
1567. do_run_southwest(void)
1568. {
1569.     set_move_cmd(DIR_SW, 1);
1570.     return ECMD_TIME;
1571. }
1572. 
1573. /* #reqmenu, prefix command to modify some others */
1574. int
1575. do_reqmenu(void)
1576. {
1577.     if (iflags.menu_requested) {
1578.         Norep("Double %s prefix, canceled.",
1579.               visctrl(cmd_from_func(do_reqmenu)));
1580.         iflags.menu_requested = FALSE;
1581.         return ECMD_CANCEL;
1582.     }
1583. 
1584.     iflags.menu_requested = TRUE;
1585.     return ECMD_OK;
1586. }
1587. 
1588. /* #rush */
1589. int
1590. do_rush(void)
1591. {
1592.     if ((gd.domove_attempting & DOMOVE_RUSH)) {
1593.         Norep("Double rush prefix, canceled.");
1594.         svc.context.run = 0;
1595.         gd.domove_attempting = 0;
1596.         return ECMD_CANCEL;
1597.     }
1598. 
1599.     svc.context.run = 2;
1600.     gd.domove_attempting |= DOMOVE_RUSH;
1601.     return ECMD_OK;
1602. }
1603. 
1604. /* #run */
1605. int
1606. do_run(void)
1607. {
1608.     if ((gd.domove_attempting & DOMOVE_RUSH)) {
1609.         Norep("Double run prefix, canceled.");
1610.         svc.context.run = 0;
1611.         gd.domove_attempting = 0;
1612.         return ECMD_CANCEL;
1613.     }
1614. 
1615.     svc.context.run = 3;
1616.     gd.domove_attempting |= DOMOVE_RUSH;
1617.     return ECMD_OK;
1618. }
1619. 
1620. /* #fight */
1621. int
1622. do_fight(void)
1623. {
1624.     if (svc.context.forcefight) {
1625.         Norep("Double fight prefix, canceled.");
1626.         svc.context.forcefight = 0;
1627.         gd.domove_attempting = 0;
1628.         return ECMD_CANCEL;
1629.     }
1630. 
1631.     svc.context.forcefight = 1;
1632.     gd.domove_attempting |= DOMOVE_WALK;
1633.     return ECMD_OK;
1634. }
1635. 
1636. /* #repeat */
1637. int
1638. do_repeat(void)
1639. {
1640.     int res = ECMD_OK;
1641. 
1642.     if (!gi.in_doagain) {
1643.         struct _cmd_queue *repeat_copy;
1644. 
1645.         if (!cmdq_peek(CQ_REPEAT)) {
1646.             Norep("There is no command available to repeat.");
1647.             return ECMD_FAIL;
1648.         }
1649.         repeat_copy = cmdq_copy(CQ_REPEAT);
1650.         gi.in_doagain = TRUE;
1651.         rhack(0); /* read and execute command */
1652.         gi.in_doagain = FALSE;
1653.         cmdq_clear(CQ_REPEAT);
1654.         gc.command_queue[CQ_REPEAT] = repeat_copy;
1655.         iflags.menu_requested = FALSE;
1656.         if (svc.context.move)
1657.             res = ECMD_TIME;
1658.     }
1659.     return res;
1660. }
1661. 
1662. /* extcmdlist: full command list, ordered by command name;
1663.    commands with no keystroke or with only a meta keystroke generally
1664.    need to be flagged as autocomplete and ones with a regular keystroke
1665.    or control keystroke generally should not be; there are a few exceptions
1666.    such as ^O/#overview and C/N/#name */
1667. struct ext_func_tab extcmdlist[] = {
1668.     { '#',    "#", "enter and perform an extended command",
1669.               doextcmd, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1670.     { M('?'), "?", "list all extended commands",
1671.               doextlist, IFBURIED | AUTOCOMPLETE | GENERALCMD | CMD_M_PREFIX,
1672.               NULL },
1673.     { M('a'), "adjust", "adjust inventory letters",
1674.               doorganize, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1675.     { M('A'), "annotate", "name current level",
1676.               donamelevel, IFBURIED | AUTOCOMPLETE | GENERALCMD | CMD_M_PREFIX, NULL },
1677.     { 'a',    "apply", "apply (use) a tool (pick-axe, key, lamp...)",
1678.               doapply, CMD_M_PREFIX, NULL },
1679.     { C('x'), "attributes", "show your attributes",
1680.               doattributes, IFBURIED | GENERALCMD, NULL },
1681.     { '@',    "autopickup", "toggle the 'autopickup' option on/off",
1682.               dotogglepickup, IFBURIED | GENERALCMD, NULL },
1683. #ifdef CRASHREPORT
1684.     { '\0',   "bugreport", "file a bug report",
1685.               dobugreport, GENERALCMD | NOFUZZERCMD, NULL },
1686. #endif
1687.     { 'C',    "call", "name a monster, specific object, or type of object",
1688.               docallcmd, IFBURIED | GENERALCMD, NULL },
1689.     { 'Z',    "cast", "zap (cast) a spell",
1690.               docast, IFBURIED, NULL },
1691.     { M('c'), "chat", "talk to someone",
1692.               dotalk, IFBURIED | AUTOCOMPLETE, NULL },
1693.     { 'v',    "chronicle", "show journal of major events",
1694.               do_gamelog, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1695.     { 'c',    "close", "close a door",
1696.               doclose, 0, NULL },
1697.     { M('C'), "conduct", "list voluntary challenges you have maintained",
1698.               doconduct, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1699.     { '\0',   "debugfuzzer", "start the fuzz tester",
1700.               wiz_fuzzer, IFBURIED | WIZMODECMD | NOFUZZERCMD, NULL },
1701.     { M('d'), "dip", "dip an object into something",
1702.               dodip, AUTOCOMPLETE | CMD_M_PREFIX, NULL },
1703.     { '>',    "down", "go down a staircase",
1704.               /* allows 'm' prefix (for move without autopickup) but not the
1705.                  g/G/F movement modifiers; not flagged as MOVEMENTCMD because
1706.                  that would suppress it from dokeylist output */
1707.               dodown, CMD_M_PREFIX, NULL },
1708.     { 'd',    "drop", "drop an item",
1709.               dodrop, 0, NULL },
1710.     { 'D',    "droptype", "drop specific item types",
1711.               doddrop, 0, NULL },
1712.     { 'e',    "eat", "eat something",
1713.               doeat, CMD_M_PREFIX, NULL },
1714.     { 'E',    "engrave", "engrave writing on the floor",
1715.               doengrave, 0, NULL },
1716.     { M('e'), "enhance", "advance or check weapon and spell skills",
1717.               enhance_weapon_skill, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1718.     /* #exploremode should be flagged AUTOCOMPETE but that would negatively
1719.        impact frequently used #enhance by making #e become ambiguous */
1720.     { M('X'), "exploremode", "enter explore (discovery) mode",
1721.               enter_explore_mode, IFBURIED | GENERALCMD | NOFUZZERCMD, NULL },
1722.     { 'F',    "fight", "prefix: force fight even if you don't see a monster",
1723.               do_fight, PREFIXCMD, NULL },
1724.     { 'f',    "fire", "fire ammunition from quiver",
1725.               dofire, 0, NULL },
1726.     { M('f'), "force", "force a lock",
1727.               doforce, AUTOCOMPLETE, NULL },
1728.     { M('g'), "genocided",
1729.               "list monsters that have been genocided or become extinct",
1730.               dogenocided,
1731.               IFBURIED | AUTOCOMPLETE | GENERALCMD | CMD_M_PREFIX, NULL },
1732.     { ';',    "glance", "show what type of thing a map symbol corresponds to",
1733.               doquickwhatis, IFBURIED | GENERALCMD, NULL },
1734.     { '?',    "help", "give a help message",
1735.               dohelp, IFBURIED | GENERALCMD, NULL },
1736.     { '\0',   "herecmdmenu", "show menu of commands you can do here",
1737.               doherecmdmenu, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1738.     { '\0',    "history", "show a summary of the game's development",
1739.               dohistory, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1740.     { 'i',    "inventory", "show your inventory",
1741.               ddoinv, IFBURIED | GENERALCMD, NULL },
1742.     { 'I',    "inventtype", "show inventory of one specific item class",
1743.               dotypeinv, IFBURIED | GENERALCMD, NULL },
1744.     { M('i'), "invoke", "invoke an object's special powers",
1745.               doinvoke, IFBURIED | AUTOCOMPLETE, NULL },
1746.     { M('j'), "jump", "jump to another location",
1747.               dojump, AUTOCOMPLETE, NULL },
1748.     { C('d'), "kick", "kick something",
1749.               dokick, 0, NULL },
1750.     { '\\',   "known", "show what object types have been discovered",
1751.               dodiscovered, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1752.     { '`',    "knownclass", "show discovered types for one class of objects",
1753.               doclassdisco, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1754.     { '\0',   "levelchange", "change experience level",
1755.               wiz_level_change, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1756.     { '\0',   "lightsources", "show mobile light sources",
1757.               wiz_light_sources, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1758.     { ':',    "look", "look at what is here",
1759.               dolook, IFBURIED, NULL },
1760.     { '\0',   "lookaround", "describe what you can see",
1761.               dolookaround, IFBURIED | GENERALCMD, NULL },
1762.     { M('l'), "loot", "loot a box on the floor",
1763.               doloot, AUTOCOMPLETE | CMD_M_PREFIX, NULL },
1764.     { '\0',   "migratemons",
1765. #ifdef DEBUG_MIGRATING_MONS
1766.               "show migrating monsters and migrate N random ones",
1767. #else
1768.               "show migrating monsters",
1769. #endif
1770.               wiz_migrate_mons, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1771.     { M('m'), "monster", "use monster's special ability",
1772.               domonability, IFBURIED | AUTOCOMPLETE, NULL },
1773.     { M('n'), "name", "same as call; name a monster or object or object type",
1774.               docallcmd, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1775.     { M('o'), "offer", "offer a sacrifice to the gods",
1776.               dosacrifice, AUTOCOMPLETE | CMD_M_PREFIX, NULL },
1777.     { 'o',    "open", "open a door",
1778.               doopen, 0, NULL },
1779.     /* 'm #options' runs doset() */
1780.     { 'O',    "options", "show option settings",
1781.               doset_simple, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1782.     /* 'm #optionsfull' runs doset_simple() */
1783.     { '\0',   "optionsfull", "show all option settings, possibly change them",
1784.               doset, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1785.     /* #overview used to need autocomplete and has retained that even
1786.        after being assigned to ^O [old wizard mode ^O is now #wizwhere];
1787.        'm' prefix displays overview as a menu where player can choose a
1788.        level to supply with an annotation */
1789.     { C('o'), "overview", "show a summary of the explored dungeon",
1790.               dooverview,
1791.               IFBURIED | AUTOCOMPLETE | GENERALCMD | CMD_M_PREFIX, NULL },
1792.     /* [should #panic actually autocomplete?] */
1793.     { '\0',   "panic", "test panic routine (fatal to game)",
1794.               wiz_panic, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1795.     { 'p',    "pay", "pay your shopping bill",
1796.               dopay, CMD_M_PREFIX, NULL },
1797.     { '|',    "perminv", "scroll persistent inventory display",
1798.               doperminv, IFBURIED | GENERALCMD | NOFUZZERCMD, NULL },
1799.     { ',',    "pickup", "pick up things at the current location",
1800.               dopickup, CMD_M_PREFIX, NULL },
1801.     { '\0',   "polyself", "polymorph self",
1802.               wiz_polyself, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1803.     { M('p'), "pray", "pray to the gods for help",
1804.               dopray, IFBURIED | AUTOCOMPLETE, NULL },
1805.     { C('p'), "prevmsg", "view recent game messages",
1806.               doprev_message, IFBURIED | GENERALCMD | CMD_INSANE, NULL },
1807.     { 'P',    "puton", "put on an accessory (ring, amulet, etc)",
1808.               doputon, 0, NULL },
1809.     { 'q',    "quaff", "quaff (drink) something",
1810.               dodrink, CMD_M_PREFIX, NULL },
1811.     { '\0',   "quit", "exit without saving current game",
1812.               done2, IFBURIED | AUTOCOMPLETE | GENERALCMD | NOFUZZERCMD,
1813.               NULL },
1814.     { 'Q',    "quiver", "select ammunition for quiver",
1815.               dowieldquiver, 0, NULL },
1816.     { 'r',    "read", "read a scroll or spellbook",
1817.               doread, 0, NULL },
1818.     { C('r'), "redraw", "redraw screen",
1819.               doredraw, IFBURIED | GENERALCMD | CMD_INSANE, NULL },
1820.     { 'R',    "remove", "remove an accessory (ring, amulet, etc)",
1821.               doremring, 0, NULL },
1822.     { C('a'), "repeat", "repeat a previous command",
1823.               do_repeat, IFBURIED | GENERALCMD, NULL },
1824.     /* "modify command" is a vague description for use as no-autopickup,
1825.        no-attack movement as well as miscellaneous non-movement things;
1826.        key2extcmddesc() constructs a more explicit two line description
1827.        for display by the '&' command and expects to find "prefix:" as
1828.        the start of the text here */
1829.     { 'm',    "reqmenu", "prefix: request menu or modify command",
1830.               do_reqmenu, PREFIXCMD, NULL },
1831.     { C('_'), "retravel", "travel to previously selected travel location",
1832.               dotravel_target, 0, NULL },
1833.     { M('R'), "ride", "mount or dismount a saddled steed",
1834.               doride, AUTOCOMPLETE, NULL },
1835.     { M('r'), "rub", "rub a lamp or a stone",
1836.               dorub, AUTOCOMPLETE, NULL },
1837.     { 'G',    "run", "prefix: run until something interesting is seen",
1838.               do_run, PREFIXCMD, NULL },
1839.     { 'g',    "rush", "prefix: rush until something interesting is seen",
1840.               do_rush, PREFIXCMD, NULL },
1841.     { 'S',    "save", "save the game and exit",
1842.               dosave, IFBURIED | GENERALCMD | NOFUZZERCMD, NULL },
1843.     { '\0',   "saveoptions", "save the game configuration",
1844.               do_write_config_file,
1845.               IFBURIED | GENERALCMD | NOFUZZERCMD, NULL },
1846.     { 's',    "search", "search for traps and secret doors",
1847.               dosearch, IFBURIED | CMD_M_PREFIX, "searching" },
1848.     { '*',    "seeall", "show all equipment in use",
1849.               doprinuse, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1850.     { AMULET_SYM, "seeamulet", "show the amulet currently worn",
1851.               dopramulet, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1852.     { ARMOR_SYM, "seearmor", "show the armor currently worn",
1853.               doprarm, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1854.     { RING_SYM, "seerings", "show the ring(s) currently worn",
1855.               doprring, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1856.     { TOOL_SYM, "seetools", "show the tools currently in use",
1857.               doprtool, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1858.     { WEAPON_SYM, "seeweapon", "show the weapon currently wielded",
1859.               doprwep, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1860.     { '!',    "shell",
1861.               "leave game to enter a sub-shell ('exit' to come back)",
1862.               dosh_core, (IFBURIED | GENERALCMD | NOFUZZERCMD
1863. #ifndef SHELL
1864.                         | CMD_NOT_AVAILABLE
1865. #endif /* SHELL */
1866.                         ), NULL },
1867.     /* $ is like ),=,&c but is not included with *, so not called "seegold" */
1868.     { GOLD_SYM, "showgold", "show gold, possibly shop credit or debt",
1869.               doprgold, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1870.     { SPBOOK_SYM, "showspells", "list and reorder known spells",
1871.               dovspell, IFBURIED | GENERALCMD, NULL },
1872.     { '^',    "showtrap", "describe an adjacent, discovered trap",
1873.               doidtrap, IFBURIED | GENERALCMD, NULL },
1874.     { M('s'), "sit", "sit down",
1875.               dosit, AUTOCOMPLETE, NULL },
1876.     { '\0',   "stats", "show memory statistics",
1877.               wiz_show_stats, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1878.     { C('z'), "suspend", "push game to background ('fg' to come back)",
1879.               dosuspend_core, (IFBURIED | GENERALCMD | NOFUZZERCMD
1880. #ifndef SUSPEND
1881.                                | CMD_NOT_AVAILABLE
1882. #endif /* SUSPEND */
1883.                                ), NULL },
1884.     { 'x',    "swap", "swap wielded and secondary weapons",
1885.               doswapweapon, 0, NULL },
1886.     { 'T',    "takeoff", "take off one piece of armor",
1887.               dotakeoff, 0, NULL },
1888.     { 'A',    "takeoffall", "remove all armor",
1889.               doddoremarm, 0, NULL },
1890.     { C('t'), "teleport", "teleport around the level",
1891.               dotelecmd, IFBURIED | CMD_M_PREFIX, NULL },
1892.     /* \177 ==  aka <delete> aka <rubout>; some terminals have an
1893.        option to swap it with <backspace> so if there's a key labeled
1894.        <delete> it may or may not actually invoke the #terrain command */
1895.     { '\177', "terrain",
1896.               "view map without monsters or objects obstructing it",
1897.               doterrain, IFBURIED | GENERALCMD | AUTOCOMPLETE, NULL },
1898.     { '\0',   "therecmdmenu",
1899.               "menu of commands you can do from here to adjacent spot",
1900.               dotherecmdmenu, AUTOCOMPLETE | GENERALCMD | MOUSECMD, NULL },
1901.     { 't',    "throw", "throw something",
1902.               dothrow, 0, NULL },
1903.     { '\0',   "timeout", "look at timeout queue and hero's timed intrinsics",
1904.               wiz_timeout_queue, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1905.     { M('T'), "tip", "empty a container",
1906.               dotip, AUTOCOMPLETE | CMD_M_PREFIX, NULL },
1907.     { '\0',   "toggle", "toggle boolean option",
1908.               dotoggleoption, IFBURIED | GENERALCMD | CMD_PARAM, NULL },
1909.     { '_',    "travel", "travel to a specific location on the map",
1910.               dotravel, CMD_M_PREFIX, NULL },
1911.     { M('t'), "turn", "turn undead away",
1912.               doturn, IFBURIED | AUTOCOMPLETE, NULL },
1913.     { 'X',    "twoweapon", "toggle two-weapon combat",
1914.               dotwoweapon, 0, NULL },
1915.     { M('u'), "untrap", "untrap something",
1916.               dountrap, AUTOCOMPLETE, NULL },
1917.     { '<',    "up", "go up a staircase",
1918.               /* (see comment for dodown() above */
1919.               doup, CMD_M_PREFIX, NULL },
1920.     { M('V'), "vanquished", "list vanquished monsters",
1921.               dovanquished,
1922.               IFBURIED | AUTOCOMPLETE | GENERALCMD | CMD_M_PREFIX, NULL },
1923.     { M('v'), "version",
1924.               "list compile time options for this version of NetHack",
1925.               doextversion, IFBURIED | AUTOCOMPLETE | GENERALCMD, NULL },
1926.     { 'V',    "versionshort", "show version and date+time program was built",
1927.               doversion, IFBURIED | GENERALCMD | CMD_M_PREFIX, NULL },
1928.     { '\0',   "vision", "show vision array",
1929.               wiz_show_vision, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1930.     { '.',    "wait", "rest one move while doing nothing",
1931.               donull, IFBURIED | CMD_M_PREFIX, "waiting" },
1932.     { 'W',    "wear", "wear a piece of armor",
1933.               dowear, 0, NULL },
1934.     { '&',    "whatdoes", "tell what a command does",
1935.               dowhatdoes, IFBURIED | GENERALCMD, NULL },
1936.     { '/',    "whatis", "show what type of thing a symbol corresponds to",
1937.               dowhatis, IFBURIED | GENERALCMD, NULL },
1938.     { 'w',    "wield", "wield (put in use) a weapon",
1939.               dowield, 0, NULL },
1940.     { M('w'), "wipe", "wipe off your face",
1941.               dowipe, AUTOCOMPLETE, NULL },
1942.     { '\0',   "wizborn", "show stats of monsters created",
1943.               doborn, IFBURIED | WIZMODECMD, NULL },
1944. #ifdef DEBUG
1945.     { '\0',   "wizbury", "bury objs under and around you",
1946.               wiz_debug_cmd_bury, IFBURIED | AUTOCOMPLETE | WIZMODECMD,
1947.               NULL },
1948. #endif
1949.     { '\0',   "wizcast", "cast any spell",
1950.               dowizcast, IFBURIED | WIZMODECMD, NULL },
1951.     { '\0',   "wizcustom", "show customized glyphs",
1952.               wiz_custom, IFBURIED | WIZMODECMD | NOFUZZERCMD, NULL },
1953.     { C('e'), "wizdetect", "reveal hidden things within a small radius",
1954.               wiz_detect, IFBURIED | WIZMODECMD, NULL },
1955. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED) || defined(DEBUG)
1956.     { '\0',   "wizdispmacros", "validate the display macro ranges",
1957.               wiz_display_macros, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1958. #endif
1959.     { '\0',   "wizfliplevel", "flip the level",
1960.               wiz_flip_level, IFBURIED | WIZMODECMD, NULL },
1961.     { C('g'), "wizgenesis", "create a monster",
1962.               wiz_genesis, IFBURIED | WIZMODECMD, NULL },
1963.     { C('i'), "wizidentify", "identify all items in inventory",
1964.               wiz_identify, IFBURIED | WIZMODECMD, NULL },
1965.     { '\0',   "wizintrinsic", "set an intrinsic",
1966.               wiz_intrinsic, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1967.     { '\0',   "wizkill", "slay a monster",
1968.               wiz_kill, (IFBURIED | AUTOCOMPLETE | WIZMODECMD
1969.                          | CMD_M_PREFIX | NOFUZZERCMD), NULL },
1970.     { C('v'), "wizlevelport", "teleport to another level",
1971.               wiz_level_tele, IFBURIED | WIZMODECMD | CMD_M_PREFIX, NULL },
1972.     { '\0',   "wizloaddes", "load and execute a des-file lua script",
1973.               wiz_load_splua, IFBURIED | WIZMODECMD | NOFUZZERCMD, NULL },
1974.     { '\0',   "wizloadlua", "load and execute a lua script",
1975.               wiz_load_lua, IFBURIED | WIZMODECMD | NOFUZZERCMD, NULL },
1976. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED) || defined(DEBUG)
1977.     { '\0',   "wizobjprobs", "list object generation probabilities",
1978.               wiz_objprobs, IFBURIED | WIZMODECMD, NULL },
1979. #endif
1980.     { '\0',   "wizmakemap", "recreate the current level",
1981.               wiz_makemap, IFBURIED | WIZMODECMD, NULL },
1982.     { C('f'), "wizmap", "map the level",
1983.               wiz_map, IFBURIED | WIZMODECMD, NULL },
1984. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED) || defined(DEBUG)
1985.     { '\0',   "wizmondiff", "validate the difficulty ratings of monsters",
1986.               wiz_mon_diff, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1987. #endif
1988.     { '\0',   "wizrumorcheck", "verify rumor boundaries",
1989.               wiz_rumor_check, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1990.     { '\0',   "wizseenv", "show map locations' seen vectors",
1991.               wiz_show_seenv, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1992.     { '\0', "wizshownhuuid", "show NHUUID for this game",
1993.               wiz_show_nhuuid, AUTOCOMPLETE | WIZMODECMD, NULL },
1994.     { '\0',   "wizsmell", "smell monster",
1995.               wiz_smell, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1996.     { '\0',   "wiztelekinesis", "telekinesis",
1997.               wiz_telekinesis, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
1998.     { '\0',   "wizwhere", "show locations of special levels",
1999.               wiz_where, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
2000.     { C('w'), "wizwish", "wish for something",
2001.               wiz_wish, IFBURIED | CMD_M_PREFIX | WIZMODECMD, NULL },
2002.     { '\0',   "wmode", "show wall modes",
2003.               wiz_show_wmodes, IFBURIED | AUTOCOMPLETE | WIZMODECMD, NULL },
2004.     { 'z',    "zap", "zap a wand",
2005.               dozap, 0, NULL },
2006.     /* movement commands will be bound by reset_commands() */
2007.     /* move or attack; accept m/g/G/F prefixes */
2008.     { '\0',   "movewest", "move west (screen left)",
2009.               do_move_west, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2010.     { '\0',   "movenorthwest", "move northwest (screen upper left)",
2011.               do_move_northwest, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2012.     { '\0',   "movenorth", "move north (screen up)",
2013.               do_move_north, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2014.     { '\0',   "movenortheast", "move northeast (screen upper right)",
2015.               do_move_northeast, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2016.     { '\0',   "moveeast", "move east (screen right)",
2017.               do_move_east, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2018.     { '\0',   "movesoutheast", "move southeast (screen lower right)",
2019.               do_move_southeast, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2020.     { '\0',   "movesouth", "move south (screen down)",
2021.               do_move_south, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2022.     { '\0',   "movesouthwest", "move southwest (screen lower left)",
2023.               do_move_southwest, MOVEMENTCMD | CMD_MOVE_PREFIXES, NULL },
2024.     /* rush; accept m prefix but not g/G/F */
2025.     { '\0',   "rushwest", "rush west (screen left)",
2026.               do_rush_west, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2027.     { '\0',   "rushnorthwest", "rush northwest (screen upper left)",
2028.               do_rush_northwest, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2029.     { '\0',   "rushnorth", "rush north (screen up)",
2030.               do_rush_north, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2031.     { '\0',   "rushnortheast", "rush northeast (screen upper right)",
2032.               do_rush_northeast, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2033.     { '\0',   "rusheast", "rush east (screen right)",
2034.               do_rush_east, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2035.     { '\0',   "rushsoutheast", "rush southeast (screen lower right)",
2036.               do_rush_southeast, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2037.     { '\0',   "rushsouth", "rush south (screen down)",
2038.               do_rush_south, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2039.     { '\0',   "rushsouthwest", "rush southwest (screen lower left)",
2040.               do_rush_southwest, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2041.     /* run; accept m prefix but not g/G/F */
2042.     { '\0',   "runwest", "run west (screen left)",
2043.               do_run_west, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2044.     { '\0',   "runnorthwest", "run northwest (screen upper left)",
2045.               do_run_northwest, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2046.     { '\0',   "runnorth", "run north (screen up)",
2047.               do_run_north, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2048.     { '\0',   "runnortheast", "run northeast (screen upper right)",
2049.               do_run_northeast, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2050.     { '\0',   "runeast", "run east (screen right)",
2051.               do_run_east, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2052.     { '\0',   "runsoutheast", "run southeast (screen lower right)",
2053.               do_run_southeast, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2054.     { '\0',   "runsouth", "run south (screen down)",
2055.               do_run_south, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2056.     { '\0',   "runsouthwest", "run southwest (screen lower left)",
2057.               do_run_southwest, MOVEMENTCMD | CMD_M_PREFIX, NULL },
2058. 
2059.     /* internal commands: only used by game core, not available for user */
2060.     { '\0', "clicklook", NULL, doclicklook, INTERNALCMD | MOUSECMD, NULL },
2061.     { '\0', "mouseaction", NULL, domouseaction, INTERNALCMD | MOUSECMD, NULL },
2062.     { '\0', "altadjust", NULL, adjust_split, INTERNALCMD, NULL },
2063.     { '\0', "altdip", NULL, dip_into, INTERNALCMD, NULL },
2064.     { '\0', "alttakeoff", NULL, ia_dotakeoff, INTERNALCMD, NULL },
2065.     { '\0', "altunwield", NULL, remarm_swapwep, INTERNALCMD, NULL },
2066.     { '\0', (char *) 0, (char *) 0, donull, 0, (char *) 0 } /* sentinel */
2067. };
2068. 
2069. /* mapping direction and move mode to extended command function */
2070. static int (*move_funcs[N_DIRS_Z][N_MOVEMODES])(void) = {
2071.     { do_move_west,      do_run_west,      do_rush_west },
2072.     { do_move_northwest, do_run_northwest, do_rush_northwest },
2073.     { do_move_north,     do_run_north,     do_rush_north },
2074.     { do_move_northeast, do_run_northeast, do_rush_northeast },
2075.     { do_move_east,      do_run_east,      do_rush_east },
2076.     { do_move_southeast, do_run_southeast, do_rush_southeast },
2077.     { do_move_south,     do_run_south,     do_rush_south },
2078.     { do_move_southwest, do_run_southwest, do_rush_southwest },
2079.     /* misleading; rush and run for down or up are rejected by rhack()
2080.        because dodown() and doup() lack the CMD_gGF_PREFIX flag */
2081.     { dodown,            dodown,           dodown },
2082.     { doup,              doup,             doup },
2083. };
2084. 
2085. /* used by dokeylist() and by key2extcmddesc() for dowhatdoes() */
2086. static const struct {
2087.     int nhkf;
2088.     const char *desc;
2089.     boolean numpad;
2090. } misc_keys[] = {
2091.     { NHKF_ESC, "cancel current prompt or pending prefix", FALSE },
2092.     { NHKF_COUNT,
2093.       "Prefix: for digits when preceding a command with a count", TRUE },
2094.     { 0, (const char *) 0, FALSE }
2095. };
2096. 
2097. static int extcmdlist_length = SIZE(extcmdlist) - 1;
2098. 
2099. /* get entry i in the extended commands list. for windowport use. */
2100. struct ext_func_tab *
2101. extcmds_getentry(int i)
2102. {
2103.     if (i < 0 || i > extcmdlist_length)
2104.         return 0;
2105.     return &extcmdlist[i];
2106. }
2107. 
2108. /* get the command bound to a key */
2109. staticfn struct Cmd_bind *
2110. cmdbind_get(uchar key)
2111. {
2112.     struct Cmd_bind *bind = gc.Cmd.cmdbinds;
2113. 
2114.     if (!key)
2115.         return NULL;
2116. 
2117.     while (bind) {
2118.         if (bind->key == key)
2119.             return bind;
2120.         bind = bind->next;
2121.     }
2122.     return bind;
2123. }
2124. 
2125. staticfn void
2126. cmdbind_add(uchar key, const struct ext_func_tab *extcmd, boolean user)
2127. {
2128.     struct Cmd_bind *bind = cmdbind_get(key);
2129. 
2130.     if (!key)
2131.         return;
2132.     if (!extcmd && bind) {
2133.         cmdbind_remove(key);
2134.         return;
2135.     }
2136. 
2137.     /* binding exists, set it to this command */
2138.     if (bind) {
2139.         bind->cmd = extcmd;
2140.         bind->userbind = user;
2141.         if (bind->param) {
2142.             free(bind->param);
2143.             bind->param = NULL;
2144.         }
2145.         return;
2146.     } else {
2147.         bind = (struct Cmd_bind *) alloc(sizeof(struct Cmd_bind));
2148.         bind->key = key;
2149.         bind->userbind = user;
2150.         bind->param = NULL;
2151.         bind->cmd = extcmd;
2152.         bind->next = gc.Cmd.cmdbinds;
2153.         gc.Cmd.cmdbinds = bind;
2154.     }
2155. }
2156. 
2157. staticfn void
2158. cmdbind_remove(uchar key)
2159. {
2160.     struct Cmd_bind *bind = gc.Cmd.cmdbinds;
2161.     struct Cmd_bind *prev = (struct Cmd_bind *) 0;
2162. 
2163.     while (bind) {
2164.         if (bind->key == key) {
2165.             if (prev)
2166.                 prev->next = bind->next;
2167.             else
2168.                 gc.Cmd.cmdbinds = bind->next;
2169.             if (bind->param)
2170.                 free(bind->param);
2171.             free(bind);
2172.             return;
2173.         }
2174.         prev = bind;
2175.         bind = bind->next;
2176.     }
2177. }
2178. 
2179. void
2180. cmdbind_freeall(void)
2181. {
2182.     struct Cmd_bind *next;
2183. 
2184.     while (gc.Cmd.cmdbinds) {
2185.         next = gc.Cmd.cmdbinds->next;
2186.         if (gc.Cmd.cmdbinds->param)
2187.             free(gc.Cmd.cmdbinds->param);
2188.         free(gc.Cmd.cmdbinds);
2189.         gc.Cmd.cmdbinds = next;
2190.     }
2191. }
2192. 
2193. /* swap key bindings for key1 and key2. both bindings must exist. */
2194. staticfn void
2195. cmdbind_swapkeys(uchar key1, uchar key2)
2196. {
2197.     struct Cmd_bind *bind1 = cmdbind_get(key1);
2198.     struct Cmd_bind *bind2 = cmdbind_get(key2);
2199. 
2200.     if (bind1 && bind2) {
2201.         bind1->key = key2;
2202.         bind2->key = key1;
2203.     }
2204. }
2205. 
2206. /* return number of extended commands bound to a non-default key */
2207. int
2208. count_bind_keys(void)
2209. {
2210.     struct Cmd_bind *bind = gc.Cmd.cmdbinds;
2211.     int i, nbinds = 0;
2212.     uchar keys[256];
2213. 
2214.     (void) memset(keys, 0, sizeof(uchar) * 256);
2215. 
2216.     /* commands bound to different key */
2217.     while (bind) {
2218.         keys[bind->key] = 1;
2219.         if (bind->userbind && bind->cmd && bind->cmd->key != bind->key) {
2220.             nbinds++;
2221.         }
2222.         bind = bind->next;
2223.     }
2224. 
2225.     /* commands which should be bound to a key, but aren't */
2226.     for (i = 0; i < extcmdlist_length; i++)
2227.         if (extcmdlist[i].key && !keys[extcmdlist[i].key])
2228.             nbinds++;
2229. 
2230.     return nbinds;
2231. }
2232. 
2233. /* show changed key bindings in text, or if sbuf is non-null, append to it */
2234. void
2235. get_changed_key_binds(strbuf_t *sbuf)
2236. {
2237.     winid win = WIN_ERR;
2238.     int i;
2239.     char buf[BUFSZ];
2240.     char buf2[QBUFSZ];
2241.     struct Cmd_bind *bind = gc.Cmd.cmdbinds;
2242.     uchar keys[256];
2243. 
2244.     (void) memset(keys, 0, sizeof(uchar) * 256);
2245. 
2246.     if (!sbuf)
2247.         win = create_nhwindow(NHW_TEXT);
2248. 
2249.     /* commands bound to different key */
2250.     while (bind) {
2251.         keys[bind->key] = 1;
2252.         if (bind->userbind && bind->cmd && bind->cmd->key != bind->key) {
2253.             if ((bind->cmd->flags & CMD_PARAM) != 0)
2254.                 Sprintf(buf, "BIND=%s:%s(%s)%s", key2txt(bind->key, buf2),
2255.                         bind->cmd->ef_txt,
2256.                         bind->param,
2257.                         sbuf ? "\n" : "");
2258.             else
2259.                 Sprintf(buf, "BIND=%s:%s%s", key2txt(bind->key, buf2),
2260.                         bind->cmd->ef_txt,
2261.                         sbuf ? "\n" : "");
2262.             if (sbuf)
2263.                 strbuf_append(sbuf, buf);
2264.             else
2265.                 putstr(win, 0, buf);
2266.         }
2267.         bind = bind->next;
2268.     }
2269. 
2270.     /* commands which should be bound to a key, but aren't */
2271.     for (i = 0; i < extcmdlist_length; i++) {
2272.         struct ext_func_tab *ec = &extcmdlist[i];
2273. 
2274.         if (ec->key && !keys[ec->key]) {
2275.             Sprintf(buf, "BIND=%s:nothing%s", key2txt(ec->key, buf2),
2276.                     sbuf ? "\n" : "");
2277.             if (sbuf)
2278.                 strbuf_append(sbuf, buf);
2279.             else
2280.                 putstr(win, 0, buf);
2281.         }
2282.     }
2283.     if (!sbuf) {
2284.         display_nhwindow(win, TRUE);
2285.         destroy_nhwindow(win);
2286.     }
2287. }
2288. 
2289. /* interactive key binding */
2290. staticfn void
2291. handler_rebind_keys_add(boolean keyfirst)
2292. {
2293.     struct ext_func_tab *ec;
2294.     winid win;
2295.     anything any;
2296.     int i, npick;
2297.     menu_item *picks = (menu_item *) 0;
2298.     char buf[BUFSZ];
2299.     char buf2[QBUFSZ];
2300.     uchar key = '\0';
2301.     int clr = NO_COLOR;
2302. 
2303.     if (keyfirst) {
2304.         pline("Bind which key? ");
2305.         key = pgetchar();
2306. 
2307.         if (!key || key == '\033')
2308.             return;
2309.     }
2310. 
2311.     win = create_nhwindow(NHW_MENU);
2312.     start_menu(win, MENU_BEHAVE_STANDARD);
2313.     any = cg.zeroany;
2314. 
2315.     if (key) {
2316.         struct Cmd_bind *bind = cmdbind_get(key);
2317. 
2318.         if (bind && bind->cmd) {
2319.             Sprintf(buf, "Key '%s' is currently bound to \"%s\".",
2320.                     key2txt(key, buf2), bind->cmd->ef_txt);
2321.         } else {
2322.             Sprintf(buf, "Key '%s' is not bound to anything.",
2323.                     key2txt(key, buf2));
2324.         }
2325.         add_menu_str(win, buf);
2326.         add_menu_str(win, "");
2327.     }
2328. 
2329.     any.a_int = -1;
2330.     add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr,
2331.              "nothing: unbind the key",
2332.              MENU_ITEMFLAGS_NONE);
2333. 
2334.     add_menu_str(win, "");
2335. 
2336.     for (i = 0; i < extcmdlist_length; i++) {
2337.         ec = &extcmdlist[i];
2338. 
2339.         if ((ec->flags & (MOVEMENTCMD|INTERNALCMD|CMD_NOT_AVAILABLE)) != 0)
2340.             continue;
2341. 
2342.         any.a_int = (i + 1);
2343.         Sprintf(buf, "%s: %s", ec->ef_txt, ec->ef_desc);
2344.         add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr, buf,
2345.              MENU_ITEMFLAGS_NONE);
2346.     }
2347.     if (key)
2348.         Sprintf(buf, "Bind '%s' to what command?", key2txt(key, buf2));
2349.     else
2350.         Sprintf(buf, "Bind what command?");
2351.     end_menu(win, buf);
2352.     npick = select_menu(win, PICK_ONE, &picks);
2353.     destroy_nhwindow(win);
2354.     if (npick > 0) {
2355.         struct Cmd_bind *prevcmd;
2356.         char cmdstr[BUFSZ];
2357. 
2358.         i = picks->item.a_int;
2359.         free((genericptr_t) picks);
2360. 
2361.         if (i == -1) {
2362.             ec = NULL;
2363.             Strcat(cmdstr, "nothing");
2364.             goto bindit;
2365.         } else {
2366.             ec = &extcmdlist[i-1];
2367. 
2368.             if ((ec->flags & CMD_PARAM) != 0) {
2369.                 char parambuf[BUFSZ];
2370.                 char querybuf[BUFSZ];
2371. 
2372.                 parambuf[0] = '\0';
2373.                 Sprintf(querybuf, "Command %s requires a parameter:", ec->ef_txt);
2374.                 getlin(querybuf, parambuf);
2375.                 (void) mungspaces(parambuf);
2376.                 Snprintf(cmdstr, BUFSZ-1, "%s(%s)", ec->ef_txt, parambuf);
2377.                 cmdstr[BUFSZ-1] = '\0';
2378.             } else {
2379.                 Strcat(cmdstr, ec->ef_txt);
2380.             }
2381.         }
2382.  bindit:
2383.         if (!key) {
2384.             pline("Bind which key? ");
2385.             key = pgetchar();
2386. 
2387.             if (!key || key == '\033')
2388.                 return;
2389.         }
2390. 
2391.         prevcmd = cmdbind_get(key);
2392. 
2393.         if (bind_key(key, cmdstr, TRUE)) {
2394.             if (prevcmd && prevcmd->cmd != ec) {
2395.                 pline("Changed key '%s' from \"%s\" to \"%s\".",
2396.                       key2txt(key, buf2), prevcmd->cmd->ef_txt, cmdstr);
2397.             } else if (!prevcmd) {
2398.                 pline("Bound key '%s' to \"%s\".",
2399.                       key2txt(key, buf2), cmdstr);
2400.             }
2401.         } else {
2402.             pline("Key binding failed?!");
2403.         }
2404.     }
2405. }
2406. 
2407. void
2408. handler_rebind_keys(void)
2409. {
2410.     winid win;
2411.     anything any;
2412.     int i, npick;
2413.     menu_item *picks = (menu_item *) 0;
2414.     int clr = NO_COLOR;
2415. 
2416.  redo_rebind:
2417.     win = create_nhwindow(NHW_MENU);
2418.     start_menu(win, MENU_BEHAVE_STANDARD);
2419.     any = cg.zeroany;
2420. 
2421.     any.a_int = 1;
2422.     add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr,
2423.              "bind key to a command", MENU_ITEMFLAGS_NONE);
2424.     any.a_int = 2;
2425.     add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr,
2426.              "bind command to a key", MENU_ITEMFLAGS_NONE);
2427.     if (count_bind_keys()) {
2428.         any.a_int = 3;
2429.         add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr,
2430.                  "view changed key binds", MENU_ITEMFLAGS_NONE);
2431.     }
2432.     end_menu(win, "Do what?");
2433.     npick = select_menu(win, PICK_ONE, &picks);
2434.     destroy_nhwindow(win);
2435.     if (npick > 0) {
2436.         i = picks->item.a_int;
2437.         free((genericptr_t) picks);
2438. 
2439.         if (i == 1 || i == 2) {
2440.             handler_rebind_keys_add((i == 1));
2441.         } else if (i == 3) {
2442.             get_changed_key_binds(NULL);
2443.         }
2444.         goto redo_rebind;
2445.     }
2446. }
2447. 
2448. void
2449. handler_change_autocompletions(void)
2450. {
2451.     winid win;
2452.     anything any;
2453.     int i, n;
2454.     menu_item *picks = (menu_item *) 0;
2455.     int clr = NO_COLOR;
2456.     struct ext_func_tab *ec;
2457.     char buf[BUFSZ];
2458. 
2459.     win = create_nhwindow(NHW_MENU);
2460.     start_menu(win, MENU_BEHAVE_STANDARD);
2461.     any = cg.zeroany;
2462. 
2463.     for (i = 0; i < extcmdlist_length; i++) {
2464.         ec = &extcmdlist[i];
2465. 
2466.         if ((ec->flags & (INTERNALCMD|CMD_NOT_AVAILABLE)) != 0)
2467.             continue;
2468.         if (strlen(ec->ef_txt) < 2)
2469.             continue;
2470. 
2471.         any.a_int = (i + 1);
2472.         Sprintf(buf, "%c %s: %s",
2473.                 (ec->flags & AUTOCOMP_ADJ) ? '*' : ' ',
2474.                 ec->ef_txt, ec->ef_desc);
2475.         add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr, buf,
2476.                  (ec->flags & AUTOCOMPLETE)
2477.                  ? MENU_ITEMFLAGS_SELECTED :
2478.                  MENU_ITEMFLAGS_NONE);
2479.     }
2480. 
2481.     end_menu(win, "Which commands autocomplete?");
2482.     n = select_menu(win, PICK_ANY, &picks);
2483.     if (n >= 0) {
2484.         int j;
2485. 
2486.         for (i = 0; i < extcmdlist_length; i++) {
2487.             boolean setit = FALSE;
2488. 
2489.             ec = &extcmdlist[i];
2490. 
2491.             if ((ec->flags & (INTERNALCMD|CMD_NOT_AVAILABLE)) != 0)
2492.                 continue;
2493.             if (strlen(ec->ef_txt) < 2)
2494.                 continue;
2495. 
2496.             Sprintf(buf, "%s", ec->ef_txt);
2497. 
2498.             for (j = 0; j < n; ++j) {
2499.                 if (ec == &extcmdlist[(picks[j].item.a_int - 1)]) {
2500.                     parseautocomplete(buf, TRUE);
2501.                     setit = TRUE;
2502.                     break;
2503.                 }
2504.             }
2505. 
2506.             if (!setit) {
2507.                 parseautocomplete(buf, FALSE);
2508.             }
2509.         }
2510.         if (n > 0)
2511.             free((genericptr_t) picks);
2512.     }
2513. 
2514.     destroy_nhwindow(win);
2515. }
2516. 
2517. /* find extended command entries matching findstr.
2518.    if findstr is NULL, returns all available entries.
2519.    returns: number of matching extended commands,
2520.             and the entry indexes in matchlist.
2521.    for windowport use. */
2522. int
2523. extcmds_match(const char *findstr, int ecmflags, int **matchlist)
2524. {
2525.     static int retmatchlist[SIZE(extcmdlist)] = DUMMY;
2526.     int i, mi = 0;
2527.     int fslen = findstr ? Strlen(findstr) : 0;
2528.     boolean ignoreac = (ecmflags & ECM_IGNOREAC) != 0;
2529.     boolean exactmatch = (ecmflags & ECM_EXACTMATCH) != 0;
2530.     boolean no1charcmd = (ecmflags & ECM_NO1CHARCMD) != 0;
2531. 
2532.     for (i = 0; extcmdlist[i].ef_txt; i++) {
2533.         if (extcmdlist[i].flags & (CMD_NOT_AVAILABLE|INTERNALCMD))
2534.             continue;
2535.         if (!wizard && (extcmdlist[i].flags & WIZMODECMD))
2536.             continue;
2537.         if (!ignoreac && !(extcmdlist[i].flags & AUTOCOMPLETE))
2538.             continue;
2539.         if (no1charcmd && (strlen(extcmdlist[i].ef_txt) == 1))
2540.             continue;
2541.         if (!findstr) {
2542.             retmatchlist[mi++] = i;
2543.         } else if (exactmatch) {
2544.             if (!strcmpi(findstr, extcmdlist[i].ef_txt)) {
2545.                 retmatchlist[mi++] = i;
2546.             }
2547.         } else {
2548.             if (!strncmpi(findstr, extcmdlist[i].ef_txt, fslen)) {
2549.                 retmatchlist[mi++] = i;
2550.             }
2551.         }
2552.     }
2553. 
2554.     if (matchlist)
2555.         *matchlist = retmatchlist;
2556. 
2557.     return mi;
2558. }
2559. 
2560. const char *
2561. key2extcmddesc(uchar key)
2562. {
2563.     static char key2cmdbuf[QBUFSZ];
2564.     const char *txt;
2565.     int k, i, j;
2566.     uchar M_5 = (uchar) M('5'), M_0 = (uchar) M('0');
2567.     struct Cmd_bind *cmdbind;
2568. 
2569.     /* need to check for movement commands before checking the extended
2570.        commands table because it contains entries for number_pad commands
2571.        that match !number_pad movement (like 'j' for "jump") */
2572.     key2cmdbuf[0] = '\0';
2573.     if (movecmd(k = key, MV_WALK))
2574.         Strcpy(key2cmdbuf, "move"); /* "move or attack"? */
2575.     else if (movecmd(k = key, MV_RUSH))
2576.         Strcpy(key2cmdbuf, "rush");
2577.     else if (movecmd(k = key, MV_RUN))
2578.         Strcpy(key2cmdbuf, "run");
2579.     if (digit(key) || (gc.Cmd.num_pad && digit(unmeta(key)))) {
2580.         key2cmdbuf[0] = '\0';
2581.         if (!gc.Cmd.num_pad)
2582.             Strcpy(key2cmdbuf, "start of, or continuation of, a count");
2583.         else if (key == '5' || key == M_5)
2584.             Sprintf(key2cmdbuf, "%s prefix",
2585.                     (!!gc.Cmd.pcHack_compat ^ (key == M_5)) ? "run" : "rush");
2586.         else if (key == '0' || (gc.Cmd.pcHack_compat && key == M_0))
2587.             Strcpy(key2cmdbuf, "synonym for 'i'");
2588.         if (*key2cmdbuf)
2589.             return key2cmdbuf;
2590.     }
2591.     /* check prefixes before regular commands; includes ^A pseudo-command */
2592.     for (i = 0; misc_keys[i].desc; ++i) {
2593.         if (misc_keys[i].numpad && !iflags.num_pad)
2594.             continue;
2595.         j = misc_keys[i].nhkf;
2596.         if (key == (uchar) gc.Cmd.spkeys[j])
2597.             return misc_keys[i].desc;
2598.     }
2599.     /* finally, check whether 'key' is a command */
2600.     if ((cmdbind = cmdbind_get(key)) != 0
2601.         && cmdbind->cmd
2602.         && (txt = cmdbind->cmd->ef_txt) != 0) {
2603.         Sprintf(key2cmdbuf, "%s (#%s)", cmdbind->cmd->ef_desc, txt);
2604. 
2605.         /* special case: for reqmenu prefix (normally 'm'), replace
2606.            "prefix: request menu or modify command (#reqmenu)"
2607.            with two-line "movement prefix:...\nnon-movement prefix:..." */
2608.         if (!strncmpi(key2cmdbuf, "prefix:", 7) && !strcmpi(txt, "reqmenu"))
2609.             (void) strsubst(key2cmdbuf, "prefix:",
2610.                      /* relies on implicit concatenation of literal strings */
2611.                             "movement prefix:"
2612.                             " move without autopickup and without attacking"
2613.                             "\n"
2614.                             "non-movement prefix:"); /* and rest of buf */
2615. 
2616.         /* another special case: 'txt' for '#' is "#" and showing that as
2617.            "perform an extended command (##)" looks silly; strip "(##)" off */
2618.         return strsubst(key2cmdbuf, " (##)", "");
2619.     }
2620.     return (char *) 0;
2621. }
2622. 
2623. boolean
2624. bind_mousebtn(int btn, const char *command)
2625. {
2626.     struct ext_func_tab *extcmd;
2627. 
2628.     if (btn < 1 || btn > NUM_MOUSE_BUTTONS) {
2629.         config_error_add("Wrong mouse button, valid are 1-%i",
2630.                          NUM_MOUSE_BUTTONS);
2631.         return FALSE;
2632.     }
2633.     btn--;
2634. 
2635.     /* special case: "nothing" is reserved for unbinding */
2636.     if (!strcmpi(command, "nothing")) {
2637.         gc.Cmd.mousebtn[btn] = (struct ext_func_tab *) 0;
2638.         return TRUE;
2639.     }
2640. 
2641.     for (extcmd = extcmdlist; extcmd->ef_txt; extcmd++) {
2642.         if (strcmpi(command, extcmd->ef_txt))
2643.             continue;
2644.         if (!(extcmd->flags & MOUSECMD))
2645.             continue;
2646.         gc.Cmd.mousebtn[btn] = extcmd;
2647. #if 0 /* silently accept key binding for unavailable command (!SHELL,&c) */
2648.         if ((extcmd->flags & CMD_NOT_AVAILABLE) != 0) {
2649.             char buf[BUFSZ];
2650. 
2651.             Sprintf(buf, cmdnotavail, extcmd->ef_txt);
2652.             config_error_add("%s", buf);
2653.         }
2654. #endif
2655.         return TRUE;
2656.     }
2657. 
2658.     return FALSE;
2659. }
2660. 
2661. boolean
2662. bind_key(uchar key, const char *command, boolean user)
2663. {
2664.     struct ext_func_tab *extcmd;
2665.     long len;
2666.     char *buf, *p = NULL, *lastp = NULL;
2667. 
2668.     /* special case: "nothing" is reserved for unbinding */
2669.     if (!strcmpi(command, "nothing")) {
2670.         cmdbind_remove(key);
2671.         return TRUE;
2672.     }
2673. 
2674.     /* copy command to buf for modification */
2675.     len = strlen(command) + 1;
2676.     buf = (char *)alloc(len);
2677.     (void) strncpy(buf, command, len);
2678. 
2679.     /* does buf have a parameter in parenthesis? */
2680.     if ((p = strchr(buf, '(')) != 0
2681.         && (lastp = strrchr(buf, ')')) != 0
2682.         && (lastp > p)) {
2683.         *p = '\0';
2684.         *lastp = '\0';
2685.         /* p points to the parameter */
2686.         p++;
2687.     }
2688. 
2689.     for (extcmd = extcmdlist; extcmd->ef_txt; extcmd++) {
2690.         if (strcmpi(buf, extcmd->ef_txt))
2691.             continue;
2692.         if ((extcmd->flags & INTERNALCMD) != 0)
2693.             continue;
2694.         cmdbind_add(key, extcmd, user);
2695. 
2696.         if ((extcmd->flags & CMD_PARAM) != 0) {
2697.             if (!p) {
2698.                 config_error_add("'%s' requires a parameter", buf);
2699.             } else {
2700.                 struct Cmd_bind *bind = cmdbind_get(key);
2701.                 int maxlen = min(30, strlen(p)) + 1;
2702. 
2703.                 if (maxlen <= 1) {
2704.                     config_error_add("Required parameter cannot be empty");
2705.                 } else {
2706.                     bind->param = (char *) alloc(maxlen);
2707.                     (void) strncpy(bind->param, p, maxlen);
2708.                     bind->param[maxlen-1] = '\0';
2709.                 }
2710.             }
2711.         } else if (p && strlen(p) > 0)
2712.             config_error_add("'%s' does not take a parameter", buf);
2713. 
2714. #if 0 /* silently accept key binding for unavailable command (!SHELL,&c) */
2715.         if ((extcmd->flags & CMD_NOT_AVAILABLE) != 0) {
2716.             char buf[BUFSZ];
2717. 
2718.             Sprintf(buf, cmdnotavail, extcmd->ef_txt);
2719.             config_error_add("%s", buf);
2720.         }
2721. #endif
2722.         free(buf);
2723.         return TRUE;
2724.     }
2725. 
2726.     free(buf);
2727.     return FALSE;
2728. }
2729. 
2730. /* bind key by ext cmd function */
2731. staticfn boolean
2732. bind_key_fn(uchar key, int (*fn)(void))
2733. {
2734.     struct ext_func_tab *extcmd;
2735. 
2736.     for (extcmd = extcmdlist; extcmd->ef_txt; extcmd++) {
2737.         if (extcmd->ef_funct != fn)
2738.             continue;
2739.         if ((extcmd->flags & INTERNALCMD) != 0)
2740.             continue;
2741.         cmdbind_add(key, extcmd, FALSE);
2742.         return TRUE;
2743.     }
2744. 
2745.     return FALSE;
2746. }
2747. 
2748. /* initialize all keyboard commands */
2749. staticfn void
2750. commands_init(void)
2751. {
2752.     struct ext_func_tab *extcmd;
2753. 
2754.     for (extcmd = extcmdlist; extcmd->ef_txt; extcmd++)
2755.         if (extcmd->key)
2756.             cmdbind_add(extcmd->key, extcmd, FALSE);
2757. 
2758.     (void) bind_mousebtn(1, "therecmdmenu");
2759.     (void) bind_mousebtn(2, "clicklook");
2760. 
2761.     /* number_pad */
2762.     (void) bind_key(C('l'), "redraw", FALSE);
2763.     (void) bind_key('h',    "help", FALSE);
2764.     (void) bind_key('j',    "jump", FALSE);
2765.     (void) bind_key('k',    "kick", FALSE);
2766.     (void) bind_key('l',    "loot", FALSE);
2767.     (void) bind_key(C('n'), "annotate", FALSE);
2768.     (void) bind_key('N',    "name", FALSE);
2769.     (void) bind_key('u',    "untrap", FALSE);
2770.     (void) bind_key('5',    "run", FALSE);
2771.     (void) bind_key(M('5'), "rush", FALSE);
2772.     (void) bind_key('-',    "fight", FALSE);
2773. 
2774.     /* alt keys: */
2775.     (void) bind_key(M('O'), "overview", FALSE);
2776.     (void) bind_key(M('2'), "twoweapon", FALSE);
2777.     (void) bind_key(M('N'), "name", FALSE);
2778. #if 0
2779.     /* don't do this until the rest_on_space option is set or cleared */
2780.     (void) bind_key(' ',    "wait", FALSE);
2781. #endif
2782. }
2783. 
2784. staticfn boolean
2785. keylist_func_has_key(const struct ext_func_tab *extcmd,
2786.                      boolean *skip_keys_used) /* boolean keys_used[256] */
2787. {
2788.     int i;
2789.     struct Cmd_bind *bind;
2790. 
2791.     for (i = 0; i < 256; ++i) {
2792.         if (skip_keys_used[i])
2793.             continue;
2794. 
2795.         if (((bind = cmdbind_get(i)) != 0) && (bind->cmd == extcmd))
2796.             return TRUE;
2797.     }
2798.     return FALSE;
2799. }
2800. 
2801. staticfn int
2802. keylist_putcmds(winid datawin, boolean docount,
2803.                 int incl_flags, int excl_flags,
2804.                 boolean *keys_used) /* boolean keys_used[256] */
2805. {
2806.     const struct ext_func_tab *extcmd;
2807.     int i;
2808.     char buf[BUFSZ], buf2[QBUFSZ];
2809.     boolean keys_already_used[256]; /* copy of keys_used[] before updates */
2810.     int count = 0;
2811.     struct Cmd_bind *bind;
2812. 
2813.     for (i = 0; i < 256; i++) {
2814.         uchar key = (uchar) i;
2815. 
2816.         keys_already_used[i] = keys_used[i];
2817.         if (keys_used[i])
2818.             continue;
2819.         if (key == ' ' && !flags.rest_on_space)
2820.             continue;
2821.         bind = cmdbind_get(key);
2822.         if (bind && bind->cmd != (struct ext_func_tab *) 0) {
2823.             if ((incl_flags && !(bind->cmd->flags & incl_flags))
2824.                 || (excl_flags && (bind->cmd->flags & excl_flags)))
2825.                 continue;
2826.             if (docount) {
2827.                 count++;
2828.                 continue;
2829.             }
2830.             if ((bind->cmd->flags & CMD_PARAM) != 0)
2831.                 Sprintf(buf, "%-7s %-13s %s \"%s\"", key2txt(key, buf2),
2832.                         bind->cmd->ef_txt, bind->cmd->ef_desc,
2833.                         bind->param);
2834.             else
2835.                 Sprintf(buf, "%-7s %-13s %s", key2txt(key, buf2),
2836.                         bind->cmd->ef_txt, bind->cmd->ef_desc);
2837.             putstr(datawin, 0, buf);
2838.             keys_used[i] = TRUE;
2839.         }
2840.     }
2841.     /* also list commands that lack key assignments; most are wizard mode */
2842.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd) {
2843.         if ((incl_flags && !(extcmd->flags & incl_flags))
2844.             || (excl_flags && (extcmd->flags & excl_flags)))
2845.             continue;
2846.         /* can't just check for non-Null extcmd->key; it holds the
2847.            default assignment and a user-specified binding might hijack
2848.            this command's default key for some other command; or this
2849.            command might have been assigned a key being used for
2850.            movement or as a prefix, intercepting that keystroke */
2851.         if (keylist_func_has_key(extcmd, keys_already_used))
2852.             continue;
2853.         /* found a command for current category without any key assignment */
2854.         if (docount) {
2855.             count++;
2856.             continue;
2857.         }
2858.         /* '#'+20 for one column here == 7+' '+13 for two columns above */
2859.         Sprintf(buf, "#%-20s %s", extcmd->ef_txt, extcmd->ef_desc);
2860.         putstr(datawin, 0, buf);
2861.     }
2862.     return count;
2863. }
2864. 
2865. /* list all keys and their bindings, like dat/hh but dynamic */
2866. void
2867. dokeylist(void)
2868. {
2869.     const struct ext_func_tab *extcmd;
2870.     winid datawin;
2871.     char buf[BUFSZ], buf2[BUFSZ];
2872.     uchar key;
2873.     boolean spkey_gap, keys_used[256], mov_seen[256];
2874.     int i, j, pfx_seen[256];
2875. 
2876.     (void) memset((genericptr_t) keys_used, 0, sizeof keys_used);
2877.     (void) memset((genericptr_t) pfx_seen, 0, sizeof pfx_seen);
2878. 
2879. #ifndef NO_SIGNAL
2880.     /* this is actually ambiguous; tty raw mode will override SIGINT;
2881.        when enabled, treat it like a movement command since assigning
2882.        other commands to this keystroke would be unwise... */
2883.     key = (uchar) C('c');
2884.     keys_used[key] = TRUE;
2885. #endif
2886. 
2887.     /* movement keys have been flagged in keys_used[]; clone them */
2888.     (void) memcpy((genericptr_t) mov_seen, (genericptr_t) keys_used,
2889.                   sizeof mov_seen);
2890. 
2891.     spkey_gap = FALSE;
2892.     for (i = 0; misc_keys[i].desc; ++i) {
2893.         if (misc_keys[i].numpad && !iflags.num_pad)
2894.             continue;
2895.         j = misc_keys[i].nhkf;
2896.         key = (uchar) gc.Cmd.spkeys[j];
2897.         if (key && !mov_seen[key] && !pfx_seen[key]) {
2898.             keys_used[key] = TRUE;
2899.             pfx_seen[key] = j;
2900.         } else
2901.             spkey_gap = TRUE;
2902.     }
2903. 
2904.     datawin = create_nhwindow(NHW_TEXT);
2905.     putstr(datawin, 0, "");
2906.     Sprintf(buf, "%7s %s", "", "    Full Current Key Bindings List");
2907.     putstr(datawin, 0, buf);
2908.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd)
2909.         if (spkey_gap || !keylist_func_has_key(extcmd, keys_used)) {
2910.             Sprintf(buf, "%7s %s", "",
2911.                                "(also commands with no key assignment)");
2912.             putstr(datawin, 0, buf);
2913.             break;
2914.         }
2915. 
2916.     /* directional keys */
2917.     putstr(datawin, 0, "");
2918.     putstr(datawin, 0, "Directional keys:");
2919.     show_direction_keys(datawin, '.', FALSE); /* '.'==self in direct'n grid */
2920. 
2921.     if (!iflags.num_pad) {
2922.         putstr(datawin, 0, "");
2923.         putstr(datawin, 0,
2924.      "Ctrl+<direction> will run in specified direction until something very");
2925.         Sprintf(buf, "%7s %s", "", "interesting is seen.");
2926.         putstr(datawin, 0, buf);
2927.         Strcpy(buf, "Shift"); /* append the rest below */
2928.     } else {
2929.         /* num_pad */
2930.         putstr(datawin, 0, "");
2931.         Strcpy(buf, "Meta"); /* append the rest next */
2932.     }
2933.     Strcat(buf,
2934.           "+<direction> will run in specified direction until you encounter");
2935.     putstr(datawin, 0, buf);
2936.     Sprintf(buf, "%7s %s", "", "an obstacle.");
2937.     putstr(datawin, 0, buf);
2938. 
2939.     putstr(datawin, 0, "");
2940.     putstr(datawin, 0, "Miscellaneous keys:");
2941.     for (i = 0; misc_keys[i].desc; ++i) {
2942.         if (misc_keys[i].numpad && !iflags.num_pad)
2943.             continue;
2944.         j = misc_keys[i].nhkf;
2945.         key = (uchar) gc.Cmd.spkeys[j];
2946.         if (key && !mov_seen[key]
2947.             && (pfx_seen[key] == j)) {
2948.             Sprintf(buf, "%-7s %s", key2txt(key, buf2), misc_keys[i].desc);
2949.             putstr(datawin, 0, buf);
2950.         }
2951.     }
2952.     /* (see above) */
2953.     key = (uchar) C('c');
2954. #ifndef NO_SIGNAL
2955.     /* last of the special keys */
2956.     Sprintf(buf, "%-7s", key2txt(key, buf2));
2957. #else
2958.     /* first of the keyless commands */
2959.     Sprintf(buf2, "[%s]", key2txt(key, buf));
2960.     Sprintf(buf, "%-21s", buf2);
2961. #endif
2962.     Strcat(buf, " interrupt: break out of NetHack (SIGINT)");
2963.     putstr(datawin, 0, buf);
2964.     /* keyless special key commands, if any */
2965.     if (spkey_gap) {
2966.         for (i = 0; misc_keys[i].desc; ++i) {
2967.             if (misc_keys[i].numpad && !iflags.num_pad)
2968.                 continue;
2969.             j = misc_keys[i].nhkf;
2970.             key = (uchar) gc.Cmd.spkeys[j];
2971.             if (!key || (pfx_seen[key] != j)) {
2972.                 Sprintf(buf2, "[%s]", spkey_name(j));
2973.                 /* lines up with the other unassigned commands which use
2974.                    "#%-20s ", but not with the other special keys */
2975.                 Snprintf(buf, sizeof(buf), "%-21s %s", buf2,
2976.                          misc_keys[i].desc);
2977.                 putstr(datawin, 0, buf);
2978.             }
2979.         }
2980.     }
2981. 
2982. #define IGNORECMD (WIZMODECMD | INTERNALCMD | MOVEMENTCMD)
2983. 
2984.     putstr(datawin, 0, "");
2985.     show_menu_controls(datawin, TRUE);
2986. 
2987.     if (keylist_putcmds(datawin, TRUE, GENERALCMD, IGNORECMD, keys_used)) {
2988.         putstr(datawin, 0, "");
2989.         putstr(datawin, 0, "General commands:");
2990.         (void) keylist_putcmds(datawin, FALSE, GENERALCMD,
2991.                                IGNORECMD, keys_used);
2992.     }
2993. 
2994.     if (keylist_putcmds(datawin, TRUE, 0, GENERALCMD | IGNORECMD, keys_used)) {
2995.         putstr(datawin, 0, "");
2996.         putstr(datawin, 0, "Game commands:");
2997.         (void) keylist_putcmds(datawin, FALSE, 0,
2998.                                GENERALCMD | IGNORECMD,
2999.                                keys_used);
3000.     }
3001. 
3002.     if (wizard && keylist_putcmds(datawin, TRUE,
3003.                                   WIZMODECMD, INTERNALCMD, keys_used)) {
3004.         putstr(datawin, 0, "");
3005.         putstr(datawin, 0, "Debug mode commands:");
3006.         (void) keylist_putcmds(datawin, FALSE,
3007.                                WIZMODECMD, INTERNALCMD, keys_used);
3008.     }
3009. 
3010.     display_nhwindow(datawin, FALSE);
3011.     destroy_nhwindow(datawin);
3012. #undef IGNORECMD
3013. }
3014. 
3015. const struct ext_func_tab *
3016. ext_func_tab_from_func(int (*fn)(void))
3017. {
3018.     const struct ext_func_tab *extcmd;
3019. 
3020.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd)
3021.         if (extcmd->ef_funct == fn)
3022.             return extcmd;
3023. 
3024.     return NULL;
3025. }
3026. 
3027. /* returns the key bound to a movement command for given DIR_ and MV_ mode */
3028. char
3029. cmd_from_dir(int dir, int mode)
3030. {
3031.     return cmd_from_func(move_funcs[dir][mode]);
3032. }
3033. 
3034. /* return the key bound to extended command */
3035. char
3036. cmd_from_func(int (*fn)(void))
3037. {
3038.     int i;
3039.     char ret = '\0';
3040.     struct Cmd_bind *bind;
3041. 
3042.     for (bind = gc.Cmd.cmdbinds; bind; bind = bind->next) {
3043.         i = bind->key;
3044.         /* skip space; we'll use it below as last resort if no other
3045.            keystroke invokes space's command */
3046.         if (i == ' ')
3047.             continue;
3048.         /* skip digits if number_pad is Off; also skip '-' unless it has
3049.            been bound to something other than what number_pad assigns */
3050.         if (((i >= '0' && i <= '9') || (i == '-' && fn == do_fight))
3051.             && !gc.Cmd.num_pad)
3052.             continue;
3053. 
3054.         if (bind->cmd && bind->cmd->ef_funct == fn) {
3055.             if (i >= ' ' && i <= '~')
3056.                 return (char) i;
3057.             else {
3058.                 ret = (char) i;
3059.             }
3060.         }
3061.     }
3062.     if ((bind = cmdbind_get(' ')) != 0 && bind->cmd
3063.         && bind->cmd->ef_funct == fn)
3064.         return ' ';
3065.     return ret;
3066. }
3067. 
3068. /* return visual interpretation of the key bound to extended command,
3069.    or the ext cmd name if not bound to any key. */
3070. char *
3071. cmd_from_ecname(const char *ecname)
3072. {
3073.     static char cmdnamebuf[QBUFSZ];
3074.     const struct ext_func_tab *extcmd;
3075. 
3076.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd)
3077.         if (!strcmp(extcmd->ef_txt, ecname)) {
3078.             char key = cmd_from_func(extcmd->ef_funct);
3079. 
3080.             if (key)
3081.                 Sprintf(cmdnamebuf, "%s", visctrl(key));
3082.             else
3083.                 Sprintf(cmdnamebuf, "#%s", ecname);
3084.             return cmdnamebuf;
3085.         }
3086. 
3087.     cmdnamebuf[0] = '\0';
3088.     return cmdnamebuf;
3089. }
3090. 
3091. const char *
3092. ecname_from_fn(int (*fn)(void))
3093. {
3094.     const struct ext_func_tab *extcmd, *cmdptr = 0;
3095. 
3096.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd)
3097.         if (extcmd->ef_funct == fn) {
3098.             cmdptr = extcmd;
3099.             return cmdptr->ef_txt;
3100.         }
3101.     return (char *) 0;
3102. }
3103. 
3104. /* return extended command name (without leading '#') for command (*fn)() */
3105. const char *
3106. cmdname_from_func(
3107.     int (*fn)(void),  /* function whose command name is wanted */
3108.     char outbuf[],    /* place to store the result */
3109.     boolean fullname) /* False: just enough to disambiguate */
3110. {
3111.     const struct ext_func_tab *extcmd, *cmdptr = 0;
3112.     const char *res = 0;
3113. 
3114.     for (extcmd = extcmdlist; extcmd->ef_txt; ++extcmd)
3115.         if (extcmd->ef_funct == fn) {
3116.             cmdptr = extcmd;
3117.             res = cmdptr->ef_txt;
3118.             break;
3119.         }
3120. 
3121.     if (!res) {
3122.         /* make sure output buffer doesn't contain junk or stale data;
3123.            return Null below */
3124.         outbuf[0] = '\0';
3125.     } else if (fullname) {
3126.         /* easy; the entire command name */
3127.         res = strcpy(outbuf, res);
3128.     } else {
3129.         const struct ext_func_tab *matchcmd = extcmdlist;
3130.         unsigned len = 0, maxlen = Strlen(res);
3131. 
3132.         /* find the shortest leading substring which is unambiguous */
3133.         do {
3134.             if (++len >= maxlen)
3135.                 break;
3136.             for (extcmd = matchcmd; extcmd->ef_txt; ++extcmd) {
3137.                 if (extcmd == cmdptr)
3138.                     continue;
3139.                 if ((extcmd->flags & CMD_NOT_AVAILABLE) != 0
3140.                     || ((extcmd->flags & WIZMODECMD) != 0 && !wizard))
3141.                     continue;
3142.                 if (!strncmp(res, extcmd->ef_txt, len)) {
3143.                     matchcmd = extcmd;
3144.                     break;
3145.                 }
3146.             }
3147.         } while (extcmd->ef_txt);
3148.         copynchars(outbuf, res, len);
3149.         /* [note: for Qt, this debugpline writes a couple dozen lines to
3150.             stdout during menu setup when message window isn't ready yet] */
3151.         debugpline2("shortened %s: \"%s\"", res, outbuf);
3152.         res = outbuf;
3153.     }
3154.     return res;
3155. }
3156. 
3157. static struct {
3158.     int nhkf;
3159.     uchar key;
3160.     const char *name;
3161. } const spkeys_binds[] = {
3162.     { NHKF_ESC,              '\033', (char *) 0 }, /* no binding */
3163.     { NHKF_GETDIR_SELF,      '.', "getdir.self" },
3164.     { NHKF_GETDIR_SELF2,     's', "getdir.self2" },
3165.     { NHKF_GETDIR_HELP,      '?', "getdir.help" },
3166.     { NHKF_GETDIR_MOUSE,     '_', "getdir.mouse" },
3167.     { NHKF_COUNT,            'n', "count" },
3168.     { NHKF_GETPOS_SELF,      '@', "getpos.self" },
3169.     { NHKF_GETPOS_PICK,      '.', "getpos.pick" },
3170.     { NHKF_GETPOS_PICK_Q,    ',', "getpos.pick.quick" },
3171.     { NHKF_GETPOS_PICK_O,    ';', "getpos.pick.once" },
3172.     { NHKF_GETPOS_PICK_V,    ':', "getpos.pick.verbose" },
3173.     { NHKF_GETPOS_SHOWVALID, '$', "getpos.valid" },
3174.     { NHKF_GETPOS_AUTODESC,  '#', "getpos.autodescribe" },
3175.     { NHKF_GETPOS_MON_NEXT,  'm', "getpos.mon.next" },
3176.     { NHKF_GETPOS_MON_PREV,  'M', "getpos.mon.prev" },
3177.     { NHKF_GETPOS_OBJ_NEXT,  'o', "getpos.obj.next" },
3178.     { NHKF_GETPOS_OBJ_PREV,  'O', "getpos.obj.prev" },
3179.     { NHKF_GETPOS_DOOR_NEXT, 'd', "getpos.door.next" },
3180.     { NHKF_GETPOS_DOOR_PREV, 'D', "getpos.door.prev" },
3181.     { NHKF_GETPOS_UNEX_NEXT, 'x', "getpos.unexplored.next" },
3182.     { NHKF_GETPOS_UNEX_PREV, 'X', "getpos.unexplored.prev" },
3183.     { NHKF_GETPOS_VALID_NEXT, 'z', "getpos.valid.next" },
3184.     { NHKF_GETPOS_VALID_PREV, 'Z', "getpos.valid.prev" },
3185.     { NHKF_GETPOS_INTERESTING_NEXT, 'a', "getpos.all.next" },
3186.     { NHKF_GETPOS_INTERESTING_PREV, 'A', "getpos.all.prev" },
3187.     { NHKF_GETPOS_HELP,      '?', "getpos.help" },
3188.     { NHKF_GETPOS_LIMITVIEW, '"', "getpos.filter" },
3189.     { NHKF_GETPOS_MOVESKIP,  '*', "getpos.moveskip" },
3190.     { NHKF_GETPOS_MENU,      '!', "getpos.menu" }
3191. };
3192. 
3193. boolean
3194. bind_specialkey(uchar key, const char *command)
3195. {
3196.     int i;
3197. 
3198.     for (i = 0; i < SIZE(spkeys_binds); i++) {
3199.         if (!spkeys_binds[i].name || strcmp(command, spkeys_binds[i].name))
3200.             continue;
3201.         gc.Cmd.spkeys[spkeys_binds[i].nhkf] = key;
3202.         return TRUE;
3203.     }
3204.     return FALSE;
3205. }
3206. 
3207. staticfn const char *
3208. spkey_name(int nhkf)
3209. {
3210.     const char *name = 0;
3211.     int i;
3212. 
3213.     for (i = 0; i < SIZE(spkeys_binds); i++) {
3214.         if (spkeys_binds[i].nhkf == nhkf) {
3215.             name = (nhkf == NHKF_ESC) ? "escape" : spkeys_binds[i].name;
3216.             break;
3217.         }
3218.     }
3219.     return name;
3220. }
3221. 
3222. /* returns the text for a one-byte encoding;
3223.  * must be shorter than a tab for proper formatting */
3224. char *
3225. key2txt(uchar c, char *txt) /* sufficiently long buffer */
3226. {
3227.     /* should probably switch to "SPC", "ESC", "RET"
3228.        since nethack's documentation uses ESC for <escape> */
3229.     if (c == ' ')
3230.         Sprintf(txt, "<space>");
3231.     else if (c == '\033')
3232.         Sprintf(txt, "<esc>"); /* "<escape>" won't fit */
3233.     else if (c == '\n')
3234.         Sprintf(txt, "<enter>"); /* "<return>" won't fit */
3235.     else if (c == '\177')
3236.         Sprintf(txt, ""); /* "<delete>" won't fit */
3237.     else
3238.         Strcpy(txt, visctrl((char) c));
3239.     return txt;
3240. }
3241. 
3242. 
3243. void
3244. parseautocomplete(char *autocomplete, boolean condition)
3245. {
3246.     struct ext_func_tab *efp;
3247.     char *autoc;
3248. 
3249.     /* break off first autocomplete from the rest; parse the rest */
3250.     if ((autoc = strchr(autocomplete, ',')) != 0
3251.         || (autoc = strchr(autocomplete, ':')) != 0) {
3252.         *autoc++ = '\0';
3253.         parseautocomplete(autoc, condition);
3254.     }
3255. 
3256.     /* strip leading and trailing white space */
3257.     autocomplete = trimspaces(autocomplete);
3258. 
3259.     if (!*autocomplete)
3260.         return;
3261. 
3262.     /* take off negation */
3263.     if (*autocomplete == '!') {
3264.         /* unlike most options, a leading "no" might actually be a part of
3265.          * the extended command.  Thus you have to use ! */
3266.         autocomplete++;
3267.         autocomplete = trimspaces(autocomplete);
3268.         condition = !condition;
3269.     }
3270. 
3271.     /* find and modify the extended command */
3272.     for (efp = extcmdlist; efp->ef_txt; efp++) {
3273.         if (!strcmp(autocomplete, efp->ef_txt)) {
3274.             if (condition == ((efp->flags & AUTOCOMPLETE) ? FALSE : TRUE)) {
3275.                 if ((efp->flags & AUTOCOMP_ADJ))
3276.                     efp->flags &= ~AUTOCOMP_ADJ;
3277.                 else
3278.                     efp->flags |= AUTOCOMP_ADJ;
3279.             }
3280.             if (condition)
3281.                 efp->flags |= AUTOCOMPLETE;
3282.             else
3283.                 efp->flags &= ~AUTOCOMPLETE;
3284.             return;
3285.         }
3286.     }
3287. 
3288.     /* not a real extended command */
3289.     raw_printf("Bad autocomplete: invalid extended command '%s'.",
3290.                autocomplete);
3291.     wait_synch();
3292. }
3293. 
3294. /* add changed autocompletions to the string buffer in config file format */
3295. void
3296. all_options_autocomplete(strbuf_t *sbuf)
3297. {
3298.     struct ext_func_tab *efp;
3299.     char buf[BUFSZ];
3300. 
3301.     for (efp = extcmdlist; efp->ef_txt; efp++)
3302.         if ((efp->flags & AUTOCOMP_ADJ) != 0) {
3303.             Sprintf(buf, "AUTOCOMPLETE=%s%s\n",
3304.                     (efp->flags & AUTOCOMPLETE) ? "" : "!",
3305.                     efp->ef_txt);
3306.             strbuf_append(sbuf, buf);
3307.         }
3308. }
3309. 
3310. /* return the number of changed autocompletions */
3311. int
3312. count_autocompletions(void)
3313. {
3314.     struct ext_func_tab *efp;
3315.     int n = 0;
3316. 
3317.     for (efp = extcmdlist; efp->ef_txt; efp++)
3318.         if ((efp->flags & AUTOCOMP_ADJ) != 0)
3319.             n++;
3320. 
3321.     return n;
3322. }
3323. 
3324. /* save&clear the mouse button actions, or restore the saved ones */
3325. void
3326. lock_mouse_buttons(boolean savebtns)
3327. {
3328.     static const struct ext_func_tab *mousebtn[NUM_MOUSE_BUTTONS] = { 0 };
3329.     int i;
3330. 
3331.     if (savebtns) {
3332.         for (i = 0; i < NUM_MOUSE_BUTTONS; i++) {
3333.             mousebtn[i] = gc.Cmd.mousebtn[i];
3334.             gc.Cmd.mousebtn[i] = NULL;
3335.         }
3336.     } else {
3337.         for (i = 0; i < NUM_MOUSE_BUTTONS; i++)
3338.             gc.Cmd.mousebtn[i] = mousebtn[i];
3339.     }
3340. }
3341. 
3342. /* called at startup and after number_pad is twiddled */
3343. void
3344. reset_commands(boolean initial)
3345. {
3346.     static const char sdir[] = "hykulnjb><",
3347.                       sdir_swap_yz[] = "hzkulnjb><",
3348.                       ndir[] = "47896321><",
3349.                       ndir_phone_layout[] = "41236987><";
3350.     static const int ylist[] = {
3351.         'y', 'Y', C('y'), M('y'), M('Y'), M(C('y'))
3352.     };
3353.     static struct ext_func_tab *back_dir_cmd[N_DIRS][N_MOVEMODES];
3354.     static uchar back_dir_key[N_DIRS][N_MOVEMODES];
3355.     static boolean backed_dir_cmd = FALSE;
3356.     boolean flagtemp;
3357.     int c, i, updated = 0;
3358.     int dir, mode;
3359. 
3360.     if (initial) {
3361.         updated = 1;
3362.         gc.Cmd.num_pad = FALSE;
3363.         gc.Cmd.pcHack_compat = gc.Cmd.phone_layout = gc.Cmd.swap_yz = FALSE;
3364.         for (i = 0; i < SIZE(spkeys_binds); i++)
3365.             gc.Cmd.spkeys[spkeys_binds[i].nhkf] = spkeys_binds[i].key;
3366.         commands_init();
3367.     } else {
3368.         if (backed_dir_cmd) {
3369.             for (dir = 0; dir < N_DIRS; dir++) {
3370.                 for (mode = 0; mode < N_MOVEMODES; mode++) {
3371.                     cmdbind_add(back_dir_key[dir][mode], back_dir_cmd[dir][mode], FALSE);
3372.                 }
3373.             }
3374.         }
3375. 
3376.         /* basic num_pad */
3377.         flagtemp = iflags.num_pad;
3378.         if (flagtemp != gc.Cmd.num_pad) {
3379.             gc.Cmd.num_pad = flagtemp;
3380.             ++updated;
3381.         }
3382.         /* swap_yz mode (only applicable for !num_pad); intended for
3383.            QWERTZ keyboard used in Central Europe, particularly Germany */
3384.         flagtemp = (iflags.num_pad_mode & 1) ? !gc.Cmd.num_pad : FALSE;
3385.         if (flagtemp != gc.Cmd.swap_yz) {
3386.             gc.Cmd.swap_yz = flagtemp;
3387.             ++updated;
3388.             /* FIXME? should Cmd.spkeys[] be scanned for y and/or z to swap?
3389.                Cmd.swap_yz has been toggled;
3390.                perform the swap (or reverse previous one) */
3391.             for (i = 0; i < SIZE(ylist); i++) {
3392.                 c = ylist[i] & 0xff;
3393.                 cmdbind_swapkeys(c, c + 1);
3394.             }
3395.         }
3396.         /* MSDOS compatibility mode (only applicable for num_pad) */
3397.         flagtemp = (iflags.num_pad_mode & 1) ? gc.Cmd.num_pad : FALSE;
3398.         if (flagtemp != gc.Cmd.pcHack_compat) {
3399.             gc.Cmd.pcHack_compat = flagtemp;
3400.             ++updated;
3401.             /* pcHack_compat has been toggled */
3402. #if 0
3403.             c = M('5') & 0xff;
3404.             cmdtmp = gc.Cmd.commands['5'];
3405.             gc.Cmd.commands['5'] = gc.Cmd.commands[c];
3406.             gc.Cmd.commands[c] = cmdtmp;
3407. #endif
3408.             /* FIXME: NHKF_DOINV2 ought to be implemented instead of this */
3409.             c = M('0') & 0xff;
3410.             if (gc.Cmd.pcHack_compat)
3411.                 cmdbind_add(c, ext_func_tab_from_func(dotypeinv), FALSE);
3412.             else
3413.                 cmdbind_remove(c);
3414.         }
3415.         /* phone keypad layout (only applicable for num_pad) */
3416.         flagtemp = (iflags.num_pad_mode & 2) ? gc.Cmd.num_pad : FALSE;
3417.         if (flagtemp != gc.Cmd.phone_layout) {
3418.             gc.Cmd.phone_layout = flagtemp;
3419.             ++updated;
3420.             /* phone_layout has been toggled */
3421.             for (i = 0; i < 3; i++) {
3422.                 c = '1' + i;             /* 1,2,3 <-> 7,8,9 */
3423.                 cmdbind_swapkeys(c, c + 6);
3424.                 c = (M('1') & 0xff) + i; /* M-1,M-2,M-3 <-> M-7,M-8,M-9 */
3425.                 cmdbind_swapkeys(c, c + 6);
3426.             }
3427.         }
3428.     } /*?initial*/
3429. 
3430.     /* choose updated movement keys */
3431.     if (updated)
3432.         gc.Cmd.serialno++;
3433.     gc.Cmd.dirchars = !gc.Cmd.num_pad
3434.                        ? (!gc.Cmd.swap_yz ? sdir : sdir_swap_yz)
3435.                        : (!gc.Cmd.phone_layout ? ndir : ndir_phone_layout);
3436.     gc.Cmd.alphadirchars = !gc.Cmd.num_pad ? gc.Cmd.dirchars : sdir;
3437. 
3438.     /* back up the commands & keys overwritten by new movement keys */
3439.     for (dir = 0; dir < N_DIRS; dir++) {
3440.         for (mode = MV_WALK; mode < N_MOVEMODES; mode++) {
3441.             uchar di = (uchar) gc.Cmd.dirchars[dir];
3442.             struct Cmd_bind *bind;
3443. 
3444.             if (!gc.Cmd.num_pad) {
3445.                 if (mode == MV_RUN) di = highc(di);
3446.                 else if (mode == MV_RUSH) di = C(di);
3447.             } else {
3448.                 if (mode == MV_RUN) di = M(di);
3449.                 else if (mode == MV_RUSH) di = M(di);
3450.             }
3451.             back_dir_key[dir][mode] = di;
3452.             if ((bind = cmdbind_get(di)) != 0)
3453.                 back_dir_cmd[dir][mode] = (struct ext_func_tab *) bind->cmd;
3454.             else
3455.                 back_dir_cmd[dir][mode] = (struct ext_func_tab *) 0;
3456.             cmdbind_remove(di);
3457.         }
3458.     }
3459.     backed_dir_cmd = TRUE;
3460. 
3461.     /* bind the new keys to movement commands */
3462.     for (i = 0; i < N_DIRS; i++) {
3463.         (void) bind_key_fn(gc.Cmd.dirchars[i], move_funcs[i][MV_WALK]);
3464.         if (!gc.Cmd.num_pad) {
3465.             (void) bind_key_fn(highc(gc.Cmd.dirchars[i]),
3466.                                move_funcs[i][MV_RUN]);
3467.             (void) bind_key_fn(C(gc.Cmd.dirchars[i]), move_funcs[i][MV_RUSH]);
3468.         } else {
3469.             /* M(number) works when altmeta is on */
3470.             (void) bind_key_fn(M(gc.Cmd.dirchars[i]), move_funcs[i][MV_RUN]);
3471.             /* can't bind highc() or C() of digits. just use the 5 prefix. */
3472.         }
3473.     }
3474.     update_rest_on_space();
3475.     gc.Cmd.extcmd_char = cmd_from_func(doextcmd);
3476. }
3477. 
3478. /* called when 'rest_on_space' is toggled, also called by reset_commands()
3479.    from initoptions_init() which takes place before key bindings have been
3480.    processed, and by initoptions_finish() after key bindings so that we
3481.    can remember anything bound to <space> in 'unrestonspace' */
3482. void
3483. update_rest_on_space(void)
3484. {
3485.     /* cloned from extcmdlist['.'], then slightly modified to be distinct;
3486.        donull is all that's needed for it to operate; command name and
3487.        description get shown by help menu's "Info on what a given key does"
3488.        (which runs the '&' command) and "Full list of keyboard commands" */
3489.     static const struct ext_func_tab restonspace = {
3490.         ' ', "wait", "rest one move via 'rest_on_space' option",
3491.         donull, (IFBURIED | CMD_M_PREFIX), "waiting"
3492.     };
3493.     static const struct ext_func_tab *unrestonspace = 0;
3494.     struct Cmd_bind *bind = cmdbind_get(' ');
3495. 
3496.     /* when 'rest_on_space' is On, <space> will run the #wait command;
3497.        when it is Off, <space> will use 'unrestonspace' which will either
3498.        be Null and elicit "Unknown command ' '." or have some non-Null
3499.        command bound in player's RC file */
3500.     if (bind && bind->cmd != &restonspace)
3501.         unrestonspace = bind->cmd;
3502.     cmdbind_add(' ', flags.rest_on_space ? &restonspace : unrestonspace, FALSE);
3503. }
3504. 
3505. /* commands which accept 'm' prefix to request menu operation or other
3506.    alternate behavior; it's also overloaded for move-without-autopickup;
3507.    there is no overlap between the two groups of commands */
3508. staticfn boolean
3509. accept_menu_prefix(const struct ext_func_tab *ec)
3510. {
3511.     return (ec && ((ec->flags & CMD_M_PREFIX) != 0));
3512. }
3513. 
3514. /* choose a random character, biased towards movement commands, primarily
3515.    for debug-fuzzer testing */
3516. char
3517. randomkey(void)
3518. {
3519.     static unsigned i = 0;
3520.     static char last_c = '\0';
3521.     char c;
3522. 
3523.     /* give ^A and ^P a high probability of being repeated */
3524.     if ((last_c == C('a') || last_c == C('p'))
3525.         && program_state.input_state == commandInp && rn2(5))
3526.         return last_c;
3527. 
3528.     switch (rn2(16)) {
3529.     default:
3530.         c = '\033';
3531.         break;
3532.     case 0:
3533.         c = '\n';
3534.         break;
3535.     case 1:
3536.     case 2:
3537.     case 3:
3538.     case 4:
3539.         c = (char) rn1('~' - ' ' + 1, ' ');
3540.         break;
3541.     case 5:
3542.         c = (char) (rn2(2) ? '\t' : ' ');
3543.         break;
3544.     case 6:
3545.         c = (char) rn1('z' - 'a' + 1, 'a');
3546.         break;
3547.     case 7:
3548.         c = (char) rn1('Z' - 'A' + 1, 'A');
3549.         break;
3550.     case 8:
3551.         c = extcmdlist[i++ % SIZE(extcmdlist)].key;
3552.         break;
3553.     case 9:
3554.         c = '#';
3555.         break;
3556.     case 10:
3557.     case 11:
3558.     case 12:
3559.         {
3560.             int d = rn2(N_DIRS);
3561.             int m = rn2(7) ? MV_WALK : (!rn2(3) ? MV_RUSH : MV_RUN);
3562. 
3563.             c = cmd_from_dir(d, m);
3564.         }
3565.         break;
3566.     case 13:
3567.         c = (char) rn1('9' - '0' + 1, '0');
3568.         break;
3569.     case 14:
3570.         /* any char, but avoid '\0' because it's used for mouse click */
3571.         c = (char) rnd(iflags.wc_eight_bit_input ? 255 : 127);
3572.         break;
3573.     }
3574. 
3575.     if (program_state.input_state == commandInp)
3576.         last_c = c;
3577.     return c;
3578. }
3579. 
3580. void
3581. random_response(char *buf, int sz)
3582. {
3583.     char c;
3584.     int count = 0;
3585. 
3586.     for (;;) {
3587.         c = randomkey();
3588.         if (c == '\n')
3589.             break;
3590.         if (c == '\033') {
3591.             count = 0;
3592.             break;
3593.         }
3594.         if (count < sz - 1)
3595.             buf[count++] = c;
3596.     }
3597.     buf[count] = '\0';
3598. }
3599. 
3600. int
3601. rnd_extcmd_idx(void)
3602. {
3603.     return rn2(extcmdlist_length + 1) - 1;
3604. }
3605. 
3606. staticfn void
3607. reset_cmd_vars(boolean reset_cmdq)
3608. {
3609.     svc.context.run = 0;
3610.     svc.context.nopick = svc.context.forcefight = FALSE;
3611.     svc.context.move = svc.context.mv = FALSE;
3612.     gd.domove_attempting = 0;
3613.     gm.multi = 0;
3614.     iflags.menu_requested = FALSE;
3615.     svc.context.travel = svc.context.travel1 = 0;
3616.     if (gt.travelmap) {
3617.         selection_free(gt.travelmap, TRUE);
3618.         gt.travelmap = NULL;
3619.     }
3620.     if (reset_cmdq) {
3621.         cmdq_clear(CQ_CANNED);
3622.         cmdq_clear(CQ_REPEAT);
3623.     }
3624. }
3625. 
3626. void
3627. rhack(int key)
3628. {
3629.     boolean bad_command, firsttime = (key == 0);
3630.     struct _cmd_queue cq, *cmdq = NULL;
3631.     const struct ext_func_tab *cmdq_ec = 0, *prefix_seen = 0;
3632.     boolean was_m_prefix = FALSE;
3633.     int (*func)(void) = dummyfunction;
3634. 
3635.     iflags.menu_requested = FALSE;
3636.     svc.context.nopick = 0;
3637.  got_prefix_input:
3638. #ifdef SAFERHANGUP
3639.     if (program_state.done_hup)
3640.         end_of_input();
3641. #endif
3642.     if ((cmdq = cmdq_pop()) != 0) {
3643.         /* doing queued commands */
3644.         cq = *cmdq;
3645.         free(cmdq);
3646.         if (cq.typ == CMDQ_EXTCMD && (cmdq_ec = cq.ec_entry) != 0)
3647.             goto do_cmdq_extcmd;
3648.         /* already handled a queued command (goto do_cmdq_extcmd);
3649.            if something other than a key is queued, we'll drop down
3650.            to the !*cmd handling which clears out the command-queue */
3651.         key = (cq.typ == CMDQ_KEY) ? cq.key : 0;
3652.     } else if (firsttime) {
3653.         key = parse();
3654.         /* parse() pushed a cmd but didn't return any key */
3655.         if (!key && cmdq_peek(CQ_CANNED))
3656.             goto got_prefix_input;
3657.     }
3658. 
3659.     /* if there's no command, there's nothing to do except reset */
3660.     if (!key || key == (char) 0377
3661.         || key == gc.Cmd.spkeys[NHKF_ESC]) {
3662.         if (key == gc.Cmd.spkeys[NHKF_ESC])
3663.             /* don't perform next sanity check if player typed ESC for
3664.                the current command, similar to handling for CMD_INSANE
3665.                flag below (^P and ^R) */
3666.             iflags.sanity_no_check = iflags.sanity_check;
3667.         else
3668.             nhbell();
3669.         reset_cmd_vars(TRUE);
3670.         return;
3671.     }
3672. 
3673.     /* handle most movement commands */
3674.     svc.context.travel = svc.context.travel1 = 0;
3675.     {
3676.         const struct ext_func_tab *tlist;
3677.         int res;
3678. 
3679.         gc.cmd_bind = cmdbind_get(key & 0xFF);
3680. 
3681.  do_cmdq_extcmd:
3682.         if (cmdq_ec)
3683.             tlist = cmdq_ec;
3684.         else
3685.             tlist = gc.cmd_bind ? gc.cmd_bind->cmd : NULL;
3686. 
3687.         /* current - use key to directly index cmdlist array */
3688.         if (tlist != 0) {
3689.             if (!can_do_extcmd(tlist)) {
3690.                 /* can_do_extcmd() already gave a message */
3691.                 reset_cmd_vars(TRUE);
3692.                 res = ECMD_OK;
3693.             } else if (prefix_seen && !(tlist->flags & PREFIXCMD)
3694.                        && !(tlist->flags & (was_m_prefix ? CMD_M_PREFIX
3695.                                                          : CMD_gGF_PREFIX))) {
3696.                 char pfxidx = cmd_from_func(prefix_seen->ef_funct);
3697.                 const char *which = (pfxidx != 0) ? visctrl(pfxidx)
3698.                                     : (prefix_seen->ef_funct == do_reqmenu)
3699.                                       ? "move-no-pickup or request-menu"
3700.                                       : prefix_seen->ef_txt;
3701. 
3702.                 /*
3703.                  * We got a prefix previously and looped for another
3704.                  * command instead of returning, but the command we got
3705.                  * doesn't accept a prefix.  The feedback here supersedes
3706.                  * the former call to help_dir() (for 'bad_command' below).
3707.                  */
3708.                 if (was_m_prefix) {
3709.                     custompline(SUPPRESS_HISTORY,
3710.                           "The %s command does not accept '%s' prefix.",
3711.                           tlist->ef_txt, which);
3712.                 } else {
3713.                     uchar ch = tlist->key;
3714.                     boolean up = (ch == '<' || tlist->ef_funct == doup),
3715.                             down = (ch == '>' || tlist->ef_funct == dodown);
3716. 
3717.                     pline(
3718.                 "The '%s' prefix should be followed by a movement command%s.",
3719.                           which,
3720.                           (up || down) ? " other than up or down" : "");
3721.                 }
3722.                 res = ECMD_FAIL;
3723.                 prefix_seen = 0;
3724.             } else {
3725.                 /* we discard 'const' because some compilers seem to have
3726.                    trouble with the pointer passed to set_occupation() */
3727.                 func = ((struct ext_func_tab *) tlist)->ef_funct;
3728.                 if (tlist->f_text && !go.occupation && gm.multi)
3729.                     set_occupation(func, tlist->f_text, gm.multi);
3730.                 ge.ext_tlist = NULL;
3731. 
3732.                 if (!gi.in_doagain && func != do_repeat && func != doextcmd) {
3733.                     if (!prefix_seen)
3734.                         cmdq_clear(CQ_REPEAT);
3735.                     cmdq_add_ec(CQ_REPEAT,
3736.                                 ((struct ext_func_tab *) tlist)->ef_funct);
3737.                 } else {
3738.                     if (func == doextcmd) {
3739.                         cmdq_clear(CQ_REPEAT);
3740.                     }
3741.                 }
3742.                 /* some commands shouldn't trigger sanity_check() because
3743.                    if it produces output that might interfere with them;
3744.                    note: if sanity_check is False, this has no effect */
3745.                 if ((tlist->flags & CMD_INSANE) != 0)
3746.                     iflags.sanity_no_check = iflags.sanity_check;
3747. 
3748.                 res = (*func)(); /* perform the command */
3749.                 /* if 'func' is doextcmd(), 'tlist' is for Cmd.commands['#']
3750.                    rather than for the command that doextcmd() just ran;
3751.                    doextcmd() notifies us what that was via ext_tlist;
3752.                    other commands leave it Null */
3753.                 if (ge.ext_tlist) {
3754.                     tlist = ge.ext_tlist, ge.ext_tlist = NULL;
3755.                     /* Add the command post-execution */
3756.                     cmdq_add_ec(CQ_REPEAT,
3757.                                 ((struct ext_func_tab *) tlist)->ef_funct);
3758.                     /* shift the command to first */
3759.                     cmdq_shift(CQ_REPEAT);
3760.                 }
3761. 
3762.                 if ((tlist->flags & PREFIXCMD) != 0) {
3763.                     /* it was a prefix command, mark and get another cmd */
3764.                     if ((res & ECMD_CANCEL) != 0) {
3765.                         /* prefix commands cancel if pressed twice */
3766.                         reset_cmd_vars(TRUE);
3767.                         return;
3768.                     }
3769.                     prefix_seen = tlist;
3770.                     cmdq_ec = NULL;
3771.                     if (func == do_reqmenu)
3772.                         was_m_prefix = TRUE;
3773.                     goto got_prefix_input;
3774.                 } else if (!(tlist->flags & MOVEMENTCMD)
3775.                            && gd.domove_attempting) {
3776.                     /* not a movement command, but a move prefix earlier? */
3777.                     ; /* just do nothing */
3778.                 } else if (((gd.domove_attempting
3779.                              & (DOMOVE_RUSH | DOMOVE_WALK)) != 0L)
3780.                            && !svc.context.travel && !dxdy_moveok()) {
3781.                     /* trying to move diagonally as a grid bug */
3782.                     You_cant("get there from here...");
3783.                     reset_cmd_vars(TRUE);
3784.                     return;
3785.                 } else if ((gd.domove_attempting & DOMOVE_WALK) != 0L) {
3786.                     if (gm.multi)
3787.                         svc.context.mv = TRUE;
3788.                     domove();
3789.                     svc.context.forcefight = 0;
3790.                     iflags.menu_requested = FALSE;
3791.                     return;
3792.                 } else if ((gd.domove_attempting & DOMOVE_RUSH) != 0L) {
3793.                     if (firsttime) {
3794.                         if (!gm.multi)
3795.                             gm.multi = max(COLNO, ROWNO);
3796.                         u.last_str_turn = 0;
3797.                     }
3798.                     svc.context.mv = TRUE;
3799.                     domove();
3800.                     iflags.menu_requested = FALSE;
3801.                     return;
3802.                 }
3803.                 prefix_seen = 0;
3804.             }
3805.             /* it is possible to have a result of (ECMD_TIME|ECMD_CANCEL)
3806.                [for example, using 'f'ire, manually filling quiver with
3807.                wielded weapon or dual-wielded swap-weapon, then cancelling
3808.                at the direction prompt; using time to unwield should take
3809.                precedence over general cancellation] */
3810.             if ((res & (ECMD_CANCEL | ECMD_FAIL)) != 0) {
3811.                 /* command was canceled by user, maybe they declined to
3812.                    pick an object to act on, or command failed to finish */
3813.                 reset_cmd_vars(TRUE);
3814.             } else if ((res & (ECMD_OK | ECMD_TIME)) == ECMD_OK) {
3815.                 reset_cmd_vars(gm.multi < 0);
3816.             }
3817.             /* reset_cmd_vars() sets context.move to False so we might
3818.                need to change it [back] to True */
3819.             if ((res & ECMD_TIME) != 0) {
3820.                 svc.context.move = TRUE;
3821.                 if (func != dokick) {
3822.                     /* hero did something else than kicking a location;
3823.                        reset the location, so pets don't avoid it */
3824.                     gk.kickedloc.x = 0, gk.kickedloc.y = 0;
3825.                 }
3826.             }
3827.             return;
3828.         }
3829.         /* if we reach here, cmd wasn't found in cmdlist[] */
3830.         bad_command = TRUE;
3831.     }
3832. 
3833.     if (bad_command) {
3834.         custompline(SUPPRESS_HISTORY, "Unknown command '%s'.", visctrl(key));
3835.         cmdq_clear(CQ_CANNED);
3836.         cmdq_clear(CQ_REPEAT);
3837.         iflags.sanity_no_check = iflags.sanity_check; /* skip sanity check */
3838.     }
3839.     /* didn't move */
3840.     svc.context.move = FALSE;
3841.     gm.multi = 0;
3842.     return;
3843. }
3844. 
3845. /* convert an x,y pair into a direction code */
3846. int
3847. xytodir(int x, int y)
3848. {
3849.     int dd;
3850. 
3851.     for (dd = 0; dd < N_DIRS; dd++)
3852.         if (x == xdir[dd] && y == ydir[dd])
3853.             return dd;
3854.     return DIR_ERR;
3855. }
3856. 
3857. /* convert a direction code into an x,y pair */
3858. void
3859. dirtocoord(coord *cc, int dd)
3860. {
3861.     if (dd > DIR_ERR && dd < N_DIRS_Z) {
3862.         cc->x = xdir[dd];
3863.         cc->y = ydir[dd];
3864.     }
3865. }
3866. 
3867. /* also sets u.dz, but returns false for <> */
3868. int
3869. movecmd(char sym, int mode)
3870. {
3871.     int d = DIR_ERR;
3872.     struct Cmd_bind *bind = cmdbind_get(sym);
3873. 
3874.     if (bind && bind->cmd) {
3875.         int (*fnc)(void) = bind->cmd->ef_funct;
3876. 
3877.         if (mode == MV_ANY) {
3878.             for (d = N_DIRS_Z - 1; d > DIR_ERR; d--)
3879.                 if (fnc == move_funcs[d][MV_WALK]
3880.                     || fnc == move_funcs[d][MV_RUN]
3881.                     || fnc == move_funcs[d][MV_RUSH])
3882.                     break;
3883.         } else {
3884.             for (d = N_DIRS_Z - 1; d > DIR_ERR; d--)
3885.                 if (fnc == move_funcs[d][mode])
3886.                     break;
3887.         }
3888.     }
3889. 
3890.     if (d != DIR_ERR) {
3891.         u.dx = xdir[d];
3892.         u.dy = ydir[d];
3893.         u.dz = zdir[d];
3894.         return !u.dz;
3895.     }
3896.     u.dz = 0;
3897.     return 0;
3898. }
3899. 
3900. /* grid bug handling */
3901. int
3902. dxdy_moveok(void)
3903. {
3904.     if (u.dx && u.dy && NODIAG(u.umonnum))
3905.         u.dx = u.dy = 0;
3906.     return u.dx || u.dy;
3907. }
3908. 
3909. /* decide whether character (user input keystroke) requests screen repaint */
3910. boolean
3911. redraw_cmd(char c)
3912. {
3913.     uchar uc = (uchar) c;
3914.     struct Cmd_bind *bind = cmdbind_get(uc);
3915. 
3916.     return (boolean) (bind && bind->cmd
3917.                       && bind->cmd->ef_funct == doredraw);
3918. }
3919. 
3920. /*
3921.  * uses getdir() but unlike getdir() it specifically
3922.  * produces coordinates using the direction from getdir()
3923.  * and verifies that those coordinates are ok.
3924.  *
3925.  * If the call to getdir() returns 0, Never_mind is displayed.
3926.  * If the resulting coordinates are not okay, emsg is displayed.
3927.  *
3928.  * Returns non-zero if coordinates in cc are valid.
3929.  */
3930. int
3931. get_adjacent_loc(
3932.     const char *prompt,
3933.     const char *emsg,
3934.     coordxy x, coordxy y,
3935.     coord *cc)
3936. {
3937.     coordxy new_x, new_y;
3938.     if (!getdir(prompt)) {
3939.         pline1(Never_mind);
3940.         return 0;
3941.     }
3942.     new_x = x + u.dx;
3943.     new_y = y + u.dy;
3944.     if (cc && isok(new_x, new_y)) {
3945.         cc->x = new_x;
3946.         cc->y = new_y;
3947.     } else {
3948.         if (emsg)
3949.             pline1(emsg);
3950.         return 0;
3951.     }
3952.     return 1;
3953. }
3954. 
3955. /* prompt for a direction (specified via movement keystroke) and return it
3956.    in u.dx, u.dy, and u.dz; function return value is 1 for ok, 0 otherwise */
3957. int
3958. getdir(const char *s)
3959. {
3960.     char dirsym;
3961.     int is_mov;
3962.     struct _cmd_queue *cmdq = cmdq_pop();
3963. 
3964.     if (cmdq) {
3965.         if (cmdq->typ == CMDQ_DIR) {
3966.             if (!cmdq->dirz) {
3967.                 dirsym = gc.Cmd.dirchars[xytodir(cmdq->dirx, cmdq->diry)];
3968.             } else {
3969.                 dirsym = gc.Cmd.dirchars[(cmdq->dirz > 0) ? DIR_DOWN
3970.                                                           : DIR_UP];
3971.             }
3972.         } else if (cmdq->typ == CMDQ_KEY) {
3973.             dirsym = cmdq->key;
3974.         } else {
3975.             cmdq_clear(CQ_CANNED);
3976.             dirsym = '\0';
3977.             impossible("getdir: command queue had no dir?");
3978.         }
3979.         free(cmdq);
3980.         goto got_dirsym;
3981.     }
3982. 
3983.  retry:
3984.     program_state.input_state = getdirInp;
3985.     if (gi.in_doagain || *readchar_queue) {
3986.         dirsym = readchar();
3987.     } else {
3988.         dirsym = yn_function((s && *s != '^') ? s : "In what direction?",
3989.                              (char *) 0, '\0', FALSE);
3990. 
3991.         /* for the fuzzer, usually force the result to be a valid direction,
3992.            but sometimes let it exercise the invalid direction code; we
3993.            don't try to enforce no-diagonal for hero in grid bug form since
3994.            things like '^' to look at adjacent trap shouldn't be bound by
3995.            that (caller is expected to handle situations where it matters) */
3996.         if (iflags.debug_fuzzer && rn2(20)) {
3997.             switch (rn2(20)) {
3998.             case 0:
3999.                 dirsym = gc.Cmd.spkeys[rn2(2) ? NHKF_GETDIR_SELF : NHKF_ESC];
4000.                 break;
4001.             case 1:
4002.                 dirsym = gc.Cmd.dirchars[rn2(2) ? DIR_DOWN : DIR_UP];
4003.                 break;
4004.             default:
4005.                 dirsym = gc.Cmd.dirchars[rn2(N_DIRS)];
4006.                 break;
4007.             }
4008.         }
4009.     }
4010.     /* remove the prompt string so caller won't have to */
4011.     clear_nhwindow(WIN_MESSAGE);
4012. 
4013.     if (redraw_cmd(dirsym)) { /* ^R */
4014.         docrt_flags(docrtRefresh); /* redraw */
4015.         goto retry;
4016.     }
4017.     if (!gi.in_doagain)
4018.         cmdq_add_key(CQ_REPEAT, dirsym);
4019. 
4020.  got_dirsym:
4021.     if (dirsym == gc.Cmd.spkeys[NHKF_GETDIR_SELF]
4022.         || dirsym == gc.Cmd.spkeys[NHKF_GETDIR_SELF2]) {
4023.         u.dx = u.dy = u.dz = 0;
4024.     } else if (dirsym == gc.Cmd.spkeys[NHKF_GETDIR_MOUSE]) {
4025.         char qbuf[QBUFSZ];
4026.         coord cc;
4027.         int pos, mod;
4028. 
4029.         /*
4030.          * For #therecmdmenu:
4031.          * Player has entered the 'simulated mouse' key ('_' by default)
4032.          * at the "which direction?" prompt so we use getpos() to get a
4033.          * simulated click after moving cursor to the desired location.
4034.          *
4035.          * getpos() returns 0..3 for period, comma, semi-colon, colon.
4036.          * We treat "," as left click and "." as right click due to
4037.          * their positions relative to each other on the keyboard.
4038.          * Using ";" as synonym for "," and ":" for "." is due to their
4039.          * shapes rather than to their keyboard location.
4040.          *
4041.          * Those keys aren't separately bindable for being treated as
4042.          * clicks but we do honor their getpos bindings if player has
4043.          * changed them.  (Bound values might have scrambled keyboard
4044.          * locations relative to each other so ruin the memory aid of
4045.          * "," being left of ".".)
4046.          */
4047.         Sprintf(qbuf,
4048.             "desired location, then type '%s' for left click, '%s' for right",
4049.                 /* visctrl() cycles through several static buffers for its
4050.                    return value so using two in the same expression is ok */
4051.                 visctrl(gc.Cmd.spkeys[NHKF_GETPOS_PICK_Q]), /* ',' */
4052.                 visctrl(gc.Cmd.spkeys[NHKF_GETPOS_PICK])); /* '.' */
4053.         cc.x = u.ux, cc.y = u.uy; /* starting cursor location for getpos() */
4054.         pos = getpos(&cc, TRUE, qbuf);
4055. 
4056.         if (pos < 0) {
4057.             /* ESC or other rejection */
4058.             u.dx = u.dy = u.dz = 0;
4059.             mod = 0; /* neither CLICK_1 nor CLICK_2 */
4060.         } else {
4061.             /* caller expects simulated click to be relative to hero's spot */
4062.             u.dx = cc.x - u.ux;
4063.             u.dy = cc.y - u.uy;
4064.             /* non-zero getdir_click actually means ok to click farther than
4065.                one spot away from hero; adjacent click is always allowed */
4066.             if (!iflags.getdir_click) {
4067.                 u.dx = sgn(u.dx);
4068.                 u.dy = sgn(u.dy);
4069.             }
4070.             u.dz = 0;
4071. 
4072.             switch (pos + NHKF_GETPOS_PICK) {
4073.             case NHKF_GETPOS_PICK_Q: /* 1: quick:   ',' */
4074.             case NHKF_GETPOS_PICK_O: /* 2: once:    ';' */
4075.                 mod = CLICK_1;
4076.                 break;
4077.             case NHKF_GETPOS_PICK:   /* 0: normal:  '.' */
4078.             case NHKF_GETPOS_PICK_V: /* 3: verbose: ':' */
4079.                 mod = CLICK_2;
4080.                 break;
4081.             default:
4082.                 /* could plug in bound values for spkeys[NHKF_GETPOS_PICK],&c
4083.                    but that feels like overkill for something which should
4084.                    never happen; just show their default values */
4085.                 impossible("getpos successful but not one of [.,;:] (%d)",
4086.                            pos);
4087.                 mod = 0; /* neither CLICK_1 nor CLICK_2 */
4088.                 pos = -1; /* return failure */
4089.                 break;
4090.             }
4091.         }
4092.         if (iflags.getdir_click)
4093.             iflags.getdir_click = mod;
4094.         return (pos >= 0);
4095.     } else if (!(is_mov = movecmd(dirsym, MV_ANY)) && !u.dz) {
4096.         boolean did_help = FALSE, help_requested;
4097. 
4098.         if (!strchr(quitchars, dirsym)) {
4099.             help_requested = (dirsym == gc.Cmd.spkeys[NHKF_GETDIR_HELP]);
4100.             if (help_requested || iflags.cmdassist) {
4101.                 did_help = help_dir((s && *s == '^') ? dirsym : '\0',
4102.                                     gc.Cmd.spkeys[NHKF_ESC],
4103.                                     help_requested ? (const char *) 0
4104.                                     : "Invalid direction key!");
4105.                 if (help_requested)
4106.                     goto retry;
4107.             }
4108.             if (!did_help)
4109.                 pline("What a strange direction!");
4110.         }
4111.         return 0;
4112.     } else if (is_mov && !dxdy_moveok()) {
4113.         You_cant("orient yourself that direction.");
4114.         return 0;
4115.     }
4116.     if (!u.dz)
4117.         confdir(FALSE);
4118.     return 1;
4119. }
4120. 
4121. staticfn void
4122. show_direction_keys(
4123.     winid win, /* should specify a window which is using a fixed-width font */
4124.     char centerchar, /* '.' or '@' or ' ' */
4125.     boolean nodiag)
4126. {
4127.     char buf[BUFSZ];
4128. 
4129.     if (!centerchar)
4130.         centerchar = ' ';
4131. 
4132.     if (nodiag) {
4133.         Sprintf(buf, "             %s   ",
4134.                 visctrl(cmd_from_func(do_move_north)));
4135.         putstr(win, 0, buf);
4136.         putstr(win, 0, "             |   ");
4137.         Sprintf(buf, "          %s- %c -%s",
4138.                 visctrl(cmd_from_func(do_move_west)),
4139.                 centerchar,
4140.                 visctrl(cmd_from_func(do_move_east)));
4141.         putstr(win, 0, buf);
4142.         putstr(win, 0, "             |   ");
4143.         Sprintf(buf, "             %s   ",
4144.                 visctrl(cmd_from_func(do_move_south)));
4145.         putstr(win, 0, buf);
4146.     } else {
4147.         Sprintf(buf, "          %s  %s  %s",
4148.                 visctrl(cmd_from_func(do_move_northwest)),
4149.                 visctrl(cmd_from_func(do_move_north)),
4150.                 visctrl(cmd_from_func(do_move_northeast)));
4151.         putstr(win, 0, buf);
4152.         putstr(win, 0, "           \\ | / ");
4153.         Sprintf(buf, "          %s- %c -%s",
4154.                 visctrl(cmd_from_func(do_move_west)),
4155.                 centerchar,
4156.                 visctrl(cmd_from_func(do_move_east)));
4157.         putstr(win, 0, buf);
4158.         putstr(win, 0, "           / | \\ ");
4159.         Sprintf(buf, "          %s  %s  %s",
4160.                 visctrl(cmd_from_func(do_move_southwest)),
4161.                 visctrl(cmd_from_func(do_move_south)),
4162.                 visctrl(cmd_from_func(do_move_southeast)));
4163.         putstr(win, 0, buf);
4164.     };
4165. }
4166. 
4167. /* explain choices if player has asked for getdir() help or has given
4168.    an invalid direction after a prefix key ('F', 'g', 'm', &c), which
4169.    might be bogus but could be up, down, or self when not applicable */
4170. staticfn boolean
4171. help_dir(
4172.     char sym,
4173.     uchar spkey, /* actual key; either prefix or ESC */
4174.     const char *msg)
4175. {
4176.     static const char wiz_only_list[] = "EFGIVW";
4177.     char ctrl;
4178.     winid win;
4179.     char buf[BUFSZ], buf2[BUFSZ], *explain;
4180.     const char *dothat /*, *how */;
4181.     boolean prefixhandling /*, viawindow */;
4182. 
4183.     /* NHKF_ESC indicates that player asked for help at getdir prompt */
4184.     /* viawindow = (spkey == gc.Cmd.spkeys[NHKF_ESC] || iflags.cmdassist); */
4185.     prefixhandling = (spkey != gc.Cmd.spkeys[NHKF_ESC]);
4186.     /*
4187.      * Handling for prefix keys that don't want special directions.
4188.      * Delivered via pline if 'cmdassist' is off, or instead of the
4189.      * general message if it's on.
4190.      */
4191.     dothat = "do that";
4192.     /* how = " at"; */ /* for "<action> at yourself"; not used for up/down */
4193. 
4194.     buf[0] = '\0';
4195. #if 0   /* Since prefix keys got 'promoted' to commands, feedback for
4196.          * invalid prefix is done in rhack() these days.
4197.          */
4198.     /* for movement prefix followed by '.' or (numpad && 's') to mean 'self';
4199.        note: '-' for hands (inventory form of 'self') is not handled here */
4200.     if (prefixhandling
4201.         && (sym == gc.Cmd.spkeys[NHKF_GETDIR_SELF]
4202.             || (gc.Cmd.num_pad && sym == gc.Cmd.spkeys[NHKF_GETDIR_SELF2]))) {
4203.         Sprintf(buf, "You can't %s%s yourself.", dothat, how);
4204.     /* for movement prefix followed by up or down */
4205.     } else if (prefixhandling && (sym == '<' || sym == '>')) {
4206.         Sprintf(buf, "You can't %s %s.", dothat,
4207.                 /* was "upwards" and "downwards", but they're considered
4208.                    to be variants of canonical "upward" and "downward" */
4209.                 (sym == '<') ? "upward" : "downward");
4210.     }
4211. 
4212.     /* if '!cmdassist', display via pline() and we're done (note: asking
4213.        for help at getdir() prompt forces cmdassist for this operation) */
4214.     if (!viawindow) {
4215.         if (prefixhandling) {
4216.             if (!*buf)
4217.                 Sprintf(buf, "Invalid direction for '%s' prefix.",
4218.                         visctrl(spkey));
4219.             pline("%s", buf);
4220.             return TRUE;
4221.         }
4222.         /* when 'cmdassist' is off and caller doesn't insist, do nothing */
4223.         return FALSE;
4224.     }
4225. #else
4226.     nhUse(prefixhandling);
4227. #endif
4228. 
4229.     win = create_nhwindow(NHW_TEXT);
4230.     if (!win)
4231.         return FALSE;
4232. 
4233.     if (*buf) {
4234.         /* show bad-prefix message instead of general invalid-direction one */
4235.         putstr(win, 0, buf);
4236.         putstr(win, 0, "");
4237.     } else if (msg) {
4238.         Sprintf(buf, "cmdassist: %s", msg);
4239.         putstr(win, 0, buf);
4240.         putstr(win, 0, "");
4241.     }
4242. 
4243.     if (!prefixhandling && (letter(sym) || sym == '[')) {
4244.         /* '[': old 'cmdhelp' showed ESC as ^[ */
4245.         sym = highc(sym); /* @A-Z[ (note: letter() accepts '@') */
4246.         ctrl = (sym - 'A') + 1; /* 0-27 (note: 28-31 aren't applicable) */
4247.         if ((explain = dowhatdoes_core(ctrl, buf2)) != 0
4248.             && (!strchr(wiz_only_list, sym) || wizard)) {
4249.             Sprintf(buf, "Are you trying to use ^%c%s?", sym,
4250.                     strchr(wiz_only_list, sym) ? ""
4251.                         : " as specified in the Guidebook");
4252.             putstr(win, 0, buf);
4253.             putstr(win, 0, "");
4254.             putstr(win, 0, explain);
4255.             putstr(win, 0, "");
4256.             putstr(win, 0,
4257.                   "To use that command, hold down the <Ctrl> key as a shift");
4258.             Sprintf(buf, "and press the <%c> key.", sym);
4259.             putstr(win, 0, buf);
4260.             putstr(win, 0, "");
4261.         }
4262.     }
4263. 
4264.     Sprintf(buf, "Valid direction keys%s%s%s are:",
4265.             prefixhandling ? " to " : "", prefixhandling ? dothat : "",
4266.             NODIAG(u.umonnum) ? " in your current form" : "");
4267.     putstr(win, 0, buf);
4268.     show_direction_keys(win, !prefixhandling ? '.' : ' ', NODIAG(u.umonnum));
4269. 
4270.     if (!prefixhandling) {
4271.         /* NOPICKUP: unlike the other prefix keys, 'm' allows up/down for
4272.            stair traversal; we won't get here when "m<" or "m>" has been
4273.            given but we include up and down for 'm'+invalid_direction;
4274.            self is excluded as a viable direction for every prefix */
4275.         putstr(win, 0, "");
4276.         putstr(win, 0, "          <  up");
4277.         putstr(win, 0, "          >  down");
4278.         if (!prefixhandling) {
4279.             int selfi = gc.Cmd.num_pad ? NHKF_GETDIR_SELF2 : NHKF_GETDIR_SELF;
4280. 
4281.             Sprintf(buf,   "       %4s  direct at yourself",
4282.                     visctrl(gc.Cmd.spkeys[selfi]));
4283.             putstr(win, 0, buf);
4284.         }
4285.     }
4286. 
4287.     if (msg) {
4288.         /* non-null msg means that this wasn't an explicit user request */
4289.         putstr(win, 0, "");
4290.         putstr(win, 0,
4291.                "(Suppress this message with !cmdassist in config file.)");
4292.     }
4293.     display_nhwindow(win, FALSE);
4294.     destroy_nhwindow(win);
4295.     return TRUE;
4296. }
4297. 
4298. /* if hero is impaired, pick random movement direction */
4299. void
4300. confdir(boolean force_impairment)
4301. {
4302.     if (force_impairment || u_maybe_impaired()) {
4303.         int kmax = NODIAG(u.umonnum) ? (N_DIRS / 2) : N_DIRS,
4304.             k = (int) dirs_ord[rn2(kmax)];
4305. 
4306.         u.dx = xdir[k];
4307.         u.dy = ydir[k];
4308.     }
4309.     return;
4310. }
4311. 
4312. const char *
4313. directionname(int dir)
4314. {
4315.     static NEARDATA const char *const dirnames[N_DIRS_Z] = {
4316.         "west",      "northwest", "north",     "northeast", "east",
4317.         "southeast", "south",     "southwest", "down",      "up",
4318.     };
4319. 
4320.     if (dir < 0 || dir >= N_DIRS_Z)
4321.         return "invalid";
4322.     return dirnames[dir];
4323. }
4324. 
4325. int
4326. isok(coordxy x, coordxy y)
4327. {
4328.     /* x corresponds to curx, so x==1 is the first column. Ach. %% */
4329.     return x >= 1 && x <= COLNO - 1 && y >= 0 && y <= ROWNO - 1;
4330. }
4331. 
4332. /* #herecmdmenu command */
4333. staticfn int
4334. doherecmdmenu(void)
4335. {
4336.     char ch = here_cmd_menu();
4337. 
4338.     return (ch && ch != '\033') ? ECMD_TIME : ECMD_OK;
4339. }
4340. 
4341. /* #therecmdmenu command, a way to test there_cmd_menu without mouse */
4342. staticfn int
4343. dotherecmdmenu(void)
4344. {
4345.     char ch;
4346.     int dir, click;
4347.     coordxy x = gc.clicklook_cc.x;
4348.     coordxy y = gc.clicklook_cc.y;
4349. 
4350.     iflags.getdir_click = CLICK_1 | CLICK_2; /* allow 'far' click */
4351. 
4352.     if (isok(x, y)) {
4353.         if (x == u.ux && y == u.uy)
4354.             ch = here_cmd_menu();
4355.         else
4356.             ch = there_cmd_menu(x, y, iflags.getdir_click);
4357.         gc.clicklook_cc.x = gc.clicklook_cc.y = -1;
4358.         iflags.getdir_click = 0;
4359.         return (ch && ch != '\033') ? ECMD_TIME : ECMD_OK;
4360.     }
4361. 
4362.     dir = getdir((const char *) 0);
4363.     click = iflags.getdir_click;
4364.     iflags.getdir_click = 0;
4365. 
4366.     if (!dir || !isok(u.ux + u.dx, u.uy + u.dy))
4367.         return ECMD_CANCEL;
4368. 
4369.     if (u.dx || u.dy)
4370.         ch = there_cmd_menu(u.ux + u.dx, u.uy + u.dy, click);
4371.     else
4372.         ch = here_cmd_menu();
4373. 
4374.     return (ch && ch != '\033') ? ECMD_TIME : ECMD_OK;
4375. }
4376. 
4377. /* commands for [t]herecmdmenu */
4378. enum menucmd {
4379.     MCMD_NOTHING = 0,
4380.     MCMD_OPEN_DOOR,
4381.     MCMD_LOCK_DOOR,
4382.     MCMD_UNTRAP_DOOR,
4383.     MCMD_KICK_DOOR,
4384.     MCMD_CLOSE_DOOR,
4385.     MCMD_SEARCH,
4386.     MCMD_LOOK_TRAP,
4387.     MCMD_UNTRAP_TRAP,
4388.     MCMD_MOVE_DIR,
4389.     MCMD_RIDE,
4390.     MCMD_REMOVE_SADDLE,
4391.     MCMD_APPLY_SADDLE,
4392.     MCMD_TALK,
4393.     MCMD_NAME,
4394. 
4395.     MCMD_QUAFF,
4396.     MCMD_DIP,
4397.     MCMD_SIT,
4398.     MCMD_UP,
4399.     MCMD_DOWN,
4400.     MCMD_DISMOUNT,
4401.     MCMD_MONABILITY,
4402.     MCMD_PICKUP,
4403.     MCMD_LOOT,
4404.     MCMD_TIP,
4405.     MCMD_EAT,
4406.     MCMD_DROP,
4407.     MCMD_REST,
4408.     MCMD_LOOK_HERE,
4409.     MCMD_LOOK_AT,
4410.     MCMD_ATTACK_NEXT2U,
4411.     MCMD_UNTRAP_HERE,
4412.     MCMD_OFFER,
4413.     MCMD_INVENTORY,
4414.     MCMD_CAST_SPELL,
4415. 
4416.     MCMD_THROW_OBJ,
4417.     MCMD_TRAVEL,
4418. };
4419. 
4420. staticfn void
4421. mcmd_addmenu(winid win, int act, const char *txt)
4422. {
4423.     anything any;
4424.     int clr = NO_COLOR;
4425. 
4426.     /* TODO: fixed letters for the menu entries? */
4427.     any = cg.zeroany;
4428.     any.a_int = act;
4429.     add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, clr, txt,
4430.              MENU_ITEMFLAGS_NONE);
4431. }
4432. 
4433. /* command menu entries when targeting self */
4434. staticfn int
4435. there_cmd_menu_self(winid win, coordxy x, coordxy y, int *act UNUSED)
4436. {
4437.     int K = 0;
4438.     char buf[BUFSZ];
4439.     schar typ = levl[x][y].typ;
4440.     stairway *stway = stairway_at(x, y);
4441.     struct trap *ttmp;
4442. 
4443.     if (!u_at(x, y))
4444.         return K;
4445. 
4446.     if ((IS_FOUNTAIN(typ) || IS_SINK(typ)) && can_reach_floor(FALSE)) {
4447.         Sprintf(buf, "Drink from the %s",
4448.                 defsyms[IS_FOUNTAIN(typ) ? S_fountain : S_sink].explanation);
4449.         mcmd_addmenu(win, MCMD_QUAFF, buf), ++K;
4450.     }
4451.     if (IS_FOUNTAIN(typ) && can_reach_floor(FALSE))
4452.         mcmd_addmenu(win, MCMD_DIP, "Dip something into the fountain"), ++K;
4453.     if (IS_THRONE(typ))
4454.         mcmd_addmenu(win, MCMD_SIT, "Sit on the throne"), ++K;
4455.     if (IS_ALTAR(typ))
4456.         mcmd_addmenu(win, MCMD_OFFER, "Sacrifice something on the altar"), ++K;
4457. 
4458.     if (stway && stway->up) {
4459.         Sprintf(buf, "Go up the %s",
4460.                 stway->isladder ? "ladder" : "stairs");
4461.         mcmd_addmenu(win, MCMD_UP, buf), ++K;
4462.     }
4463.     if (stway && !stway->up) {
4464.         Sprintf(buf, "Go down the %s",
4465.                 stway->isladder ? "ladder" : "stairs");
4466.         mcmd_addmenu(win, MCMD_DOWN, buf), ++K;
4467.     }
4468.     if (u.usteed) { /* another movement choice */
4469.         Sprintf(buf, "Dismount %s",
4470.                 x_monnam(u.usteed, ARTICLE_THE, (char *) 0,
4471.                          SUPPRESS_SADDLE, FALSE));
4472.         mcmd_addmenu(win, MCMD_DISMOUNT, buf), ++K;
4473.     }
4474. 
4475. #if 0
4476.     if (Upolyd) { /* before objects */
4477.         Sprintf(buf, "Use %s special ability",
4478.                 s_suffix(pmname(&mons[u.umonnum], Ugender)));
4479.         mcmd_addmenu(win, MCMD_MONABILITY, buf), ++K;
4480.     }
4481. #endif
4482. 
4483.     if (OBJ_AT(x, y)) {
4484.         struct obj *otmp = svl.level.objects[x][y];
4485. 
4486.         Sprintf(buf, "Pick up %s", otmp->nexthere ? "items" : doname(otmp));
4487.         mcmd_addmenu(win, MCMD_PICKUP, buf), ++K;
4488. 
4489.         if (Is_container(otmp)) {
4490.             Sprintf(buf, "Loot %s", doname(otmp));
4491.             mcmd_addmenu(win, MCMD_LOOT, buf), ++K;
4492. 
4493.             Sprintf(buf, "Tip %s", doname(otmp));
4494.             mcmd_addmenu(win, MCMD_TIP, buf), ++K;
4495.         }
4496.         if (otmp->oclass == FOOD_CLASS) {
4497.             Sprintf(buf, "Eat %s", doname(otmp));
4498.             mcmd_addmenu(win, MCMD_EAT, buf), ++K;
4499.         }
4500.     }
4501. 
4502. 
4503.     if (gi.invent) {
4504.         mcmd_addmenu(win, MCMD_INVENTORY, "Inventory"), ++K;
4505.         mcmd_addmenu(win, MCMD_DROP, "Drop items"), ++K;
4506.     }
4507.     mcmd_addmenu(win, MCMD_REST, "Rest one turn"), ++K;
4508.     mcmd_addmenu(win, MCMD_SEARCH, "Search around you"), ++K;
4509.     mcmd_addmenu(win, MCMD_LOOK_HERE, "Look at what is here"), ++K;
4510. 
4511.     if (num_spells() > 0)
4512.         mcmd_addmenu(win, MCMD_CAST_SPELL, "Cast a spell"), ++K;
4513. 
4514.     if ((ttmp = t_at(x, y)) != 0 && ttmp->tseen) {
4515.         if (ttmp->ttyp != VIBRATING_SQUARE)
4516.             mcmd_addmenu(win, MCMD_UNTRAP_HERE,
4517.                          "Attempt to disarm trap"), ++K;
4518.     }
4519.     return K;
4520. }
4521. 
4522. /* add entries to there_cmd_menu, when x,y is next to hero */
4523. staticfn int
4524. there_cmd_menu_next2u(
4525.     winid win,
4526.     coordxy x, coordxy y,
4527.     int mod,
4528.     int *act)
4529. {
4530.     int K = 0;
4531.     char buf[BUFSZ];
4532.     schar typ = levl[x][y].typ;
4533.     struct trap *ttmp;
4534.     struct monst *mtmp;
4535. 
4536.     if (!next2u(x, y))
4537.         return K;
4538. 
4539.     if (IS_DOOR(typ)) {
4540.         boolean key_or_pick, card;
4541.         int dm = levl[x][y].doormask;
4542. 
4543.         if ((dm & (D_CLOSED | D_LOCKED))) {
4544.             mcmd_addmenu(win, MCMD_OPEN_DOOR, "Open the door"), ++K;
4545.             /* unfortunately there's no lknown flag for doors to
4546.                remember the locked/unlocked state */
4547.             key_or_pick = (carrying(SKELETON_KEY) || carrying(LOCK_PICK));
4548.             card = (carrying(CREDIT_CARD) != 0);
4549.             if (key_or_pick || card) {
4550.                 Sprintf(buf, "%sunlock the door",
4551.                         key_or_pick ? "lock or " : "");
4552.                 mcmd_addmenu(win, MCMD_LOCK_DOOR, upstart(buf)), ++K;
4553.             }
4554.             /* unfortunately there's no tknown flag for doors (or chests)
4555.                to remember whether a trap had been found */
4556.             mcmd_addmenu(win, MCMD_UNTRAP_DOOR,
4557.                          "Search the door for a trap"), ++K;
4558.             /* [what about #force?] */
4559.             mcmd_addmenu(win, MCMD_KICK_DOOR, "Kick the door"), ++K;
4560.         } else if ((dm & D_ISOPEN) && (mod == CLICK_2)) {
4561.             mcmd_addmenu(win, MCMD_CLOSE_DOOR, "Close the door"), ++K;
4562.         }
4563.     }
4564. 
4565.     if (typ <= SCORR)
4566.         mcmd_addmenu(win, MCMD_SEARCH, "Search for secret doors"), ++K;
4567. 
4568.     if ((ttmp = t_at(x, y)) != 0 && ttmp->tseen) {
4569.         mcmd_addmenu(win, MCMD_LOOK_TRAP, "Examine trap"), ++K;
4570.         if (ttmp->ttyp != VIBRATING_SQUARE)
4571.             mcmd_addmenu(win, MCMD_UNTRAP_TRAP,
4572.                                  "Attempt to disarm trap"), ++K;
4573.         mcmd_addmenu(win, MCMD_MOVE_DIR, "Move on the trap"), ++K;
4574.     }
4575. 
4576.     if (levl[x][y].glyph == objnum_to_glyph(BOULDER))
4577.         mcmd_addmenu(win, MCMD_MOVE_DIR, "Push the boulder"), ++K;
4578. 
4579.     mtmp = m_at(x, y);
4580.     if (mtmp && !canspotmon(mtmp))
4581.         mtmp = 0;
4582.     if (mtmp && which_armor(mtmp, W_SADDLE)) {
4583.         char *mnam = x_monnam(mtmp, ARTICLE_THE, (char *) 0,
4584.                               SUPPRESS_SADDLE, FALSE);
4585. 
4586.         if (!u.usteed) {
4587.             Sprintf(buf, "Ride %s", mnam);
4588.             mcmd_addmenu(win, MCMD_RIDE, buf), ++K;
4589.         }
4590.         Sprintf(buf, "Remove saddle from %s", mnam);
4591.         mcmd_addmenu(win, MCMD_REMOVE_SADDLE, buf), ++K;
4592.     }
4593.     if (mtmp && can_saddle(mtmp) && !which_armor(mtmp, W_SADDLE)
4594.         && carrying(SADDLE)) {
4595.         Sprintf(buf, "Put saddle on %s", mon_nam(mtmp));
4596.         mcmd_addmenu(win, MCMD_APPLY_SADDLE, buf), ++K;
4597.     }
4598.     if (mtmp && (mtmp->mpeaceful || mtmp->mtame)) {
4599.         Sprintf(buf, "Talk to %s", mon_nam(mtmp));
4600.         mcmd_addmenu(win, MCMD_TALK, buf), ++K;
4601. 
4602.         Sprintf(buf, "Swap places with %s", mon_nam(mtmp));
4603.         mcmd_addmenu(win, MCMD_MOVE_DIR, buf), ++K;
4604. 
4605.         Sprintf(buf, "%s %s",
4606.                 !has_mgivenname(mtmp) ? "Name" : "Rename",
4607.                 mon_nam(mtmp));
4608.         mcmd_addmenu(win, MCMD_NAME, buf), ++K;
4609.     }
4610. 
4611.     if ((mtmp && !(mtmp->mpeaceful || mtmp->mtame))
4612.         || glyph_is_invisible(glyph_at(x, y))) {
4613.         Sprintf(buf, "Attack %s", mtmp ? mon_nam(mtmp) : "unseen creature");
4614.         mcmd_addmenu(win, MCMD_ATTACK_NEXT2U, buf), ++K;
4615.         /* attacking overrides any other automatic action */
4616.         *act = MCMD_ATTACK_NEXT2U;
4617.     } else {
4618.         /* "Move %s", direction - handled below */
4619.     }
4620.     return K;
4621. }
4622. 
4623. staticfn int
4624. there_cmd_menu_far(winid win, coordxy x, coordxy y, int mod)
4625. {
4626.     int K = 0;
4627. 
4628.     if (mod == CLICK_1) {
4629.         if (linedup(u.ux, u.uy, x, y, 1)
4630.             && dist2(u.ux, u.uy, x, y) < 18*18)
4631.             mcmd_addmenu(win, MCMD_THROW_OBJ, "Throw something"), ++K;
4632. 
4633.         mcmd_addmenu(win, MCMD_TRAVEL, "Travel here"), ++K;
4634.     }
4635.     return K;
4636. }
4637. 
4638. staticfn int
4639. there_cmd_menu_common(
4640.     winid win,
4641.     coordxy x, coordxy y,
4642.     int mod,
4643.     int *act UNUSED)
4644. {
4645.     int K = 0;
4646. 
4647.     if (mod == CLICK_1 || mod == CLICK_2) { /* ignore iflags.clicklook here */
4648.         /* for self, only include "look at map symbol" if it isn't the
4649.            ordinary hero symbol (steed, invisible w/o see invisible, ?) */
4650.         if (!u_at(x, y) || Upolyd || glyph_at(x, y) != hero_glyph)
4651.             mcmd_addmenu(win, MCMD_LOOK_AT, "Look at map symbol"), ++K;
4652.     }
4653.     return K;
4654. }
4655. 
4656. /* queue up command(s) to perform #therecmdmenu action */
4657. staticfn void
4658. act_on_act(
4659.     int act,                /* action */
4660.     coordxy dx, coordxy dy) /* delta to adjacent spot (farther sometimes) */
4661. {
4662.     struct obj *otmp;
4663.     int dir;
4664. 
4665.     /* a few there_cmd_menu_far() actions use dx,dy differently */
4666.     switch (act) {
4667.     case MCMD_THROW_OBJ:
4668.     case MCMD_TRAVEL:
4669.     case MCMD_LOOK_AT:
4670.         /* keep dx,dy as-is */
4671.         break;
4672.     default:
4673.         /* force dx and dy to be +1, 0, or -1 */
4674.         dx = sgn(dx);
4675.         dy = sgn(dy);
4676.         break;
4677.     }
4678. 
4679.     switch (act) {
4680.     case MCMD_TRAVEL:
4681.         /* FIXME: player has explicitly picked "travel to this location"
4682.            from the menu but it will only work if flags.travelcmd is True.
4683.            That option is intended as way to guard against stray mouse
4684.            clicks and shouldn't inhibit explicit travel. */
4685.         iflags.travelcc.x = u.tx = u.ux + dx;
4686.         iflags.travelcc.y = u.ty = u.uy + dy;
4687.         cmdq_add_ec(CQ_CANNED, dotravel_target);
4688.         break;
4689.     case MCMD_THROW_OBJ:
4690.         cmdq_add_ec(CQ_CANNED, dothrow);
4691.         cmdq_add_userinput(CQ_CANNED);
4692.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4693.         break;
4694.     case MCMD_OPEN_DOOR:
4695.         cmdq_add_ec(CQ_CANNED, doopen);
4696.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4697.         break;
4698.     case MCMD_LOCK_DOOR:
4699.         otmp = carrying(SKELETON_KEY);
4700.         if (!otmp)
4701.             otmp = carrying(LOCK_PICK);
4702.         if (!otmp)
4703.             otmp = carrying(CREDIT_CARD);
4704.         if (otmp) {
4705.             cmdq_add_ec(CQ_CANNED, doapply);
4706.             cmdq_add_key(CQ_CANNED, otmp->invlet);
4707.             cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4708.             cmdq_add_key(CQ_CANNED, 'y'); /* "Lock it?" */
4709.         }
4710.         break;
4711.     case MCMD_UNTRAP_DOOR:
4712.         cmdq_add_ec(CQ_CANNED, dountrap);
4713.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4714.         break;
4715.     case MCMD_KICK_DOOR:
4716.         cmdq_add_ec(CQ_CANNED, dokick);
4717.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4718.         break;
4719.     case MCMD_CLOSE_DOOR:
4720.         cmdq_add_ec(CQ_CANNED, doclose);
4721.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4722.         break;
4723.     case MCMD_SEARCH:
4724.         cmdq_add_ec(CQ_CANNED, dosearch);
4725.         break;
4726.     case MCMD_LOOK_TRAP:
4727.         cmdq_add_ec(CQ_CANNED, doidtrap);
4728.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4729.         break;
4730.     case MCMD_UNTRAP_TRAP:
4731.         cmdq_add_ec(CQ_CANNED, dountrap);
4732.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4733.         break;
4734.     case MCMD_MOVE_DIR:
4735.         dir = xytodir(dx, dy);
4736.         cmdq_add_ec(CQ_CANNED, move_funcs[dir][MV_WALK]);
4737.         break;
4738.     case MCMD_RIDE:
4739.         cmdq_add_ec(CQ_CANNED, doride);
4740.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4741.         break;
4742.     case MCMD_REMOVE_SADDLE:
4743.         /* m-prefix for #loot: skip any floor containers */
4744.         cmdq_add_ec(CQ_CANNED, do_reqmenu);
4745.         cmdq_add_ec(CQ_CANNED, doloot);
4746.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4747.         cmdq_add_key(CQ_CANNED, 'y'); /* "Do you want to remove saddle? */
4748.         break;
4749.     case MCMD_APPLY_SADDLE:
4750.         if ((otmp = carrying(SADDLE)) != 0) {
4751.             cmdq_add_ec(CQ_CANNED, doapply);
4752.             cmdq_add_key(CQ_CANNED, otmp->invlet);
4753.             cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4754.         }
4755.         break;
4756.     case MCMD_ATTACK_NEXT2U:
4757.         dir = xytodir(dx, dy);
4758.         cmdq_add_ec(CQ_CANNED, move_funcs[dir][MV_WALK]);
4759.         break;
4760.     case MCMD_TALK:
4761.         cmdq_add_ec(CQ_CANNED, dotalk);
4762.         cmdq_add_dir(CQ_CANNED, dx, dy, 0);
4763.         break;
4764.     case MCMD_NAME:
4765.         cmdq_add_ec(CQ_CANNED, docallcmd);
4766.         cmdq_add_key(CQ_CANNED, 'm'); /* name a monster */
4767.         cmdq_add_dir(CQ_CANNED, dx, dy, 0); /* getpos() uses u.ux+dx,u.uy+dy */
4768.         break;
4769.     case MCMD_QUAFF:
4770.         cmdq_add_ec(CQ_CANNED, dodrink);
4771.         cmdq_add_key(CQ_CANNED, 'y'); /* "Drink from the fountain?" */
4772.         break;
4773.     case MCMD_DIP:
4774.         cmdq_add_ec(CQ_CANNED, dodip);
4775.         cmdq_add_userinput(CQ_CANNED);
4776.         cmdq_add_key(CQ_CANNED, 'y'); /* "Dip foo into the fountain?" */
4777.         break;
4778.     case MCMD_SIT:
4779.         cmdq_add_ec(CQ_CANNED, dosit);
4780.         break;
4781.     case MCMD_UP:
4782.         cmdq_add_ec(CQ_CANNED, doup);
4783.         break;
4784.     case MCMD_DOWN:
4785.         cmdq_add_ec(CQ_CANNED, dodown);
4786.         break;
4787.     case MCMD_DISMOUNT:
4788.         cmdq_add_ec(CQ_CANNED, doride);
4789.         break;
4790.     case MCMD_MONABILITY:
4791.         cmdq_add_ec(CQ_CANNED, domonability);
4792.         break;
4793.     case MCMD_PICKUP:
4794.         cmdq_add_ec(CQ_CANNED, dopickup);
4795.         break;
4796.     case MCMD_LOOT:
4797.         cmdq_add_ec(CQ_CANNED, doloot);
4798.         break;
4799.     case MCMD_TIP:
4800.         cmdq_add_ec(CQ_CANNED, dotip);
4801.         cmdq_add_key(CQ_CANNED, 'y'); /* "There is foo here; tip it?" */
4802.         break;
4803.     case MCMD_EAT:
4804.         cmdq_add_ec(CQ_CANNED, doeat);
4805.         cmdq_add_key(CQ_CANNED, 'y'); /* "There is foo here; eat it?" */
4806.         break;
4807.     case MCMD_DROP:
4808.         cmdq_add_ec(CQ_CANNED, dodrop);
4809.         break;
4810.     case MCMD_INVENTORY:
4811.         cmdq_add_ec(CQ_CANNED, ddoinv);
4812.         break;
4813.     case MCMD_REST:
4814.         cmdq_add_ec(CQ_CANNED, donull);
4815.         break;
4816.     case MCMD_LOOK_HERE:
4817.         cmdq_add_ec(CQ_CANNED, dolook);
4818.         break;
4819.     case MCMD_LOOK_AT:
4820.         gc.clicklook_cc.x = u.ux + dx;
4821.         gc.clicklook_cc.y = u.uy + dy;
4822.         cmdq_add_ec(CQ_CANNED, doclicklook);
4823.         break;
4824.     case MCMD_UNTRAP_HERE:
4825.         cmdq_add_ec(CQ_CANNED, dountrap);
4826.         cmdq_add_dir(CQ_CANNED, 0, 0, 1);
4827.         break;
4828.     case MCMD_OFFER:
4829.         cmdq_add_ec(CQ_CANNED, dosacrifice);
4830.         cmdq_add_userinput(CQ_CANNED);
4831.         break;
4832.     case MCMD_CAST_SPELL:
4833.         cmdq_add_ec(CQ_CANNED, docast);
4834.         break;
4835.     default:
4836.         break;
4837.     }
4838. }
4839. 
4840. /* offer choice of actions to perform at adjacent location <x,y>;
4841.    a few choices can be farther away */
4842. staticfn char
4843. there_cmd_menu(coordxy x, coordxy y, int mod)
4844. {
4845.     winid win;
4846.     char ch = '\0';
4847.     int npick = 0, K = 0;
4848.     menu_item *picks = (menu_item *) 0;
4849.     /*int dx = sgn(x - u.ux), dy = sgn(y - u.uy);*/
4850.     coordxy dx = x - u.ux, dy = y - u.uy;
4851.     int act = MCMD_NOTHING;
4852. 
4853.     win = create_nhwindow(NHW_MENU);
4854.     start_menu(win, MENU_BEHAVE_STANDARD);
4855. 
4856.     if (u_at(x, y))
4857.         K += there_cmd_menu_self(win, x, y, &act);
4858.     else if (next2u(x, y))
4859.         K += there_cmd_menu_next2u(win, x, y, mod, &act);
4860.     else
4861.         K += there_cmd_menu_far(win, x, y, mod);
4862.     K += there_cmd_menu_common(win, x, y, mod, &act);
4863. 
4864.     if (!K) {
4865.         /* no menu options, try to move */
4866.         if (next2u(x, y) && test_move(u.ux, u.uy, dx, dy, TEST_MOVE)) {
4867.             int dir = xytodir(dx, dy);
4868. 
4869.             cmdq_add_ec(CQ_CANNED, move_funcs[dir][MV_WALK]);
4870.         } else if (flags.travelcmd) {
4871.             iflags.travelcc.x = u.tx = x;
4872.             iflags.travelcc.y = u.ty = y;
4873.             cmdq_add_ec(CQ_CANNED, dotravel_target);
4874.         }
4875.         npick = 0;
4876.         ch = '\0';
4877.     } else if (K == 1 && act != MCMD_NOTHING && act != MCMD_TRAVEL) {
4878.         destroy_nhwindow(win);
4879. 
4880.         act_on_act(act, dx, dy);
4881.         return '\0';
4882.     } else {
4883.         end_menu(win, "What do you want to do?");
4884.         npick = select_menu(win, PICK_ONE, &picks);
4885.         ch = '\033';
4886.     }
4887.     destroy_nhwindow(win);
4888.     if (npick > 0) {
4889.         act = picks->item.a_int;
4890.         free((genericptr_t) picks);
4891. 
4892.         act_on_act(act, dx, dy);
4893.         return '\0';
4894.     }
4895.     return ch;
4896. }
4897. 
4898. staticfn char
4899. here_cmd_menu(void)
4900. {
4901.     there_cmd_menu(u.ux, u.uy, CLICK_1);
4902.     return '\0';
4903. }
4904. 
4905. void
4906. click_to_cmd(coordxy x, coordxy y, int mod)
4907. {
4908.     gc.clicklook_cc.x = x;
4909.     gc.clicklook_cc.y = y;
4910. 
4911.     if (gc.Cmd.mousebtn[mod-1])
4912.         cmdq_add_ec(CQ_CANNED, gc.Cmd.mousebtn[mod-1]->ef_funct);
4913. }
4914. 
4915. staticfn int
4916. domouseaction(void)
4917. {
4918.     coordxy x, y;
4919.     struct obj *o;
4920.     int dir;
4921. 
4922.     x = gc.clicklook_cc.x - u.ux;
4923.     y = gc.clicklook_cc.y - u.uy;
4924. 
4925.     if (flags.travelcmd) {
4926.         if (abs(x) <= 1 && abs(y) <= 1) {
4927.             x = sgn(x), y = sgn(y);
4928.         } else {
4929.             iflags.travelcc.x = u.tx = u.ux + x;
4930.             iflags.travelcc.y = u.ty = u.uy + y;
4931.             cmdq_add_ec(CQ_CANNED, dotravel_target);
4932.             return ECMD_OK;
4933.         }
4934. 
4935.         if (x == 0 && y == 0) {
4936.             /* here */
4937.             if (IS_FOUNTAIN(levl[u.ux][u.uy].typ)
4938.                 || IS_SINK(levl[u.ux][u.uy].typ)) {
4939.                 cmdq_add_ec(CQ_CANNED, dodrink);
4940.                 return ECMD_OK;
4941.             } else if (IS_THRONE(levl[u.ux][u.uy].typ)) {
4942.                 cmdq_add_ec(CQ_CANNED, dosit);
4943.                 return ECMD_OK;
4944.             } else if (On_stairs_up(u.ux, u.uy)) {
4945.                 cmdq_add_ec(CQ_CANNED, doup);
4946.                 return ECMD_OK;
4947.             } else if (On_stairs_dn(u.ux, u.uy)) {
4948.                 cmdq_add_ec(CQ_CANNED, dodown);
4949.                 return ECMD_OK;
4950.             } else if ((o = vobj_at(u.ux, u.uy)) != 0) {
4951.                 cmdq_add_ec(CQ_CANNED, Is_container(o) ? doloot : dopickup);
4952.                 return ECMD_OK;
4953.             } else {
4954.                 cmdq_add_ec(CQ_CANNED, donull); /* just rest */
4955.                 return ECMD_OK;
4956.             }
4957.         }
4958. 
4959.         /* directional commands */
4960. 
4961.         dir = xytodir(x, y);
4962.         if (!m_at(u.ux + x, u.uy + y)
4963.             && !test_move(u.ux, u.uy, x, y, TEST_MOVE)) {
4964.             if (IS_DOOR(levl[u.ux + x][u.uy + y].typ)) {
4965.                 /* slight assistance to player: choose kick/open for them */
4966.                 if (levl[u.ux + x][u.uy + y].doormask & D_LOCKED) {
4967.                     cmdq_add_ec(CQ_CANNED, dokick);
4968.                     return ECMD_OK;
4969.                 }
4970.                 if (levl[u.ux + x][u.uy + y].doormask & D_CLOSED) {
4971.                     cmdq_add_ec(CQ_CANNED, doopen);
4972.                     return ECMD_OK;
4973.                 }
4974.             }
4975.             if (levl[u.ux + x][u.uy + y].typ <= SCORR) {
4976.                 cmdq_add_ec(CQ_CANNED, dosearch);
4977.                 return ECMD_OK;
4978.             }
4979.             cmdq_add_ec(CQ_CANNED, move_funcs[dir][MV_WALK]);
4980.             return ECMD_OK;
4981.         }
4982.     } else {
4983.         /* convert without using floating point, allowing sloppy clicking */
4984.         if (x > 2 * abs(y))
4985.             x = 1, y = 0;
4986.         else if (y > 2 * abs(x))
4987.             x = 0, y = 1;
4988.         else if (x < -2 * abs(y))
4989.             x = -1, y = 0;
4990.         else if (y < -2 * abs(x))
4991.             x = 0, y = -1;
4992.         else
4993.             x = sgn(x), y = sgn(y);
4994. 
4995.         if (x == 0 && y == 0) {
4996.             /* map click on player to "rest" command */
4997.             cmdq_add_ec(CQ_CANNED, donull);
4998.             return ECMD_OK;
4999.         }
5000.         dir = xytodir(x, y);
5001.     }
5002. 
5003.     /* move, attack, etc. */
5004.     cmdq_add_ec(CQ_CANNED, move_funcs[dir][MV_WALK]);
5005.     return ECMD_OK;
5006. }
5007. 
5008. /* gather typed digits into a number in *count; return the next non-digit */
5009. char
5010. get_count(
5011.     const char *allowchars, /* what comes after digits; if Null, anything */
5012.     char inkey,          /* if caller already got first digit, this is it */
5013.     long maxcount,       /* if user tries to enter a bigger count, use this */
5014.     cmdcount_nht *count, /* primary output */
5015.     unsigned gc_flags)   /* control flags: GC_SAVEHIST, GC_ECHOFIRST */
5016. {
5017.     char qbuf[QBUFSZ];
5018.     int key, save_input_state = program_state.input_state;
5019.     long cnt = 0L, first = inkey ? (long) (inkey - '0') : 0L;
5020.     boolean backspaced = FALSE, showzero = TRUE,
5021.             /* should "Count: 123" go into message history? */
5022.             historicmsg = (gc_flags & GC_SAVEHIST) != 0,
5023.             /* put "Count: N" into mesg hist unless N is the same as the
5024.                [first digit] value passed in via 'inkey' */
5025.             conditionalmsg = (gc_flags & GC_CONDHIST) != 0,
5026.             /* normally "Count: 12" isn't echoed until the second digit */
5027.             echoalways = (gc_flags & GC_ECHOFIRST) != 0;
5028.     /* this should be done in port code so that we have erase_char
5029.        and kill_char available; we can at least fake erase_char */
5030. #define STANDBY_erase_char '\177'
5031. 
5032.     *count = 0;
5033.     for (;;) {
5034.         if (inkey) {
5035.             key = inkey;
5036.             inkey = '\0';
5037.         } else {
5038.             /* if readchar() has already been called in this loop, it will
5039.                have reset input_state; put that back to its previous value */
5040.             program_state.input_state = save_input_state;
5041.             key = readchar();
5042.         }
5043. 
5044.         if (digit(key)) {
5045.             long dgt = (long) (key - '0');
5046. 
5047.             /* cnt = (10 * cnt) + (key - '0'); */
5048.             cnt = AppendLongDigit(cnt, dgt);
5049.             if (cnt < 0L)
5050.                 cnt = 0L;
5051.             else if (maxcount > 0L && cnt > maxcount)
5052.                 cnt = maxcount;
5053.             /* if we've backed up to nothing, then typed 0, show that 0 */
5054.             showzero = (key == '0');
5055.         } else if (key == '\b' || key == STANDBY_erase_char) {
5056.             if (!cnt && !echoalways)
5057.                 break;
5058.             showzero = FALSE;
5059.             cnt = cnt / 10L;
5060.             backspaced = TRUE;
5061.         } else if (key == gc.Cmd.spkeys[NHKF_ESC]) {
5062.             break;
5063.         } else if (!allowchars || strchr(allowchars, key)) {
5064.             *count = (cmdcount_nht) cnt;
5065.             if ((long) *count != cnt)
5066.                 impossible("get_count: cmdcount_nht");
5067.             break;
5068.         }
5069. 
5070.         if (cnt > 9 || backspaced || echoalways) {
5071.             clear_nhwindow(WIN_MESSAGE);
5072.             if (backspaced && !cnt && !showzero) {
5073.                 Sprintf(qbuf, "Count: ");
5074.             } else {
5075.                 Sprintf(qbuf, "Count: %ld", cnt);
5076.                 backspaced = FALSE;
5077.             }
5078.             custompline(SUPPRESS_HISTORY, "%s", qbuf);
5079.             mark_synch();
5080.         }
5081.     }
5082. 
5083.     if (historicmsg || (conditionalmsg && *count != first)) {
5084.         Sprintf(qbuf, "Count: %ld ", *count);
5085.         (void) key2txt((uchar) key, eos(qbuf));
5086.         putmsghistory(qbuf, FALSE);
5087.     }
5088. 
5089.     return key;
5090. }
5091. 
5092. /* main command input routine when not repeating and not executing canned
5093.    commands; input comes via get_count() which collects repeat count if one
5094.    is present and returns next non-digit to us */
5095. staticfn int
5096. parse(void)
5097. {
5098.     int foo;
5099.     struct Cmd_bind *bind;
5100. 
5101.     iflags.in_parse = TRUE;
5102.     gc.command_count = 0;
5103.     svc.context.move = TRUE; /* assume next command will take game time */
5104.     flush_screen(1); /* Flush screen buffer. Put the cursor on the hero. */
5105. 
5106.     /* affects readchar() behavior for ESC iff 'altmeta' option is On;
5107.        is always reset to otherInp by readchar() */
5108.     program_state.input_state = commandInp;
5109. 
5110.     if (!gc.Cmd.num_pad || (foo = readchar()) == gc.Cmd.spkeys[NHKF_COUNT]) {
5111.         /* if 'num_pad' is On then readchar() has just reset input_state;
5112.            set it back to commandInp, so that get_count() supports 'altmeta';
5113.            otherwise "n<count>ESC<character>" becomes "n<count>ESC" (with
5114.            <character> not read from keyboard yet) rather than intended count
5115.            and meta keystroke "n<count>M-<character>" */
5116.         program_state.input_state = commandInp;
5117. 
5118.         foo = get_count((char *) 0, '\0', LARGEST_INT,
5119.                         &gc.command_count, GC_NOFLAGS);
5120.     }
5121.     gl.last_command_count = gc.command_count;
5122. 
5123.     if (foo == gc.Cmd.spkeys[NHKF_ESC]) { /* esc cancels count (TH) */
5124.         clear_nhwindow(WIN_MESSAGE);
5125.         gc.command_count = 0;
5126.         gl.last_command_count = 0;
5127.     } else if (gi.in_doagain) {
5128.         gc.command_count = gl.last_command_count;
5129.     } else if (foo && (bind = cmdbind_get(foo & 0xFF)) != 0
5130.                /* these shouldn't go into the do-again buffer */
5131.                && bind && bind->cmd
5132.                && (bind->cmd->ef_funct == do_repeat
5133.                    || bind->cmd->ef_funct == doprev_message
5134.                    /* this one might get put into the do-again buffer but
5135.                       only if the interface code tells the core to do it */
5136.                    || bind->cmd->ef_funct == doextcmd)) {
5137.         /* gc.command_count will be set again when we
5138.            re-enter with gi.in_doagain set true */
5139.         gc.command_count = gl.last_command_count;
5140.     }
5141. 
5142.     gm.multi = gc.command_count;
5143.     if (gm.multi)
5144.         gm.multi--;
5145. 
5146.     gc.cmd_key = foo;
5147.     clear_nhwindow(WIN_MESSAGE);
5148. 
5149.     iflags.in_parse = FALSE;
5150.     return gc.cmd_key;
5151. }
5152. 
5153. #ifdef HANGUPHANDLING
5154. /* some very old systems, or descendents of such systems, expect signal
5155.    handlers to have return type `int', but they don't actually inspect
5156.    the return value so we should be safe using `void' unconditionally */
5157. /*ARGUSED*/
5158. void
5159. hangup(
5160.     int sig_unused UNUSED)   /* called as signal() handler, so sent
5161.                               * at least one arg */
5162. {
5163.     if (program_state.exiting)
5164.         program_state.in_moveloop = 0;
5165.     nhwindows_hangup();
5166. #ifdef SAFERHANGUP
5167.     /* When using SAFERHANGUP, the done_hup flag is tested in rhack
5168.        and a couple of other places; actual hangup handling occurs then.
5169.        This is 'safer' because it disallows certain cheats and also
5170.        protects against losing objects in the process of being thrown,
5171.        but also potentially riskier because the disconnected program
5172.        must continue running longer before attempting a hangup save. */
5173.     program_state.done_hup++;
5174.     /* defer hangup iff game appears to be in progress */
5175.     if (program_state.in_moveloop
5176.         && program_state.something_worth_saving)
5177.         return;
5178. #endif /* SAFERHANGUP */
5179.     end_of_input();
5180. }
5181. 
5182. void
5183. end_of_input(void)
5184. {
5185. #ifdef NOSAVEONHANGUP
5186. #ifdef INSURANCE
5187.     if (flags.ins_chkpt && program_state.something_worth_saving)
5188.         program_state.preserve_locks = 1; /* keep files for recovery */
5189. #endif
5190.     program_state.something_worth_saving = 0; /* don't save */
5191. #endif
5192. 
5193.     if (In_tutorial(&u.uz))
5194.         program_state.something_worth_saving = 0; /* don't save in tutorial */
5195. 
5196. #ifndef SAFERHANGUP
5197.     if (!program_state.done_hup++)
5198. #endif
5199.         if (program_state.something_worth_saving)
5200.             (void) dosave0();
5201.     if (soundprocs.sound_exit_nhsound)
5202.         (*soundprocs.sound_exit_nhsound)("end_of_input");
5203.     if (iflags.window_inited)
5204.         exit_nhwindows((char *) 0);
5205.     clearlocks();
5206.     nh_terminate(EXIT_SUCCESS);
5207.     /*NOTREACHED*/ /* not necessarily true for vms... */
5208.     return;
5209. }
5210. #endif /* HANGUPHANDLING */
5211. 
5212. staticfn char
5213. readchar_core(coordxy *x, coordxy *y, int *mod)
5214. {
5215.     int sym;
5216. 
5217.     if (iflags.debug_fuzzer) {
5218.         sym = randomkey();
5219.         goto readchar_done;
5220.     }
5221.     if (*readchar_queue)
5222.         sym = *readchar_queue++;
5223.     else if (gi.in_doagain)
5224.         sym = pgetchar();
5225.     else
5226.         sym = nh_poskey(x, y, mod);
5227. 
5228. #ifdef NR_OF_EOFS
5229.     if (sym == EOF) {
5230.         int cnt = NR_OF_EOFS;
5231.         /*
5232.          * Some SYSV systems seem to return EOFs for various reasons
5233.          * (?like when one hits break or for interrupted systemcalls?),
5234.          * and we must see several before we quit.
5235.          */
5236.         do {
5237.             clearerr(stdin); /* omit if clearerr is undefined */
5238.             sym = pgetchar();
5239.         } while (--cnt && sym == EOF);
5240.     }
5241. #endif /* NR_OF_EOFS */
5242. 
5243.     if (sym == EOF) {
5244. #ifdef HANGUPHANDLING
5245.         hangup(0); /* call end_of_input() or set program_state.done_hup */
5246. #endif
5247.         sym = '\033';
5248. #ifdef ALTMETA
5249.     } else if (sym == '\033' && iflags.altmeta
5250.                && program_state.input_state != otherInp) {
5251.         /* iflags.altmeta: treat two character ``ESC c as single `M-c' but
5252.            only when we're called by parse() [possibly via get_count()]
5253.            or getpos() [to support Alt+digit] or getdir() [for arrow keys
5254.            under curses] */
5255.         sym = *readchar_queue ? *readchar_queue++ : pgetchar();
5256.         if (sym == EOF || sym == 0)
5257.             sym = '\033';
5258.         else if (sym != '\033')
5259.             sym |= 0200; /* force 8th bit on */
5260. #endif /*ALTMETA*/
5261.     } else if (sym == 0) {
5262.         /* click event */
5263.         gc.clicklook_cc.x = gc.clicklook_cc.y = -1;
5264.         click_to_cmd(*x, *y, *mod);
5265.     }
5266. 
5267.  readchar_done:
5268.     /* next readchar() will be for an ordinary char unless parse()
5269.        sets this back to non-zero */
5270.     program_state.input_state = otherInp;
5271.     return (char) sym;
5272. }
5273. 
5274. /* get a character */
5275. char
5276. readchar(void)
5277. {
5278.     char ch;
5279.     coordxy x = u.ux, y = u.uy;
5280.     int mod = 0;
5281. 
5282.     ch = readchar_core(&x, &y, &mod);
5283.     return ch;
5284. }
5285. 
5286. /* used by getpos() to accept mouse input as well as keyboard input */
5287. char
5288. readchar_poskey(coordxy *x, coordxy *y, int *mod)
5289. {
5290.     char ch;
5291. 
5292.     program_state.input_state = getposInp;
5293.     ch = readchar_core(x, y, mod);
5294.     return ch;
5295. }
5296. 
5297. /* '_' command, #travel, via keyboard rather than mouse click */
5298. staticfn int
5299. dotravel(void)
5300. {
5301.     coord cc;
5302. 
5303.     /*
5304.      * Traveling used to be a no-op if user toggled 'travel' option
5305.      * Off.  However, travel was initially implemented as a mouse-only
5306.      * command and the original purpose of the option was to be able
5307.      * to prevent clicks on the map from initiating travel.
5308.      *
5309.      * Travel via '_' came later.  Since it requires a destination--
5310.      * which offers the user a chance to cancel if it was accidental--
5311.      * there's no reason for the option to disable travel-by-keys.
5312.      */
5313. 
5314.     cc.x = iflags.travelcc.x;
5315.     cc.y = iflags.travelcc.y;
5316.     if (cc.x == 0 && cc.y == 0) {
5317.         /* No cached destination, start attempt from current position */
5318.         cc.x = u.ux;
5319.         cc.y = u.uy;
5320.     }
5321.     iflags.getloc_travelmode = TRUE;
5322.     if (iflags.menu_requested) {
5323.         int gfilt = iflags.getloc_filter;
5324. 
5325.         iflags.getloc_filter = GFILTER_VIEW;
5326.         if (!getpos_menu(&cc, GLOC_INTERESTING)) {
5327.             iflags.getloc_filter = gfilt;
5328.             iflags.getloc_travelmode = FALSE;
5329.             return ECMD_OK;
5330.         }
5331.         iflags.getloc_filter = gfilt;
5332.     } else {
5333.         pline("Where do you want to travel to?");
5334.         if (getpos(&cc, TRUE, "the desired destination") < 0) {
5335.             /* user pressed ESC */
5336.             iflags.getloc_travelmode = FALSE;
5337.             return ECMD_CANCEL;
5338.         }
5339.     }
5340.     iflags.travelcc.x = u.tx = cc.x;
5341.     iflags.travelcc.y = u.ty = cc.y;
5342. 
5343.     return dotravel_target();
5344. }
5345. 
5346. /* #retravel, travel to iflags.travelcc, which must be set */
5347. staticfn int
5348. dotravel_target(void)
5349. {
5350.     if (!isok(iflags.travelcc.x, iflags.travelcc.y)) {
5351.         /* assume <0,0>, the value assigned when travel reaches destination */
5352.         pline("No travel destination set.");
5353.         return ECMD_OK;
5354.     } else if (u_at(iflags.travelcc.x, iflags.travelcc.y)) {
5355.         /* maybe interrupted while traveling then just walked rest of way
5356.            so destination hasn't been reset yet */
5357.         You("are already here.");
5358.         iflags.travelcc.x = iflags.travelcc.y = 0;
5359.         return ECMD_OK;
5360.     }
5361. 
5362.     iflags.getloc_travelmode = FALSE;
5363. 
5364.     svc.context.travel = 1;
5365.     svc.context.travel1 = 1;
5366.     svc.context.run = 8;
5367.     svc.context.nopick = 1;
5368.     gd.domove_attempting |= DOMOVE_RUSH;
5369. 
5370.     if (!gm.multi)
5371.         gm.multi = max(COLNO, ROWNO);
5372.     u.last_str_turn = 0;
5373.     svc.context.mv = TRUE;
5374. 
5375.     domove();
5376.     return ECMD_TIME;
5377. }
5378. 
5379. /* mouse click look command */
5380. staticfn int
5381. doclicklook(void)
5382. {
5383.     if (!isok(gc.clicklook_cc.x, gc.clicklook_cc.y))
5384.         return ECMD_OK;
5385. 
5386.     svc.context.move = FALSE;
5387.     auto_describe(gc.clicklook_cc.x, gc.clicklook_cc.y);
5388. 
5389.     return ECMD_OK;
5390. }
5391. 
5392. /* can we use menu entries to respond to a query? */
5393. staticfn boolean
5394. yn_menuable_resp(const char *resp)
5395. {
5396.     return iflags.query_menu && iflags.window_inited
5397.         && (resp == ynchars || resp == ynqchars || resp == ynaqchars
5398.             || resp == rightleftchars || resp == hidespinchars);
5399. }
5400. 
5401. staticfn void
5402. yn_func_menu_opt(winid win, char key, const char *text, char def)
5403. {
5404.     anything any;
5405. 
5406.     any = cg.zeroany;
5407.     any.a_char = key;
5408.     add_menu(win, &nul_glyphinfo, &any, key, 0,
5409.              ATR_NONE, NO_COLOR, text,
5410.              (def == key) ? MENU_ITEMFLAGS_SELECTED
5411.                           : MENU_ITEMFLAGS_NONE);
5412. 
5413. }
5414. 
5415. /* use a menu to ask a specific response to a query.
5416.    returns TRUE if the menu was shown to the user.
5417.    puts the response char into res. */
5418. staticfn boolean
5419. yn_function_menu(
5420.     const char *query,
5421.     const char *resp,
5422.     char def,
5423.     char *res)
5424. {
5425.     if (yn_menuable_resp(resp)) {
5426.         winid win = create_nhwindow(NHW_MENU);
5427.         menu_item *sel;
5428.         int n;
5429.         char keybuf[QBUFSZ];
5430. 
5431.         start_menu(win, MENU_BEHAVE_STANDARD);
5432.         if (resp == rightleftchars) {
5433.             yn_func_menu_opt(win, 'r', "Right", def);
5434.             yn_func_menu_opt(win, 'l', "Left", def);
5435.         } else if (resp == hidespinchars) {
5436.             yn_func_menu_opt(win, 'h', "Hide", def);
5437.             yn_func_menu_opt(win, 's', "Spin a web", def);
5438.         } else {
5439.             yn_func_menu_opt(win, 'y', "Yes", def);
5440.             yn_func_menu_opt(win, 'n', "No", def);
5441.         }
5442.         if (resp == ynaqchars)
5443.             yn_func_menu_opt(win, 'a', "All", def);
5444.         if (resp == ynqchars || resp == ynaqchars || resp == hidespinchars)
5445.             yn_func_menu_opt(win, 'q', "Quit", def);
5446.         end_menu(win, query);
5447.         n = select_menu(win, PICK_ONE, &sel);
5448.         destroy_nhwindow(win);
5449.         if (n > 0) {
5450.             *res = sel[0].item.a_char;
5451.             /* two were selected? use the one that wasn't the default */
5452.             if (n > 1 && *res == def)
5453.                 *res = sel[1].item.a_char;
5454.             free((genericptr_t) sel);
5455.         } else {
5456.             *res = def;
5457.         }
5458.         pline("%s %s", query, key2txt(*res, keybuf));
5459.         clear_nhwindow(WIN_MESSAGE);
5460.         return TRUE;
5461.     }
5462.     return FALSE;
5463. }
5464. 
5465. /*
5466.  *   Parameter validator for generic yes/no function to prevent
5467.  *   the core from sending too long a prompt string to the
5468.  *   window port causing a buffer overflow there.
5469.  */
5470. char
5471. yn_function(
5472.     const char *query,
5473.     const char *resp,
5474.     char def,
5475.     boolean addcmdq)
5476. {
5477.     char res = '\033', qbuf[QBUFSZ];
5478.     struct _cmd_queue cq, *cmdq;
5479. #ifdef DUMPLOG_CORE
5480.     unsigned idx = gs.saved_pline_index;
5481.     /* buffer to hold query+space+formatted_single_char_response */
5482.     char dumplog_buf[QBUFSZ + 1 + 15]; /* [QBUFSZ+1+7] should suffice */
5483. #endif
5484. 
5485.     iflags.last_msg = PLNMSG_UNKNOWN; /* most recent pline is clobbered */
5486. 
5487.     /* maximum acceptable length is QBUFSZ-1 */
5488.     if (strlen(query) >= QBUFSZ) {
5489.         /* caller shouldn't have passed anything this long */
5490.         paniclog("Query truncated: ", query);
5491.         (void) strncpy(qbuf, query, QBUFSZ - 1 - 3);
5492.         Strcpy(&qbuf[QBUFSZ - 1 - 3], "...");
5493.         query = qbuf;
5494.     }
5495. 
5496.     if (addcmdq && (cmdq = cmdq_pop()) != 0) {
5497.         cq = *cmdq;
5498.         free(cmdq);
5499.     } else {
5500.         cq.typ = CMDQ_USER_INPUT;
5501.         cq.key = '\0'; /* lint suppression */
5502.     }
5503. 
5504.     if (cq.typ != CMDQ_USER_INPUT) {
5505.         if (cq.typ == CMDQ_KEY)
5506.             res = cq.key;
5507.         else
5508.             cmdq_clear(CQ_CANNED); /* 'res' is ESC */
5509.         addcmdq = FALSE;
5510. 
5511.     /* for the fuzzer, usually force a valid response, but sometimes let
5512.        it exercise windowport yn_function and invalid response handling */
5513.     } else if (iflags.debug_fuzzer && resp && *resp && rn2(20)) {
5514.         int ln = (int) strlen(resp), ridx = rn2(ln);
5515. 
5516.         res = resp[ridx];
5517.         /* if valid-responses includes ESC followed by unshown candidates
5518.            and we randomly picked the ESC, try again with only whatever is
5519.            before it; be careful to avoid rn2(0) */
5520.         if (res == '\033') {
5521.             if (ln > 1) {
5522.                 /* if ESC is at start (ridx==0), pick something after it */
5523.                 ridx = (ridx == 0) ? (1 + rn2(ln - 1)) : rn2(ridx);
5524.                 res = resp[ridx];
5525.             } else {
5526.                 /* ESC is the only thing (ln==1); something is strange... */
5527.                 res = def; /* might be '\0' */
5528.             }
5529.         }
5530. 
5531.     } else {
5532. #ifdef SND_SPEECH
5533.         if ((gp.pline_flags & PLINE_SPEECH) != 0) {
5534.             sound_speak(query);
5535.             gp.pline_flags &= ~PLINE_SPEECH;
5536.         }
5537. #endif
5538.         if (!yn_function_menu(query, resp, def, &res)) {
5539.             res = (*windowprocs.win_yn_function)(query, resp, def);
5540.         }
5541.     }
5542.     if (addcmdq)
5543.         cmdq_add_key(CQ_REPEAT, res);
5544. 
5545. #ifdef DUMPLOG_CORE
5546.     if (idx == gs.saved_pline_index) {
5547.         /* when idx is still the same as gs.saved_pline_index, the interface
5548.            didn't put the prompt into gs.saved_plines[]; we put a simplified
5549.            version in there now (without response choices or default) */
5550.         Sprintf(dumplog_buf, "%s ", query);
5551.         (void) key2txt((uchar) res, eos(dumplog_buf));
5552.         dumplogmsg(dumplog_buf);
5553.     }
5554. #endif
5555.     /* should not happen but cq.key has been observed to not obey 'resp';
5556.        it is most likely caused by saving a keystroke that was just used
5557.        to answer a context-sensitive prompt, then using the do-again
5558.        command with context that has changed */
5559.     if (resp && *resp && res && !strchr(resp, res)) {
5560.         /* this probably needs refinement since caller is expecting something
5561.            within 'resp' and ESC won't be (it could be present, but as a flag
5562.            for unshown possibilities rather than as acceptable input) */
5563.         int altres = def ? def : '\033';
5564. 
5565.         if (!gi.in_doagain || wizard) {
5566. /*TEMP*/    xint8 fuzzing = iflags.debug_fuzzer;
5567.             char dbg_buf[BUFSZ];
5568. 
5569.             Snprintf(dbg_buf, sizeof dbg_buf, "%s [%s] (%s)",
5570.                      query, resp ? resp : "", def ? visctrl(def) : "");
5571.             paniclog("yn debug", dbg_buf);
5572. /*TEMP*/    /* don't let this known problem kill the fuzzer */
5573. /*TEMP*/    iflags.debug_fuzzer = fuzzer_impossible_continue;
5574.             impossible("yn_function() returned '%s'; using '%s' instead",
5575.                        visctrl(res), visctrl(altres));
5576. /*TEMP*/    iflags.debug_fuzzer = fuzzing;
5577.         }
5578.         res = altres;
5579.     }
5580.     /* in case we're called via getdir() which sets input_state */
5581.     program_state.input_state = otherInp;
5582.     return res;
5583. }
5584. 
5585. /* for paranoid_confirm:quit,die,attack,&c prompting; allows yes, n|no,
5586.    or q|quit; result is one of 'y' or 'n' or 'q'; ESC yields 'q' */
5587. char
5588. paranoid_ynq(
5589.     boolean be_paranoid,
5590.     const char *prompt,
5591.     boolean accept_q)
5592. {
5593.     char c = 'n'; /* default result */
5594. 
5595.     /* when paranoid, player must respond with "yes" rather than just 'y'
5596.        to give the go-ahead for this query; default is "no" unless the
5597.        ParanoidConfirm flag is set in which case there's no default */
5598.     if (be_paranoid) {
5599.         char pbuf[BUFSZ], qbuf[QBUFSZ], ans[BUFSZ];
5600.         const char *promptprefix = "", /* empty for first iteration */
5601.             *responsetype = ParanoidConfirm ? (accept_q ? "[yes|no|quit]"
5602.                                                : "[yes|no]")
5603.                                             /* default of 'n' is shown for
5604.                                              * the !ParanoidConfirm cases */
5605.                                             : (accept_q ? "[yes|n|q] (n)"
5606.                                                : "[yes|n] (n)");
5607.         int k, trylimit = 6; /* 1 normal, 5 more with "Yes or No:" prefix */
5608. 
5609.         copynchars(pbuf, prompt, BUFSZ - 1);
5610.         /* in addition to being paranoid about this particular
5611.            query, we might be even more paranoid about all paranoia
5612.            responses (ie, ParanoidConfirm is set) in which case we
5613.            require "no" to reject in addition to "yes" to confirm
5614.            (except we won't loop if response is ESC; it means no) */
5615.         do {
5616.             /* make sure we won't overflow a QBUFSZ sized buffer */
5617.             k = (int) (strlen(promptprefix) + 1 + strlen(responsetype));
5618.             if ((int) strlen(pbuf) + k > QBUFSZ - 1) {
5619.                 /* chop off some at the end */
5620.                 Strcpy(pbuf + (QBUFSZ - 1) - k - 4, "...?"); /* -4: "...?" */
5621.             }
5622. 
5623.             Snprintf(qbuf, sizeof qbuf, "%s%s %s", promptprefix, pbuf,
5624.                      responsetype);
5625.             *ans = '\0';
5626.             getlin(qbuf, ans);
5627.             (void) mungspaces(ans);
5628.             if (!strcmpi(ans, "yes")) {
5629.                 c = 'y';
5630.                 break;
5631.             }
5632.             if (!strcmpi(ans, "quit") || *ans == '\033') {
5633.                 c = 'q';
5634.                 break;
5635.             }
5636.             /* we don't bother adding "or \"Quit\"" for the accept_q case */
5637.             promptprefix = "\"Yes\" or \"No\": ";
5638.             /* for empty input, return value c will already be 'n' */
5639.         } while (ParanoidConfirm && strcmpi(ans, "no") && --trylimit);
5640.     } else if (accept_q) {
5641.         /* 'y', 'n', or 'q' */
5642.         c = yn_function(prompt, ynqchars, 'n', FALSE);
5643.     } else {
5644.         /* 'y' or 'n' */
5645.         c = yn_function(prompt, ynchars, 'n', FALSE);
5646.     }
5647.     if (c != 'y' && (c != 'q' || !accept_q))
5648.         c = 'n';
5649.     return c;
5650. }
5651. 
5652. /* for paranoid_confirm:quit,die,attack,&c prompting; allows yes or n|no;
5653.    result is True for yes; n|no and ESC yield False */
5654. boolean
5655. paranoid_query(boolean be_paranoid, const char *prompt)
5656. {
5657.     return (paranoid_ynq(be_paranoid, prompt, FALSE) == 'y');
5658. }
5659. 
5660. /* ^Z command, #suspend */
5661. staticfn int
5662. dosuspend_core(void)
5663. {
5664. #ifdef SUSPEND
5665.     /* Does current window system support suspend? */
5666.     if ((*windowprocs.win_can_suspend)()) {
5667.         time_t now = getnow();
5668. 
5669.         urealtime.realtime += timet_delta(now, urealtime.start_timing);
5670.         urealtime.start_timing = now; /* as a safeguard against panic save */
5671.         /* NB: SYSCF SHELLERS handled in port code. */
5672.         dosuspend();
5673.         urealtime.start_timing = getnow(); /* resume keeping track of time */
5674.     } else
5675. #endif
5676.         Norep(cmdnotavail, "#suspend");
5677.     return ECMD_OK;
5678. }
5679. 
5680. /* '!' command, #shell */
5681. staticfn int
5682. dosh_core(void)
5683. {
5684. #ifdef SHELL
5685.     time_t now = getnow();
5686. 
5687.     urealtime.realtime += timet_delta(now, urealtime.start_timing);
5688.     urealtime.start_timing = now; /* (see dosuspend_core) */
5689.     /* access restrictions, if any, are handled in port code */
5690.     dosh();
5691.     urealtime.start_timing = getnow();
5692. #else
5693.     Norep(cmdnotavail, "#shell");
5694. #endif
5695.     return ECMD_OK;
5696. }
5697. 
5698. staticfn int
5699. dummyfunction(void)
5700. {
5701.     return ECMD_CANCEL;
5702. }
5703. 
5704. /*cmd.c*/