OSDN Git Service

[Refactor] #37353 職業ID定義を player-class.h へ移動.
[hengband/hengband.git] / src / util.c
1 /* File: util.c */
2
3 /*
4  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
5  *
6  * This software may be copied and distributed for educational, research,
7  * and not for profit purposes provided that this copyright and statement
8  * are included in all such copies.  Other copyrights may also apply.
9  */
10
11 /* Purpose: Angband utilities -BEN- */
12
13 #include "angband.h"
14 #include "core.h"
15 #include "term.h"
16 #include "util.h"
17 #include "files.h"
18 #include "monsterrace-hook.h"
19 #include "view-mainwindow.h"
20 #include "quest.h"
21 #include "floor.h"
22 #include "world.h"
23 #include "cmd-dump.h"
24 #include "japanese.h"
25 #include "player-class.h"
26
27 /*!
28  * 10進数から16進数への変換テーブル /
29  * Global array for converting numbers to uppercase hecidecimal digit
30  * This array can also be used to convert a number to an octal digit
31  */
32 const char hexsym[16] =
33 {
34         '0', '1', '2', '3', '4', '5', '6', '7',
35         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
36 };
37
38 /*
39  * Keymaps for each "mode" associated with each keypress.
40  */
41 concptr keymap_act[KEYMAP_MODES][256];
42
43 /*
44  * The next "free" index to use
45  */
46 u32b message__next;
47
48 /*
49  * The index of the oldest message (none yet)
50  */
51 u32b message__last;
52
53 /*
54  * The next "free" offset
55  */
56 u32b message__head;
57
58 /*
59  * The offset to the oldest used char (none yet)
60  */
61 u32b message__tail;
62
63 /*
64  * The array of offsets, by index [MESSAGE_MAX]
65  */
66 u32b *message__ptr;
67
68 /*
69  * The array of chars, by offset [MESSAGE_BUF]
70  */
71 char *message__buf;
72
73 bool msg_flag;                  /* Used in msg_print() for "buffering" */
74
75 /*
76  * Number of active macros.
77  */
78 s16b macro__num;
79
80 /*
81  * Array of macro patterns [MACRO_MAX]
82  */
83 concptr *macro__pat;
84
85 /*
86  * Array of macro actions [MACRO_MAX]
87  */
88 concptr *macro__act;
89
90 /*
91  * Array of macro types [MACRO_MAX]
92  */
93 bool *macro__cmd;
94
95 /*
96  * Current macro action [1024]
97  */
98 char *macro__buf;
99
100 bool get_com_no_macros = FALSE; /* Expand macros in "get_com" or not */
101
102 bool inkey_base;                /* See the "inkey()" function */
103 bool inkey_xtra;                /* See the "inkey()" function */
104 bool inkey_scan;                /* See the "inkey()" function */
105 bool inkey_flag;                /* See the "inkey()" function */
106
107 static int num_more = 0;
108
109 /* Save macro trigger string for use in inkey_special() */
110 static char inkey_macro_trigger_string[1024];
111
112 int max_macrotrigger = 0; /*!< 現在登録中のマクロ(トリガー)の数 */
113 concptr macro_template = NULL; /*!< Angband設定ファイルのT: タグ情報から読み込んだ長いTコードを処理するために利用する文字列ポインタ */
114 concptr macro_modifier_chr; /*!< &x# で指定されるマクロトリガーに関する情報を記録する文字列ポインタ */
115 concptr macro_modifier_name[MAX_MACRO_MOD]; /*!< マクロ上で取り扱う特殊キーを文字列上で表現するためのフォーマットを記録した文字列ポインタ配列 */
116 concptr macro_trigger_name[MAX_MACRO_TRIG]; /*!< マクロのトリガーコード */
117 concptr macro_trigger_keycode[2][MAX_MACRO_TRIG];  /*!< マクロの内容 */
118
119 s16b command_cmd;               /* Current "Angband Command" */
120 COMMAND_ARG command_arg;        /*!< 各種コマンドの汎用的な引数として扱う / Gives argument of current command */
121 COMMAND_NUM command_rep;        /*!< 各種コマンドの汎用的なリピート数として扱う / Gives repetition of current command */
122 DIRECTION command_dir;          /*!< 各種コマンドの汎用的な方向値処理として扱う/ Gives direction of current command */
123 s16b command_see;               /* See "object1.c" */
124 s16b command_wrk;               /* See "object1.c" */
125 TERM_LEN command_gap = 999;         /* See "object1.c" */
126 s16b command_new;               /* Command chaining from inven/equip view */
127
128
129 #if 0
130 #ifndef HAS_STRICMP
131
132 /*
133  * For those systems that don't have "stricmp()"
134  *
135  * Compare the two strings "a" and "b" ala "strcmp()" ignoring case.
136  */
137 int stricmp(concptr a, concptr b)
138 {
139         concptr s1, s2;
140         char z1, z2;
141
142         /* Scan the strings */
143         for (s1 = a, s2 = b; TRUE; s1++, s2++)
144         {
145                 z1 = FORCEUPPER(*s1);
146                 z2 = FORCEUPPER(*s2);
147                 if (z1 < z2) return (-1);
148                 if (z1 > z2) return (1);
149                 if (!z1) return (0);
150         }
151 }
152
153 #endif /* HAS_STRICMP */
154 #endif /* 0 */
155
156 #ifdef SET_UID
157
158 # ifndef HAVE_USLEEP
159
160 /*
161  * For those systems that don't have "usleep()" but need it.
162  *
163  * Fake "usleep()" function grabbed from the inl netrek server -cba
164  */
165 int usleep(huge usecs)
166 {
167         struct timeval      Timer;
168
169         int                 nfds = 0;
170
171 #ifdef FD_SET
172         fd_set          *no_fds = NULL;
173 #else
174         int                     *no_fds = NULL;
175 #endif
176
177
178         /* Was: int readfds, writefds, exceptfds; */
179         /* Was: readfds = writefds = exceptfds = 0; */
180
181
182         /* Paranoia -- No excessive sleeping */
183         if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
184
185         /* Wait for it */
186         Timer.tv_sec = (usecs / 1000000L);
187         Timer.tv_usec = (usecs % 1000000L);
188
189         /* Wait for it */
190         if (select(nfds, no_fds, no_fds, no_fds, &Timer) < 0)
191         {
192                 /* Hack -- ignore interrupts */
193                 if (errno != EINTR) return -1;
194         }
195
196         /* Success */
197         return 0;
198 }
199
200 # endif
201
202
203 /*
204  * Hack -- External functions
205  */
206 #ifdef SET_UID
207 extern struct passwd *getpwuid(uid_t uid);
208 extern struct passwd *getpwnam(concptr name);
209 #endif
210
211
212 /*
213  * Find a default user name from the system.
214  */
215 void user_name(char *buf, int id)
216 {
217         struct passwd *pw;
218
219         /* Look up the user name */
220         if ((pw = getpwuid(id)))
221         {
222                 (void)strcpy(buf, pw->pw_name);
223                 buf[16] = '\0';
224
225 #ifdef CAPITALIZE_USER_NAME
226                 /* Hack -- capitalize the user name */
227 #ifdef JP
228                 if (!iskanji(buf[0]))
229 #endif
230                         if (islower(buf[0]))
231                                 buf[0] = toupper(buf[0]);
232 #endif /* CAPITALIZE_USER_NAME */
233
234                 return;
235         }
236
237         /* Oops.  Hack -- default to "PLAYER" */
238         strcpy(buf, "PLAYER");
239 }
240
241 #endif /* SET_UID */
242
243
244
245
246 /*
247  * The concept of the "file" routines below (and elsewhere) is that all
248  * file handling should be done using as few routines as possible, since
249  * every machine is slightly different, but these routines always have the
250  * same semantics.
251  *
252  * In fact, perhaps we should use the "path_parse()" routine below to convert
253  * from "canonical" filenames (optional leading tilde's, internal wildcards,
254  * slash as the path seperator, etc) to "system" filenames (no special symbols,
255  * system-specific path seperator, etc).  This would allow the program itself
256  * to assume that all filenames are "Unix" filenames, and explicitly "extract"
257  * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
258  *
259  * Note that "path_temp" should probably return a "canonical" filename.
260  *
261  * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
262  * and "my_move()" and "my_copy()" should all take "canonical" filenames.
263  *
264  * Note that "canonical" filenames use a leading "slash" to indicate an absolute
265  * path, and a leading "tilde" to indicate a special directory, and default to a
266  * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
267  * use of a "special drive", and then the rest of the path is parsed "normally",
268  * and MACINTOSH uses a leading colon to indicate a relative path, and an embedded
269  * colon to indicate a "drive plus absolute path", and finally defaults to a file
270  * in the current working directory, which may or may not be defined.
271  *
272  * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
273  */
274
275
276 #ifdef ACORN
277
278
279 /*
280  * Most of the "file" routines for "ACORN" should be in "main-acn.c"
281  */
282
283
284 #else /* ACORN */
285
286
287 #ifdef SET_UID
288
289 /*
290  * Extract a "parsed" path from an initial filename
291  * Normally, we simply copy the filename into the buffer
292  * But leading tilde symbols must be handled in a special way
293  * Replace "~user/" by the home directory of the user named "user"
294  * Replace "~/" by the home directory of the current user
295  */
296 errr path_parse(char *buf, int max, concptr file)
297 {
298         concptr         u, s;
299         struct passwd   *pw;
300         char            user[128];
301
302
303         /* Assume no result */
304         buf[0] = '\0';
305
306         /* No file? */
307         if (!file) return (-1);
308
309         /* File needs no parsing */
310         if (file[0] != '~')
311         {
312                 (void)strnfmt(buf, max, "%s", file);
313                 return (0);
314         }
315
316         /* Point at the user */
317         u = file+1;
318
319         /* Look for non-user portion of the file */
320         s = my_strstr(u, PATH_SEP);
321
322         /* Hack -- no long user names */
323         if (s && (s >= u + sizeof(user))) return (1);
324
325         /* Extract a user name */
326         if (s)
327         {
328                 int i;
329                 for (i = 0; u < s; ++i) user[i] = *u++;
330                 user[i] = '\0';
331                 u = user;
332         }
333
334         /* Look up the "current" user */
335         if (u[0] == '\0') u = getlogin();
336
337         /* Look up a user (or "current" user) */
338         if (u) pw = getpwnam(u);
339         else pw = getpwuid(getuid());
340
341         /* Nothing found? */
342         if (!pw) return (1);
343
344         /* Make use of the info */
345         if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
346         else strnfmt(buf, max, "%s", pw->pw_dir);
347
348         /* Success */
349         return (0);
350 }
351
352
353 #else /* SET_UID */
354
355
356 /*
357  * Extract a "parsed" path from an initial filename
358  *
359  * This requires no special processing on simple machines,
360  * except for verifying the size of the filename.
361  */
362 errr path_parse(char *buf, int max, concptr file)
363 {
364         /* Accept the filename */
365         (void)strnfmt(buf, max, "%s", file);
366
367 #if defined(MAC_MPW) && defined(CARBON)
368      /* Fix it according to the current operating system */
369     convert_pathname(buf);
370 #endif /* MAC_MPW && CARBON */
371
372         /* Success */
373         return (0);
374 }
375
376
377 #endif /* SET_UID */
378
379
380 #ifndef HAVE_MKSTEMP
381
382 /*
383  * Hack -- acquire a "temporary" file name if possible
384  *
385  * This filename is always in "system-specific" form.
386  */
387 static errr path_temp(char *buf, int max)
388 {
389         concptr s;
390
391         /* Temp file */
392         s = tmpnam(NULL);
393
394         if (!s) return (-1);
395
396         /* Format to length */
397 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
398         (void)strnfmt(buf, max, "%s", s);
399 #else
400         (void)strnfmt(buf, max, ".%s", s);
401 #endif
402
403         /* Success */
404         return (0);
405 }
406
407 #endif
408
409 /*
410  * Create a new path by appending a file (or directory) to a path.
411  *
412  * This requires no special processing on simple machines, except
413  * for verifying the size of the filename, but note the ability to
414  * bypass the given "path" with certain special file-names.
415  *
416  * Note that the "file" may actually be a "sub-path", including
417  * a path and a file.
418  *
419  * Note that this function yields a path which must be "parsed"
420  * using the "parse" function above.
421  */
422 errr path_build(char *buf, int max, concptr path, concptr file)
423 {
424         /* Special file */
425         if (file[0] == '~')
426         {
427                 /* Use the file itself */
428                 (void)strnfmt(buf, max, "%s", file);
429         }
430
431         /* Absolute file, on "normal" systems */
432         else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
433         {
434                 /* Use the file itself */
435                 (void)strnfmt(buf, max, "%s", file);
436         }
437
438         /* No path given */
439         else if (!path[0])
440         {
441                 /* Use the file itself */
442                 (void)strnfmt(buf, max, "%s", file);
443         }
444
445         /* Path and File */
446         else
447         {
448                 /* Build the new path */
449                 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
450         }
451
452         /* Success */
453         return (0);
454 }
455
456
457 /*
458  * Hack -- replacement for "fopen()"
459  */
460 FILE *my_fopen(concptr file, concptr mode)
461 {
462         char buf[1024];
463
464 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
465         FILE *tempfff;
466 #endif
467
468         /* Hack -- Try to parse the path */
469         if (path_parse(buf, 1024, file)) return (NULL);
470
471 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
472         if (my_strchr(mode, 'w'))
473         {
474                 /* setting file type/creator */
475                 tempfff = fopen(buf, mode);
476                 fsetfileinfo(buf, _fcreator, _ftype);
477                 fclose(tempfff);
478         }
479 #endif
480
481         /* Attempt to fopen the file anyway */
482         return (fopen(buf, mode));
483 }
484
485
486 /*
487  * Hack -- replacement for "fclose()"
488  */
489 errr my_fclose(FILE *fff)
490 {
491         /* Require a file */
492         if (!fff) return (-1);
493
494         /* Close, check for error */
495         if (fclose(fff) == EOF) return (1);
496
497         /* Success */
498         return (0);
499 }
500
501
502 #endif /* ACORN */
503
504
505 #ifdef HAVE_MKSTEMP
506
507 FILE *my_fopen_temp(char *buf, int max)
508 {
509         int fd;
510
511         /* Prepare the buffer for mkstemp */
512         strncpy(buf, "/tmp/anXXXXXX", max);
513
514         /* Secure creation of a temporary file */
515         fd = mkstemp(buf);
516
517         /* Check the file-descriptor */
518         if (fd < 0) return (NULL);
519
520         /* Return a file stream */
521         return (fdopen(fd, "w"));
522 }
523
524 #else /* HAVE_MKSTEMP */
525
526 FILE *my_fopen_temp(char *buf, int max)
527 {
528         /* Generate a temporary filename */
529         if (path_temp(buf, max)) return (NULL);
530
531         /* Open the file */
532         return (my_fopen(buf, "w"));
533 }
534
535 #endif /* HAVE_MKSTEMP */
536
537
538 /*
539  * Hack -- replacement for "fgets()"
540  *
541  * Read a string, without a newline, to a file
542  *
543  * Process tabs, strip internal non-printables
544  */
545 errr my_fgets(FILE *fff, char *buf, huge n)
546 {
547         huge i = 0;
548         char *s;
549         char tmp[1024];
550
551         /* Read a line */
552         if (fgets(tmp, 1024, fff))
553         {
554 #ifdef JP
555                 guess_convert_to_system_encoding(tmp, sizeof(tmp));
556 #endif
557
558                 /* Convert weirdness */
559                 for (s = tmp; *s; s++)
560                 {
561 #if defined(MACINTOSH) || defined(MACH_O_CARBON)
562
563                         /*
564                          * Be nice to the Macintosh, where a file can have Mac or Unix
565                          * end of line, especially since the introduction of OS X.
566                          * MPW tools were also very tolerant to the Unix EOL.
567                          */
568                         if (*s == '\r') *s = '\n';
569
570 #endif /* MACINTOSH || MACH_O_CARBON */
571
572                         /* Handle newline */
573                         if (*s == '\n')
574                         {
575                                 /* Terminate */
576                                 buf[i] = '\0';
577
578                                 /* Success */
579                                 return (0);
580                         }
581
582                         /* Handle tabs */
583                         else if (*s == '\t')
584                         {
585                                 /* Hack -- require room */
586                                 if (i + 8 >= n) break;
587
588                                 /* Append a space */
589                                 buf[i++] = ' ';
590
591                                 /* Append some more spaces */
592                                 while (0 != (i % 8)) buf[i++] = ' ';
593                         }
594
595 #ifdef JP
596                         else if (iskanji(*s))
597                         {
598                                 if (!s[1]) break;
599                                 buf[i++] = *s++;
600                                 buf[i++] = *s;
601                         }
602
603                         /* 半角かなに対応 */
604                         else if (iskana(*s))
605                         {
606                                 buf[i++] = *s;
607                                 if (i >= n) break;
608                         }
609 #endif
610                         /* Handle printables */
611                         else if (isprint((unsigned char)*s))
612                         {
613                                 /* Copy */
614                                 buf[i++] = *s;
615
616                                 /* Check length */
617                                 if (i >= n) break;
618                         }
619                 }
620                 /* No newline character, but terminate */
621                 buf[i] = '\0';
622
623                 /* Success */
624                 return (0);
625         }
626
627         /* Nothing */
628         buf[0] = '\0';
629
630         /* Failure */
631         return (1);
632 }
633
634
635 /*
636  * Hack -- replacement for "fputs()"
637  * Dump a string, plus a newline, to a file
638  * Process internal weirdness?
639  */
640 errr my_fputs(FILE *fff, concptr buf, huge n)
641 {
642         /* XXX XXX */
643         n = n ? n : 0;
644
645         /* Dump, ignore errors */
646         (void)fprintf(fff, "%s\n", buf);
647
648         /* Success */
649         return (0);
650 }
651
652
653 #ifdef ACORN
654
655
656 /*
657  * Most of the "file" routines for "ACORN" should be in "main-acn.c"
658  *
659  * Many of them can be rewritten now that only "fd_open()" and "fd_make()"
660  * and "my_fopen()" should ever create files.
661  */
662
663
664 #else /* ACORN */
665
666
667 /*
668  * The Macintosh is a little bit brain-dead sometimes
669  */
670 #ifdef MACINTOSH
671 # define open(N,F,M) \
672 ((M), open((char*)(N),F))
673 # define write(F,B,S) \
674 write(F,(char*)(B),S)
675 #endif /* MACINTOSH */
676
677
678 /*
679  * Several systems have no "O_BINARY" flag
680  */
681 #ifndef O_BINARY
682 # define O_BINARY 0
683 #endif /* O_BINARY */
684
685
686 /*
687  * Hack -- attempt to delete a file
688  */
689 errr fd_kill(concptr file)
690 {
691         char buf[1024];
692
693         /* Hack -- Try to parse the path */
694         if (path_parse(buf, 1024, file)) return (-1);
695
696         /* Remove */
697         (void)remove(buf);
698
699         return (0);
700 }
701
702
703 /*
704  * Hack -- attempt to move a file
705  */
706 errr fd_move(concptr file, concptr what)
707 {
708         char buf[1024];
709         char aux[1024];
710
711         /* Hack -- Try to parse the path */
712         if (path_parse(buf, 1024, file)) return (-1);
713
714         /* Hack -- Try to parse the path */
715         if (path_parse(aux, 1024, what)) return (-1);
716
717         /* Rename */
718         (void)rename(buf, aux);
719
720         return (0);
721 }
722
723
724 /*
725  * Hack -- attempt to copy a file
726  */
727 errr fd_copy(concptr file, concptr what)
728 {
729         char buf[1024];
730         char aux[1024];
731         int read_num;
732         int src_fd, dst_fd;
733
734         /* Hack -- Try to parse the path */
735         if (path_parse(buf, 1024, file)) return (-1);
736
737         /* Hack -- Try to parse the path */
738         if (path_parse(aux, 1024, what)) return (-1);
739
740         /* Open source file */
741         src_fd = fd_open(buf, O_RDONLY);
742         if (src_fd < 0) return (-1);
743
744         /* Open destination file */
745         dst_fd = fd_open(aux, O_WRONLY|O_TRUNC|O_CREAT);
746         if (dst_fd < 0) return (-1);
747
748         /* Copy */
749         while ((read_num = read(src_fd, buf, 1024)) > 0)
750         {
751                 int write_num = 0;
752                 while (write_num < read_num)
753                 {
754                         int ret = write(dst_fd, buf + write_num, read_num - write_num);
755                         if (ret < 0) {
756                                 /* Close files */
757                                 fd_close(src_fd);
758                                 fd_close(dst_fd);
759
760                                 return ret;
761                         }
762                         write_num += ret;
763                 }
764         }
765
766         /* Close files */
767         fd_close(src_fd);
768         fd_close(dst_fd);
769
770         return (0);
771 }
772
773 /*
774  * Hack -- attempt to open a file descriptor (create file)
775  * This function should fail if the file already exists
776  * Note that we assume that the file should be "binary"
777  */
778 int fd_make(concptr file, BIT_FLAGS mode)
779 {
780         char buf[1024];
781
782         /* Hack -- Try to parse the path */
783         if (path_parse(buf, 1024, file)) return (-1);
784
785 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
786         {
787                 int fdes;
788                 /* Create the file, fail if exists, write-only, binary */
789                 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
790                 /* Set creator and type if the file is successfully opened */
791                 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
792                 /* Return the descriptor */
793                 return (fdes);
794         }
795 #else
796         /* Create the file, fail if exists, write-only, binary */
797         return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
798 #endif
799
800 }
801
802
803 /*
804  * Hack -- attempt to open a file descriptor (existing file)
805  *
806  * Note that we assume that the file should be "binary"
807  */
808 int fd_open(concptr file, int flags)
809 {
810         char buf[1024];
811
812         /* Hack -- Try to parse the path */
813         if (path_parse(buf, 1024, file)) return (-1);
814
815         /* Attempt to open the file */
816         return (open(buf, flags | O_BINARY, 0));
817 }
818
819
820 /*
821  * Hack -- attempt to lock a file descriptor
822  *
823  * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
824  */
825 errr fd_lock(int fd, int what)
826 {
827         /* XXX XXX */
828         what = what ? what : 0;
829
830         /* Verify the fd */
831         if (fd < 0) return (-1);
832
833 #ifdef SET_UID
834
835 # ifdef USG
836
837 #  if defined(F_ULOCK) && defined(F_LOCK)
838
839         /* Un-Lock */
840         if (what == F_UNLCK)
841         {
842                 /* Unlock it, Ignore errors */
843                 lockf(fd, F_ULOCK, 0);
844         }
845
846         /* Lock */
847         else
848         {
849                 /* Lock the score file */
850                 if (lockf(fd, F_LOCK, 0) != 0) return (1);
851         }
852
853 #  endif
854
855 # else
856
857 #  if defined(LOCK_UN) && defined(LOCK_EX)
858
859         /* Un-Lock */
860         if (what == F_UNLCK)
861         {
862                 /* Unlock it, Ignore errors */
863                 (void)flock(fd, LOCK_UN);
864         }
865
866         /* Lock */
867         else
868         {
869                 /* Lock the score file */
870                 if (flock(fd, LOCK_EX) != 0) return (1);
871         }
872
873 #  endif
874
875 # endif
876
877 #endif
878
879         /* Success */
880         return (0);
881 }
882
883
884 /*
885  * Hack -- attempt to seek on a file descriptor
886  */
887 errr fd_seek(int fd, huge n)
888 {
889         huge p;
890
891         /* Verify fd */
892         if (fd < 0) return (-1);
893
894         /* Seek to the given position */
895         p = lseek(fd, n, SEEK_SET);
896
897         /* Failure */
898         if (p != n) return (1);
899
900         /* Success */
901         return (0);
902 }
903
904
905 /*
906  * Hack -- attempt to truncate a file descriptor
907  */
908 errr fd_chop(int fd, huge n)
909 {
910         /* XXX XXX */
911         n = n ? n : 0;
912
913         /* Verify the fd */
914         if (fd < 0) return (-1);
915
916 #if defined(ULTRIX) || defined(NeXT)
917         /* Truncate */
918         ftruncate(fd, n);
919 #endif
920
921         /* Success */
922         return (0);
923 }
924
925
926 /*
927  * Hack -- attempt to read data from a file descriptor
928  */
929 errr fd_read(int fd, char *buf, huge n)
930 {
931         /* Verify the fd */
932         if (fd < 0) return (-1);
933
934 #ifndef SET_UID
935
936         /* Read pieces */
937         while (n >= 16384)
938         {
939                 /* Read a piece */
940                 if (read(fd, buf, 16384) != 16384) return (1);
941
942                 /* Shorten the task */
943                 buf += 16384;
944
945                 /* Shorten the task */
946                 n -= 16384;
947         }
948
949 #endif
950
951         /* Read the final piece */
952         if (read(fd, buf, n) != (int)n) return (1);
953
954         /* Success */
955         return (0);
956 }
957
958
959 /*
960  * Hack -- Attempt to write data to a file descriptor
961  */
962 errr fd_write(int fd, concptr buf, huge n)
963 {
964         /* Verify the fd */
965         if (fd < 0) return (-1);
966
967 #ifndef SET_UID
968
969         /* Write pieces */
970         while (n >= 16384)
971         {
972                 /* Write a piece */
973                 if (write(fd, buf, 16384) != 16384) return (1);
974
975                 /* Shorten the task */
976                 buf += 16384;
977
978                 /* Shorten the task */
979                 n -= 16384;
980         }
981
982 #endif
983
984         /* Write the final piece */
985         if (write(fd, buf, n) != (int)n) return (1);
986
987         /* Success */
988         return (0);
989 }
990
991
992 /*
993  * Hack -- attempt to close a file descriptor
994  */
995 errr fd_close(int fd)
996 {
997         /* Verify the fd */
998         if (fd < 0) return (-1);
999
1000         /* Close */
1001         (void)close(fd);
1002
1003         return (0);
1004 }
1005
1006
1007 #endif /* ACORN */
1008
1009
1010
1011
1012 /*
1013  * Important note about "colors" 
1014  *
1015  * The "TERM_*" color definitions list the "composition" of each
1016  * "Angband color" in terms of "quarters" of each of the three color
1017  * components (Red, Green, Blue), for example, TERM_UMBER is defined
1018  * as 2/4 Red, 1/4 Green, 0/4 Blue.
1019  *
1020  * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
1021  *
1022  * These values are NOT gamma-corrected.  On most machines (with the
1023  * Macintosh being an important exception), you must "gamma-correct"
1024  * the given values, that is, "correct for the intrinsic non-linearity
1025  * of the phosphor", by converting the given intensity levels based
1026  * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
1027  *
1028  * The actual formula for conversion is unknown to me at this time,
1029  * but you can use the table below for the most common gamma values.
1030  *
1031  * So, on most machines, simply convert the values based on the "gamma"
1032  * of the target screen, which is usually in the range 1.5 to 1.7, and
1033  * usually is closest to 1.7.  The converted value for each of the five
1034  * different "quarter" values is given below:
1035  *
1036  *  Given     Gamma 1.0       Gamma 1.5       Gamma 1.7     Hex 1.7
1037  *  -----       ----            ----            ----          ---
1038  *   0/4        0.00            0.00            0.00          #00
1039  *   1/4        0.25            0.27            0.28          #47
1040  *   2/4        0.50            0.55            0.56          #8f
1041  *   3/4        0.75            0.82            0.84          #d7
1042  *   4/4        1.00            1.00            1.00          #ff
1043  *
1044  * Note that some machines (i.e. most IBM machines) are limited to a
1045  * hard-coded set of colors, and so the information above is useless.
1046  *
1047  * Also, some machines are limited to a pre-determined set of colors,
1048  * for example, the IBM can only display 16 colors, and only 14 of
1049  * those colors resemble colors used by Angband, and then only when
1050  * you ignore the fact that "Slate" and "cyan" are not really matches,
1051  * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
1052  * in addition to the obvious "Orange", since by combining all of the
1053  * "indeterminate" colors into a single color, the rest of the colors
1054  * are left with "meaningful" values.
1055  */
1056
1057
1058 /*
1059  * Move the cursor
1060  */
1061 void move_cursor(int row, int col)
1062 {
1063         Term_gotoxy(col, row);
1064 }
1065
1066
1067
1068 /*
1069  * Convert a decimal to a single digit octal number
1070  */
1071 static char octify(uint i)
1072 {
1073         return (hexsym[i%8]);
1074 }
1075
1076 /*
1077  * Convert a decimal to a single digit hex number
1078  */
1079 static char hexify(uint i)
1080 {
1081         return (hexsym[i%16]);
1082 }
1083
1084
1085 /*
1086  * Convert a octal-digit into a decimal
1087  */
1088 static int deoct(char c)
1089 {
1090         if (isdigit(c)) return (D2I(c));
1091         return (0);
1092 }
1093
1094 /*
1095  * Convert a hexidecimal-digit into a decimal
1096  */
1097 static int dehex(char c)
1098 {
1099         if (isdigit(c)) return (D2I(c));
1100         if (islower(c)) return (A2I(c) + 10);
1101         if (isupper(c)) return (A2I(tolower(c)) + 10);
1102         return (0);
1103 }
1104
1105
1106 static int my_stricmp(concptr a, concptr b)
1107 {
1108         concptr s1, s2;
1109         char z1, z2;
1110
1111         /* Scan the strings */
1112         for (s1 = a, s2 = b; TRUE; s1++, s2++)
1113         {
1114                 z1 = FORCEUPPER(*s1);
1115                 z2 = FORCEUPPER(*s2);
1116                 if (z1 < z2) return (-1);
1117                 if (z1 > z2) return (1);
1118                 if (!z1) return (0);
1119         }
1120 }
1121
1122 static int my_strnicmp(concptr a, concptr b, int n)
1123 {
1124         concptr s1, s2;
1125         char z1, z2;
1126
1127         /* Scan the strings */
1128         for (s1 = a, s2 = b; n > 0; s1++, s2++, n--)
1129         {
1130                 z1 = FORCEUPPER(*s1);
1131                 z2 = FORCEUPPER(*s2);
1132                 if (z1 < z2) return (-1);
1133                 if (z1 > z2) return (1);
1134                 if (!z1) return (0);
1135         }
1136         return 0;
1137 }
1138
1139
1140 static void trigger_text_to_ascii(char **bufptr, concptr *strptr)
1141 {
1142         char *s = *bufptr;
1143         concptr str = *strptr;
1144         bool mod_status[MAX_MACRO_MOD];
1145
1146         int i, len = 0;
1147         int shiftstatus = 0;
1148         concptr key_code;
1149
1150         if (macro_template == NULL)
1151                 return;
1152         
1153         for (i = 0; macro_modifier_chr[i]; i++)
1154                 mod_status[i] = FALSE;
1155         str++;
1156
1157         /* Examine modifier keys */
1158         while (1)
1159         {
1160                 for (i=0; macro_modifier_chr[i]; i++)
1161                 {
1162                         len = strlen(macro_modifier_name[i]);
1163                         
1164                         if(!my_strnicmp(str, macro_modifier_name[i], len))
1165                                 break;
1166                 }
1167                 if (!macro_modifier_chr[i]) break;
1168                 str += len;
1169                 mod_status[i] = TRUE;
1170                 if ('S' == macro_modifier_chr[i])
1171                         shiftstatus = 1;
1172         }
1173         for (i = 0; i < max_macrotrigger; i++)
1174         {
1175                 len = strlen(macro_trigger_name[i]);
1176                 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
1177                 {
1178                         /* a trigger name found */
1179                         break;
1180                 }
1181         }
1182
1183         /* Invalid trigger name? */
1184         if (i == max_macrotrigger)
1185         {
1186                 str = my_strchr(str, ']');
1187                 if (str)
1188                 {
1189                         *s++ = (char)31;
1190                         *s++ = '\r';
1191                         *bufptr = s;
1192                         *strptr = str; /* where **strptr == ']' */
1193                 }
1194                 return;
1195         }
1196         key_code = macro_trigger_keycode[shiftstatus][i];
1197         str += len;
1198
1199         *s++ = (char)31;
1200         for (i = 0; macro_template[i]; i++)
1201         {
1202                 char ch = macro_template[i];
1203                 int j;
1204
1205                 switch(ch)
1206                 {
1207                 case '&':
1208                         for (j = 0; macro_modifier_chr[j]; j++) {
1209                                 if (mod_status[j])
1210                                         *s++ = macro_modifier_chr[j];
1211                         }
1212                         break;
1213                 case '#':
1214                         strcpy(s, key_code);
1215                         s += strlen(key_code);
1216                         break;
1217                 default:
1218                         *s++ = ch;
1219                         break;
1220                 }
1221         }
1222         *s++ = '\r';
1223
1224         *bufptr = s;
1225         *strptr = str; /* where **strptr == ']' */
1226         return;
1227 }
1228
1229
1230 /*
1231  * Hack -- convert a printable string into real ascii
1232  *
1233  * I have no clue if this function correctly handles, for example,
1234  * parsing "\xFF" into a (signed) char.  Whoever thought of making
1235  * the "sign" of a "char" undefined is a complete moron.  Oh well.
1236  */
1237 void text_to_ascii(char *buf, concptr str)
1238 {
1239         char *s = buf;
1240
1241         /* Analyze the "ascii" string */
1242         while (*str)
1243         {
1244                 /* Backslash codes */
1245                 if (*str == '\\')
1246                 {
1247                         /* Skip the backslash */
1248                         str++;
1249                         if (!(*str)) break;
1250
1251                         /* Macro Trigger */
1252                         if (*str == '[')
1253                         {
1254                                 trigger_text_to_ascii(&s, &str);
1255                         }
1256                         else
1257
1258                         /* Hex-mode XXX */
1259                         if (*str == 'x')
1260                         {
1261                                 *s = 16 * (char)dehex(*++str);
1262                                 *s++ += (char)dehex(*++str);
1263                         }
1264
1265                         /* Hack -- simple way to specify "backslash" */
1266                         else if (*str == '\\')
1267                         {
1268                                 *s++ = '\\';
1269                         }
1270
1271                         /* Hack -- simple way to specify "caret" */
1272                         else if (*str == '^')
1273                         {
1274                                 *s++ = '^';
1275                         }
1276
1277                         /* Hack -- simple way to specify "space" */
1278                         else if (*str == 's')
1279                         {
1280                                 *s++ = ' ';
1281                         }
1282
1283                         /* Hack -- simple way to specify Escape */
1284                         else if (*str == 'e')
1285                         {
1286                                 *s++ = ESCAPE;
1287                         }
1288
1289                         /* Backspace */
1290                         else if (*str == 'b')
1291                         {
1292                                 *s++ = '\b';
1293                         }
1294
1295                         /* Newline */
1296                         else if (*str == 'n')
1297                         {
1298                                 *s++ = '\n';
1299                         }
1300
1301                         /* Return */
1302                         else if (*str == 'r')
1303                         {
1304                                 *s++ = '\r';
1305                         }
1306
1307                         /* Tab */
1308                         else if (*str == 't')
1309                         {
1310                                 *s++ = '\t';
1311                         }
1312
1313                         /* Octal-mode */
1314                         else if (*str == '0')
1315                         {
1316                                 *s = 8 * (char)deoct(*++str);
1317                                 *s++ += (char)deoct(*++str);
1318                         }
1319
1320                         /* Octal-mode */
1321                         else if (*str == '1')
1322                         {
1323                                 *s = 64 + 8 * (char)deoct(*++str);
1324                                 *s++ += (char)deoct(*++str);
1325                         }
1326
1327                         /* Octal-mode */
1328                         else if (*str == '2')
1329                         {
1330                                 *s = 64 * 2 + 8 * (char)deoct(*++str);
1331                                 *s++ += (char)deoct(*++str);
1332                         }
1333
1334                         /* Octal-mode */
1335                         else if (*str == '3')
1336                         {
1337                                 *s = 64 * 3 + 8 * (char)deoct(*++str);
1338                                 *s++ += (char)deoct(*++str);
1339                         }
1340
1341                         /* Skip the final char */
1342                         str++;
1343                 }
1344
1345                 /* Normal Control codes */
1346                 else if (*str == '^')
1347                 {
1348                         str++;
1349                         *s++ = (*str++ & 037);
1350                 }
1351
1352                 /* Normal chars */
1353                 else
1354                 {
1355                         *s++ = *str++;
1356                 }
1357         }
1358
1359         /* Terminate */
1360         *s = '\0';
1361 }
1362
1363
1364 static bool trigger_ascii_to_text(char **bufptr, concptr *strptr)
1365 {
1366         char *s = *bufptr;
1367         concptr str = *strptr;
1368         char key_code[100];
1369         int i;
1370         concptr tmp;
1371
1372         if (macro_template == NULL)
1373                 return FALSE;
1374
1375         *s++ = '\\';
1376         *s++ = '[';
1377
1378         for (i = 0; macro_template[i]; i++)
1379         {
1380                 int j;
1381                 char ch = macro_template[i];
1382
1383                 switch(ch)
1384                 {
1385                 case '&':
1386                         while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1387                         {
1388                                 j = (int)(tmp - macro_modifier_chr);
1389                                 tmp = macro_modifier_name[j];
1390                                 while(*tmp) *s++ = *tmp++;
1391                                 str++;
1392                         }
1393                         break;
1394                 case '#':
1395                         for (j = 0; *str && *str != '\r'; j++)
1396                                 key_code[j] = *str++;
1397                         key_code[j] = '\0';
1398                         break;
1399                 default:
1400                         if (ch != *str) return FALSE;
1401                         str++;
1402                 }
1403         }
1404         if (*str++ != '\r') return FALSE;
1405
1406         for (i = 0; i < max_macrotrigger; i++)
1407         {
1408                 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1409                     || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1410                         break;
1411         }
1412         if (i == max_macrotrigger)
1413                 return FALSE;
1414
1415         tmp = macro_trigger_name[i];
1416         while (*tmp) *s++ = *tmp++;
1417
1418         *s++ = ']';
1419         
1420         *bufptr = s;
1421         *strptr = str;
1422         return TRUE;
1423 }
1424
1425
1426 /*
1427  * Hack -- convert a string into a printable form
1428  */
1429 void ascii_to_text(char *buf, concptr str)
1430 {
1431         char *s = buf;
1432
1433         /* Analyze the "ascii" string */
1434         while (*str)
1435         {
1436                 byte i = (byte)(*str++);
1437
1438                 /* Macro Trigger */
1439                 if (i == 31)
1440                 {
1441                         if(!trigger_ascii_to_text(&s, &str))
1442                         {
1443                                 *s++ = '^';
1444                                 *s++ = '_';
1445                         }
1446                 }
1447                 else
1448
1449                 if (i == ESCAPE)
1450                 {
1451                         *s++ = '\\';
1452                         *s++ = 'e';
1453                 }
1454                 else if (i == ' ')
1455                 {
1456                         *s++ = '\\';
1457                         *s++ = 's';
1458                 }
1459                 else if (i == '\b')
1460                 {
1461                         *s++ = '\\';
1462                         *s++ = 'b';
1463                 }
1464                 else if (i == '\t')
1465                 {
1466                         *s++ = '\\';
1467                         *s++ = 't';
1468                 }
1469                 else if (i == '\n')
1470                 {
1471                         *s++ = '\\';
1472                         *s++ = 'n';
1473                 }
1474                 else if (i == '\r')
1475                 {
1476                         *s++ = '\\';
1477                         *s++ = 'r';
1478                 }
1479                 else if (i == '^')
1480                 {
1481                         *s++ = '\\';
1482                         *s++ = '^';
1483                 }
1484                 else if (i == '\\')
1485                 {
1486                         *s++ = '\\';
1487                         *s++ = '\\';
1488                 }
1489                 else if (i < 32)
1490                 {
1491                         *s++ = '^';
1492                         *s++ = i + 64;
1493                 }
1494                 else if (i < 127)
1495                 {
1496                         *s++ = i;
1497                 }
1498                 else if (i < 64)
1499                 {
1500                         *s++ = '\\';
1501                         *s++ = '0';
1502                         *s++ = octify(i / 8);
1503                         *s++ = octify(i % 8);
1504                 }
1505                 else
1506                 {
1507                         *s++ = '\\';
1508                         *s++ = 'x';
1509                         *s++ = hexify(i / 16);
1510                         *s++ = hexify(i % 16);
1511                 }
1512         }
1513
1514         /* Terminate */
1515         *s = '\0';
1516 }
1517
1518
1519
1520 /*
1521  * The "macro" package
1522  *
1523  * Functions are provided to manipulate a collection of macros, each
1524  * of which has a trigger pattern string and a resulting action string
1525  * and a small set of flags.
1526  */
1527
1528
1529
1530 /*
1531  * Determine if any macros have ever started with a given character.
1532  */
1533 static bool macro__use[256];
1534
1535
1536 /*
1537  * Find the macro (if any) which exactly matches the given pattern
1538  */
1539 sint macro_find_exact(concptr pat)
1540 {
1541         int i;
1542
1543         /* Nothing possible */
1544         if (!macro__use[(byte)(pat[0])])
1545         {
1546                 return (-1);
1547         }
1548
1549         /* Scan the macros */
1550         for (i = 0; i < macro__num; ++i)
1551         {
1552                 /* Skip macros which do not match the pattern */
1553                 if (!streq(macro__pat[i], pat)) continue;
1554
1555                 /* Found one */
1556                 return (i);
1557         }
1558
1559         /* No matches */
1560         return (-1);
1561 }
1562
1563
1564 /*
1565  * Find the first macro (if any) which contains the given pattern
1566  */
1567 static sint macro_find_check(concptr pat)
1568 {
1569         int i;
1570
1571         /* Nothing possible */
1572         if (!macro__use[(byte)(pat[0])])
1573         {
1574                 return (-1);
1575         }
1576
1577         /* Scan the macros */
1578         for (i = 0; i < macro__num; ++i)
1579         {
1580                 /* Skip macros which do not contain the pattern */
1581                 if (!prefix(macro__pat[i], pat)) continue;
1582
1583                 /* Found one */
1584                 return (i);
1585         }
1586
1587         /* Nothing */
1588         return (-1);
1589 }
1590
1591
1592 /*
1593  * Find the first macro (if any) which contains the given pattern and more
1594  */
1595 static sint macro_find_maybe(concptr pat)
1596 {
1597         int i;
1598
1599         /* Nothing possible */
1600         if (!macro__use[(byte)(pat[0])])
1601         {
1602                 return (-1);
1603         }
1604
1605         /* Scan the macros */
1606         for (i = 0; i < macro__num; ++i)
1607         {
1608                 /* Skip macros which do not contain the pattern */
1609                 if (!prefix(macro__pat[i], pat)) continue;
1610
1611                 /* Skip macros which exactly match the pattern XXX XXX */
1612                 if (streq(macro__pat[i], pat)) continue;
1613
1614                 /* Found one */
1615                 return (i);
1616         }
1617
1618         /* Nothing */
1619         return (-1);
1620 }
1621
1622
1623 /*
1624  * Find the longest macro (if any) which starts with the given pattern
1625  */
1626 static sint macro_find_ready(concptr pat)
1627 {
1628         int i, t, n = -1, s = -1;
1629
1630         /* Nothing possible */
1631         if (!macro__use[(byte)(pat[0])])
1632         {
1633                 return (-1);
1634         }
1635
1636         /* Scan the macros */
1637         for (i = 0; i < macro__num; ++i)
1638         {
1639                 /* Skip macros which are not contained by the pattern */
1640                 if (!prefix(pat, macro__pat[i])) continue;
1641
1642                 /* Obtain the length of this macro */
1643                 t = strlen(macro__pat[i]);
1644
1645                 /* Only track the "longest" pattern */
1646                 if ((n >= 0) && (s > t)) continue;
1647
1648                 /* Track the entry */
1649                 n = i;
1650                 s = t;
1651         }
1652         return (n);
1653 }
1654
1655
1656 /*
1657  * Add a macro definition (or redefinition).
1658  *
1659  * We should use "act == NULL" to "remove" a macro, but this might make it
1660  * impossible to save the "removal" of a macro definition.  
1661  *
1662  * We should consider refusing to allow macros which contain existing macros,
1663  * or which are contained in existing macros, because this would simplify the
1664  * macro analysis code.  
1665  *
1666  * We should consider removing the "command macro" crap, and replacing it
1667  * with some kind of "powerful keymap" ability, but this might make it hard
1668  * to change the "roguelike" option from inside the game.  
1669  */
1670 errr macro_add(concptr pat, concptr act)
1671 {
1672         int n;
1673
1674
1675         /* Paranoia -- require data */
1676         if (!pat || !act) return (-1);
1677
1678
1679         /* Look for any existing macro */
1680         n = macro_find_exact(pat);
1681
1682         /* Replace existing macro */
1683         if (n >= 0)
1684         {
1685                 /* Free the old macro action */
1686                 string_free(macro__act[n]);
1687         }
1688
1689         /* Create a new macro */
1690         else
1691         {
1692                 /* Acquire a new index */
1693                 n = macro__num++;
1694
1695                 /* Save the pattern */
1696                 macro__pat[n] = string_make(pat);
1697         }
1698
1699         /* Save the action */
1700         macro__act[n] = string_make(act);
1701
1702         /* Efficiency */
1703         macro__use[(byte)(pat[0])] = TRUE;
1704
1705         /* Success */
1706         return (0);
1707 }
1708
1709
1710
1711 /*
1712  * Local variable -- we are inside a "macro action"
1713  *
1714  * Do not match any macros until "ascii 30" is found.
1715  */
1716 static bool parse_macro = FALSE;
1717
1718 /*
1719  * Local variable -- we are inside a "macro trigger"
1720  *
1721  * Strip all keypresses until a low ascii value is found.
1722  */
1723 static bool parse_under = FALSE;
1724
1725
1726 /*
1727  * Flush all input chars.  Actually, remember the flush,
1728  * and do a "special flush" before the next "inkey()".
1729  *
1730  * This is not only more efficient, but also necessary to make sure
1731  * that various "inkey()" codes are not "lost" along the way.
1732  */
1733 void flush(void)
1734 {
1735         /* Do it later */
1736         inkey_xtra = TRUE;
1737 }
1738
1739
1740 /*
1741  * Flush the screen, make a noise
1742  */
1743 void bell(void)
1744 {
1745         /* Mega-Hack -- Flush the output */
1746         Term_fresh();
1747
1748         /* Make a bell noise (if allowed) */
1749         if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1750
1751         /* Flush the input (later!) */
1752         flush();
1753 }
1754
1755
1756 /*
1757  * Hack -- Make a (relevant?) sound
1758  */
1759 void sound(int val)
1760 {
1761         /* No sound */
1762         if (!use_sound) return;
1763
1764         /* Make a sound (if allowed) */
1765         Term_xtra(TERM_XTRA_SOUND, val);
1766 }
1767
1768 /*
1769  * Hack -- Play a music
1770  */
1771 errr play_music(int type, int val)
1772 {
1773         /* No sound */
1774         if (!use_music) return 1;
1775
1776         /* Make a sound (if allowed) */
1777         return Term_xtra(type, val);
1778 }
1779
1780 /*
1781  * Hack -- Select floor music.
1782  */
1783 void select_floor_music(void)
1784 {
1785         int i;
1786         /* No sound */
1787         if (!use_music) return;
1788
1789         if(p_ptr->ambush_flag)
1790         {
1791                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH);
1792                 return;
1793         }
1794
1795         if(p_ptr->wild_mode)
1796         {
1797                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD);
1798                 return;
1799         }
1800
1801         if(p_ptr->inside_arena)
1802         {
1803                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA);
1804                 return;
1805         }
1806
1807         if(p_ptr->inside_battle)
1808         {
1809                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE);
1810                 return;
1811         }
1812
1813         if(p_ptr->inside_quest)
1814         {
1815                 if(play_music(TERM_XTRA_MUSIC_QUEST, p_ptr->inside_quest))
1816                 {
1817                         play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1818                 }
1819                 return;
1820         }
1821
1822         for(i = 0; i < max_q_idx; i++)
1823         { // TODO マクロで類似条件を統合すること
1824                 if(quest[i].status == QUEST_STATUS_TAKEN &&
1825                         (quest[i].type == QUEST_TYPE_KILL_LEVEL || quest[i].type == QUEST_TYPE_RANDOM) &&
1826                          quest[i].level == current_floor_ptr->dun_level && p_ptr->dungeon_idx == quest[i].dungeon)
1827                 {
1828                         if(play_music(TERM_XTRA_MUSIC_QUEST, i)) 
1829                         {
1830                                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1831                         }
1832                         return;
1833                 }
1834         }
1835
1836         if(p_ptr->dungeon_idx)
1837         {
1838                 if(p_ptr->feeling == 2) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2);
1839                 else if(p_ptr->feeling >= 3 && p_ptr->feeling <= 5) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1);
1840                 else
1841                 {
1842                         if(play_music(TERM_XTRA_MUSIC_DUNGEON, p_ptr->dungeon_idx))
1843                         {
1844                                 if(current_floor_ptr->dun_level < 40) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW);
1845                                 else if(current_floor_ptr->dun_level < 80) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED);
1846                                 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH);
1847                         }
1848                 }
1849                 return;
1850         }
1851
1852         if(p_ptr->town_num)
1853         {
1854                 if(play_music(TERM_XTRA_MUSIC_TOWN, p_ptr->town_num))
1855                 {
1856                         play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN);
1857                 }
1858                 return;
1859         }
1860
1861         if(!current_floor_ptr->dun_level)
1862         {
1863                 if(p_ptr->lev >= 45) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3);
1864                 else if(p_ptr->lev >= 25) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2);
1865                 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1);
1866                 return;
1867         }
1868         
1869 }
1870
1871
1872
1873 /*
1874  * Helper function called only from "inkey()"
1875  *
1876  * This function does almost all of the "macro" processing.
1877  *
1878  * We use the "Term_key_push()" function to handle "failed" macros, as well
1879  * as "extra" keys read in while choosing the proper macro, and also to hold
1880  * the action for the macro, plus a special "ascii 30" character indicating
1881  * that any macro action in progress is complete.  Embedded macros are thus
1882  * illegal, unless a macro action includes an explicit "ascii 30" character,
1883  * which would probably be a massive hack, and might break things.
1884  *
1885  * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1886  * the macro trigger sequence.  If a key sequence forms the "prefix" of a
1887  * macro trigger, 500 milliseconds must pass before the key sequence is
1888  * known not to be that macro trigger.  
1889  */
1890 static char inkey_aux(void)
1891 {
1892         int k = 0, n, p = 0, w = 0;
1893
1894         char ch;
1895
1896         concptr pat, act;
1897
1898         char *buf = inkey_macro_trigger_string;
1899
1900         /* Hack : キー入力待ちで止まっているので、流れた行の記憶は不要。 */
1901         num_more = 0;
1902
1903         if (parse_macro)
1904         {
1905                 /* Scan next keypress from macro action */
1906                 if (Term_inkey(&ch, FALSE, TRUE))
1907                 {
1908                         /* Over-flowed? Cancel macro action */
1909                         parse_macro = FALSE;
1910                 }
1911         }
1912         else
1913         {
1914                 /* Wait for a keypress */
1915                 (void) (Term_inkey(&ch, TRUE, TRUE));
1916         }
1917
1918
1919         /* End "macro action" */
1920         if (ch == 30) parse_macro = FALSE;
1921
1922         /* Inside "macro action" */
1923         if (ch == 30) return (ch);
1924
1925         /* Inside "macro action" */
1926         if (parse_macro) return (ch);
1927
1928         /* Inside "macro trigger" */
1929         if (parse_under) return (ch);
1930
1931         /* Save the first key, advance */
1932         buf[p++] = ch;
1933         buf[p] = '\0';
1934
1935
1936         /* Check for possible macro */
1937         k = macro_find_check(buf);
1938
1939         /* No macro pending */
1940         if (k < 0) return (ch);
1941
1942
1943         /* Wait for a macro, or a timeout */
1944         while (TRUE)
1945         {
1946                 /* Check for pending macro */
1947                 k = macro_find_maybe(buf);
1948
1949                 /* No macro pending */
1950                 if (k < 0) break;
1951
1952                 /* Check for (and remove) a pending key */
1953                 if (0 == Term_inkey(&ch, FALSE, TRUE))
1954                 {
1955                         /* Append the key */
1956                         buf[p++] = ch;
1957                         buf[p] = '\0';
1958
1959                         /* Restart wait */
1960                         w = 0;
1961                 }
1962
1963                 /* No key ready */
1964                 else
1965                 {
1966                         /* Increase "wait" */
1967                         w += 1;
1968
1969                         /* Excessive delay */
1970                         if (w >= 10) break;
1971
1972                         Term_xtra(TERM_XTRA_DELAY, w);
1973                 }
1974         }
1975
1976
1977         /* Check for available macro */
1978         k = macro_find_ready(buf);
1979
1980         /* No macro available */
1981         if (k < 0)
1982         {
1983                 /* Push all the keys back on the queue */
1984                 while (p > 0)
1985                 {
1986                         /* Push the key, notice over-flow */
1987                         if (Term_key_push(buf[--p])) return (0);
1988                 }
1989
1990                 /* Wait for (and remove) a pending key */
1991                 (void)Term_inkey(&ch, TRUE, TRUE);
1992
1993                 /* Return the key */
1994                 return (ch);
1995         }
1996
1997
1998         /* Get the pattern */
1999         pat = macro__pat[k];
2000
2001         /* Get the length of the pattern */
2002         n = strlen(pat);
2003
2004         /* Push the "extra" keys back on the queue */
2005         while (p > n)
2006         {
2007                 /* Push the key, notice over-flow */
2008                 if (Term_key_push(buf[--p])) return (0);
2009         }
2010
2011
2012         /* Begin "macro action" */
2013         parse_macro = TRUE;
2014
2015         /* Push the "end of macro action" key */
2016         if (Term_key_push(30)) return (0);
2017
2018
2019         /* Access the macro action */
2020         act = macro__act[k];
2021
2022         /* Get the length of the action */
2023         n = strlen(act);
2024
2025         /* Push the macro "action" onto the key queue */
2026         while (n > 0)
2027         {
2028                 /* Push the key, notice over-flow */
2029                 if (Term_key_push(act[--n])) return (0);
2030         }
2031
2032
2033         /* Hack -- Force "inkey()" to call us again */
2034         return (0);
2035 }
2036
2037
2038 /*
2039  * Cancel macro action on the queue
2040  */
2041 static void forget_macro_action(void)
2042 {
2043         if (!parse_macro) return;
2044
2045         /* Drop following macro action string */
2046         while (TRUE)
2047         {
2048                 char ch;
2049
2050                 /* End loop if no key ready */
2051                 if (Term_inkey(&ch, FALSE, TRUE)) break;
2052
2053                 /* End loop if no key ready */
2054                 if (ch == 0) break;
2055
2056                 /* End of "macro action" */
2057                 if (ch == 30) break;
2058         }
2059
2060         /* No longer inside "macro action" */
2061         parse_macro = FALSE;
2062 }
2063
2064
2065 /*
2066  * Mega-Hack -- special "inkey_next" pointer.  
2067  *
2068  * This special pointer allows a sequence of keys to be "inserted" into
2069  * the stream of keys returned by "inkey()".  This key sequence will not
2070  * trigger any macros, and cannot be bypassed by the Borg.  It is used
2071  * in Angband to handle "keymaps".
2072  */
2073 static concptr inkey_next = NULL;
2074
2075
2076 #ifdef ALLOW_BORG
2077
2078 /*
2079  * Mega-Hack -- special "inkey_hack" hook.  
2080  *
2081  * This special function hook allows the "Borg" (see elsewhere) to take
2082  * control of the "inkey()" function, and substitute in fake keypresses.
2083  */
2084 char (*inkey_hack)(int flush_first) = NULL;
2085
2086 #endif /* ALLOW_BORG */
2087
2088
2089
2090 /*
2091  * Get a keypress from the user.
2092  *
2093  * This function recognizes a few "global parameters".  These are variables
2094  * which, if set to TRUE before calling this function, will have an effect
2095  * on this function, and which are always reset to FALSE by this function
2096  * before this function returns.  Thus they function just like normal
2097  * parameters, except that most calls to this function can ignore them.
2098  *
2099  * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
2100  * and any macro processing in progress will be aborted.  This flag is
2101  * set by the "flush()" function, which does not actually flush anything
2102  * itself, but rather, triggers delayed input flushing via "inkey_xtra".
2103  *
2104  * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
2105  * keypress is available, instead of waiting for a keypress.
2106  *
2107  * If "inkey_base" is TRUE, then all macro processing will be bypassed.
2108  * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
2109  * not return immediately, but will wait for a keypress for as long as the
2110  * normal macro matching code would, allowing the direct entry of macro
2111  * triggers.  The "inkey_base" flag is extremely dangerous!
2112  *
2113  * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
2114  * normal command, and we will only show the cursor if "hilite_player" is
2115  * TRUE (or if the player is in a store), instead of always showing the
2116  * cursor.  The various "main-xxx.c" files should avoid saving the game
2117  * in response to a "menu item" request unless "inkey_flag" is TRUE, to
2118  * prevent savefile corruption.
2119  *
2120  * If we are waiting for a keypress, and no keypress is ready, then we will
2121  * refresh (once) the window which was active when this function was called.
2122  *
2123  * Note that "back-quote" is automatically converted into "escape" for
2124  * convenience on machines with no "escape" key.  This is done after the
2125  * macro matching, so the user can still make a macro for "backquote".
2126  *
2127  * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
2128  * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
2129  * provide support for simple keyboard "macros".  These keys are so strange
2130  * that their loss as normal keys will probably be noticed by nobody.  The
2131  * "ascii 30" key is used to indicate the "end" of a macro action, which
2132  * allows recursive macros to be avoided.  The "ascii 31" key is used by
2133  * some of the "main-xxx.c" files to introduce macro trigger sequences.
2134  *
2135  * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
2136  * which can be used to give a variety of "sub-commands" which can be used
2137  * any time.  These sub-commands could include commands to take a picture of
2138  * the current screen, to start/stop recording a macro action, etc.
2139  *
2140  * If "angband_term[0]" is not active, we will make it active during this
2141  * function, so that the various "main-xxx.c" files can assume that input
2142  * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
2143  *
2144  * Mega-Hack -- This function is used as the entry point for clearing the
2145  * "signal_count" variable, and of the "current_world_ptr->character_saved" variable.
2146  *
2147  * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
2148  *
2149  * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
2150  * control of the keyboard from the user.
2151  */
2152 char inkey(void)
2153 {
2154         int v;
2155         char kk;
2156         char ch = 0;
2157         bool done = FALSE;
2158         term *old = Term;
2159
2160         /* Hack -- Use the "inkey_next" pointer */
2161         if (inkey_next && *inkey_next && !inkey_xtra)
2162         {
2163                 /* Get next character, and advance */
2164                 ch = *inkey_next++;
2165
2166                 /* Cancel the various "global parameters" */
2167                 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2168
2169                 /* Accept result */
2170                 return (ch);
2171         }
2172
2173         /* Forget pointer */
2174         inkey_next = NULL;
2175
2176
2177 #ifdef ALLOW_BORG
2178
2179         /* Mega-Hack -- Use the special hook */
2180         if (inkey_hack && ((ch = (*inkey_hack)(inkey_xtra)) != 0))
2181         {
2182                 /* Cancel the various "global parameters" */
2183                 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2184
2185                 /* Accept result */
2186                 return (ch);
2187         }
2188
2189 #endif /* ALLOW_BORG */
2190
2191
2192         /* Hack -- handle delayed "flush()" */
2193         if (inkey_xtra)
2194         {
2195                 /* End "macro action" */
2196                 parse_macro = FALSE;
2197
2198                 /* End "macro trigger" */
2199                 parse_under = FALSE;
2200
2201                 /* Forget old keypresses */
2202                 Term_flush();
2203         }
2204
2205
2206         /* Access cursor state */
2207         (void)Term_get_cursor(&v);
2208
2209         /* Show the cursor if waiting, except sometimes in "command" mode */
2210         if (!inkey_scan && (!inkey_flag || hilite_player || current_world_ptr->character_icky))
2211         {
2212                 /* Show the cursor */
2213                 (void)Term_set_cursor(1);
2214         }
2215
2216
2217         /* Hack -- Activate main screen */
2218         Term_activate(angband_term[0]);
2219
2220
2221         /* Get a key */
2222         while (!ch)
2223         {
2224                 /* Hack -- Handle "inkey_scan" */
2225                 if (!inkey_base && inkey_scan &&
2226                         (0 != Term_inkey(&kk, FALSE, FALSE)))
2227                 {
2228                         break;
2229                 }
2230
2231
2232                 /* Hack -- Flush output once when no key ready */
2233                 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
2234                 {
2235                         /* Hack -- activate proper term */
2236                         Term_activate(old);
2237
2238                         /* Flush output */
2239                         Term_fresh();
2240
2241                         /* Hack -- activate main screen */
2242                         Term_activate(angband_term[0]);
2243
2244                         /* Mega-Hack -- reset saved flag */
2245                         current_world_ptr->character_saved = FALSE;
2246
2247                         /* Mega-Hack -- reset signal counter */
2248                         signal_count = 0;
2249
2250                         /* Only once */
2251                         done = TRUE;
2252                 }
2253
2254
2255                 /* Hack -- Handle "inkey_base" */
2256                 if (inkey_base)
2257                 {
2258                         int w = 0;
2259
2260                         /* Wait forever */
2261                         if (!inkey_scan)
2262                         {
2263                                 /* Wait for (and remove) a pending key */
2264                                 if (0 == Term_inkey(&ch, TRUE, TRUE))
2265                                 {
2266                                         break;
2267                                 }
2268
2269                                 break;
2270                         }
2271
2272                         /* Wait */
2273                         while (TRUE)
2274                         {
2275                                 /* Check for (and remove) a pending key */
2276                                 if (0 == Term_inkey(&ch, FALSE, TRUE))
2277                                 {
2278                                         break;
2279                                 }
2280
2281                                 /* No key ready */
2282                                 else
2283                                 {
2284                                         /* Increase "wait" */
2285                                         w += 10;
2286
2287                                         /* Excessive delay */
2288                                         if (w >= 100) break;
2289
2290                                         Term_xtra(TERM_XTRA_DELAY, w);
2291                                 }
2292                         }
2293
2294                         break;
2295                 }
2296
2297
2298                 /* Get a key (see above) */
2299                 ch = inkey_aux();
2300
2301
2302                 /* Handle "control-right-bracket" */
2303                 if (ch == 29)
2304                 {
2305                         /* Strip this key */
2306                         ch = 0;
2307                         continue;
2308                 }
2309
2310
2311                 /* Treat back-quote as escape */
2312 /*              if (ch == '`') ch = ESCAPE; */
2313
2314
2315                 /* End "macro trigger" */
2316                 if (parse_under && (ch <= 32))
2317                 {
2318                         /* Strip this key */
2319                         ch = 0;
2320
2321                         /* End "macro trigger" */
2322                         parse_under = FALSE;
2323                 }
2324
2325
2326                 /* Handle "control-caret" */
2327                 if (ch == 30)
2328                 {
2329                         /* Strip this key */
2330                         ch = 0;
2331                 }
2332
2333                 /* Handle "control-underscore" */
2334                 else if (ch == 31)
2335                 {
2336                         /* Strip this key */
2337                         ch = 0;
2338
2339                         /* Begin "macro trigger" */
2340                         parse_under = TRUE;
2341                 }
2342
2343                 /* Inside "macro trigger" */
2344                 else if (parse_under)
2345                 {
2346                         /* Strip this key */
2347                         ch = 0;
2348                 }
2349         }
2350
2351
2352         /* Hack -- restore the term */
2353         Term_activate(old);
2354
2355
2356         /* Restore the cursor */
2357         Term_set_cursor(v);
2358
2359
2360         /* Cancel the various "global parameters" */
2361         inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2362
2363         /* Return the keypress */
2364         return (ch);
2365 }
2366
2367
2368
2369
2370 /*
2371  * We use a global array for all inscriptions to reduce the memory
2372  * spent maintaining inscriptions.  Of course, it is still possible
2373  * to run out of inscription memory, especially if too many different
2374  * inscriptions are used, but hopefully this will be rare.
2375  *
2376  * We use dynamic string allocation because otherwise it is necessary
2377  * to pre-guess the amount of quark activity.  We limit the total
2378  * number of quarks, but this is much easier to "expand" as needed.
2379  *
2380  * Any two items with the same inscription will have the same "quark"
2381  * index, which should greatly reduce the need for inscription space.
2382  *
2383  * Note that "quark zero" is NULL and should not be "dereferenced".
2384  */
2385
2386 /*
2387  * Initialize the quark array
2388  */
2389 void quark_init(void)
2390 {
2391         /* Quark variables */
2392         C_MAKE(quark__str, QUARK_MAX, concptr);
2393
2394         /* Prepare first quark, which is used when quark_add() is failed */
2395         quark__str[1] = string_make("");
2396
2397         /* There is one quark (+ NULL) */
2398         quark__num = 2;
2399 }
2400
2401
2402 /*
2403  * Add a new "quark" to the set of quarks.
2404  */
2405 u16b quark_add(concptr str)
2406 {
2407         u16b i;
2408
2409         /* Look for an existing quark */
2410         for (i = 1; i < quark__num; i++)
2411         {
2412                 /* Check for equality */
2413                 if (streq(quark__str[i], str)) return (i);
2414         }
2415
2416         /* Return "" when no room is available */
2417         if (quark__num == QUARK_MAX) return 1;
2418
2419         /* New maximal quark */
2420         quark__num = i + 1;
2421
2422         /* Add a new quark */
2423         quark__str[i] = string_make(str);
2424
2425         /* Return the index */
2426         return (i);
2427 }
2428
2429
2430 /*
2431  * This function looks up a quark
2432  */
2433 concptr quark_str(STR_OFFSET i)
2434 {
2435         concptr q;
2436
2437         /* Return NULL for an invalid index */
2438         if ((i < 1) || (i >= quark__num)) return NULL;
2439
2440         /* Access the quark */
2441         q = quark__str[i];
2442
2443         /* Return the quark */
2444         return (q);
2445 }
2446
2447
2448
2449
2450 /*
2451  * Second try for the "message" handling routines.
2452  *
2453  * Each call to "message_add(s)" will add a new "most recent" message
2454  * to the "message recall list", using the contents of the string "s".
2455  *
2456  * The messages will be stored in such a way as to maximize "efficiency",
2457  * that is, we attempt to maximize the number of sequential messages that
2458  * can be retrieved, given a limited amount of storage space.
2459  *
2460  * We keep a buffer of chars to hold the "text" of the messages, not
2461  * necessarily in "order", and an array of offsets into that buffer,
2462  * representing the actual messages.  This is made more complicated
2463  * by the fact that both the array of indexes, and the buffer itself,
2464  * are both treated as "circular arrays" for efficiency purposes, but
2465  * the strings may not be "broken" across the ends of the array.
2466  *
2467  * The "message_add()" function is rather "complex", because it must be
2468  * extremely efficient, both in space and time, for use with the Borg.
2469  */
2470
2471
2472
2473 /*!
2474  * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
2475  * @return 残っているメッセージの数
2476  */
2477 s32b message_num(void)
2478 {
2479         int last, next, n;
2480
2481         /* Extract the indexes */
2482         last = message__last;
2483         next = message__next;
2484
2485         /* Handle "wrap" */
2486         if (next < last) next += MESSAGE_MAX;
2487
2488         /* Extract the space */
2489         n = (next - last);
2490
2491         /* Return the result */
2492         return (n);
2493 }
2494
2495
2496 /*!
2497  * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
2498  * @params age メッセージの世代
2499  * @return メッセージの文字列ポインタ
2500  */
2501 concptr message_str(int age)
2502 {
2503         s32b x;
2504         s32b o;
2505         concptr s;
2506
2507         /* Forgotten messages have no text */
2508         if ((age < 0) || (age >= message_num())) return ("");
2509
2510         /* Acquire the "logical" index */
2511         x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
2512
2513         /* Get the "offset" for the message */
2514         o = message__ptr[x];
2515
2516         /* Access the message text */
2517         s = &message__buf[o];
2518
2519         /* Return the message text */
2520         return (s);
2521 }
2522
2523
2524 /*!
2525  * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
2526  * @params str 保存したいメッセージ
2527  * @return なし
2528  */
2529 void message_add(concptr str)
2530 {
2531         u32b i, n;
2532         int k, x, m;
2533
2534         char u[4096];
2535         char splitted1[81];
2536         concptr splitted2;
2537
2538         /*** Step 1 -- Analyze the message ***/
2539
2540         /* Hack -- Ignore "non-messages" */
2541         if (!str) return;
2542
2543         /* Message length */
2544         n = strlen(str);
2545
2546         /* Important Hack -- Ignore "long" messages */
2547         if (n >= MESSAGE_BUF / 4) return;
2548
2549         /* extra step -- split the message if n>80.(added by Mogami) */
2550         if (n > 80) {
2551 #ifdef JP
2552                 concptr t = str;
2553
2554                 for (n = 0; n < 80; n++, t++)
2555                 {
2556                         if(iskanji(*t)) {
2557                                 t++;
2558                                 n++;
2559                         }
2560                 }
2561                 if (n == 81) n = 79; /* 最後の文字が漢字半分 */
2562 #else
2563                 for (n = 80; n > 60; n--)
2564                         if (str[n] == ' ') break;
2565                 if (n == 60) n = 80;
2566 #endif
2567                 splitted2 = str + n;
2568                 strncpy(splitted1, str ,n);
2569                 splitted1[n] = '\0';
2570                 str = splitted1;
2571         } else {
2572                 splitted2 = NULL;
2573         }
2574
2575         /*** Step 2 -- 最適化の試行 / Attempt to optimize ***/
2576
2577         /* Limit number of messages to check */
2578         m = message_num();
2579         k = m / 4;
2580         if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
2581
2582         /* Check previous message */
2583         for (i = message__next; m; m--)
2584         {
2585                 int j = 1;
2586
2587                 char buf[1024];
2588                 char *t;
2589
2590                 concptr old;
2591
2592                 /* Back up and wrap if needed */
2593                 if (i-- == 0) i = MESSAGE_MAX - 1;
2594
2595                 /* Access the old string */
2596                 old = &message__buf[message__ptr[i]];
2597
2598                 /* Skip small messages */
2599                 if (!old) continue;
2600
2601                 strcpy(buf, old);
2602
2603                 /* Find multiple */
2604 #ifdef JP
2605                 for (t = buf; *t && (*t != '<' || (*(t+1) != 'x' )); t++) 
2606                         if(iskanji(*t))t++;
2607 #else
2608                 for (t = buf; *t && (*t != '<'); t++);
2609 #endif
2610
2611                 if (*t)
2612                 {
2613                         /* Message is too small */
2614                         if (strlen(buf) < A_MAX) break;
2615
2616                         /* Drop the space */
2617                         *(t - 1) = '\0';
2618
2619                         /* Get multiplier */
2620                         j = atoi(t+2);
2621                 }
2622
2623                 /* Limit the multiplier to 1000 */
2624                 if (streq(buf, str) && (j < 1000))
2625                 {
2626                         j++;
2627
2628                         /* Overwrite */
2629                         message__next = i;
2630
2631                         str = u;
2632
2633                         /* Write it out */
2634                         sprintf(u, "%s <x%d>", buf, j);
2635
2636                         /* Message length */
2637                         n = strlen(str);
2638
2639                         if (!now_message) now_message++;
2640                 }
2641                 else
2642                 {
2643                         num_more++;/*流れた行の数を数えておく */
2644                         now_message++;
2645                 }
2646
2647                 break;
2648         }
2649
2650         /* Check the last few messages (if any to count) */
2651         for (i = message__next; k; k--)
2652         {
2653                 int q;
2654                 concptr old;
2655
2656                 /* Back up and wrap if needed */
2657                 if (i-- == 0) i = MESSAGE_MAX - 1;
2658
2659                 /* Stop before oldest message */
2660                 if (i == message__last) break;
2661
2662                 /* Extract "distance" from "head" */
2663                 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
2664
2665                 /* Do not optimize over large distance */
2666                 if (q > MESSAGE_BUF / 2) continue;
2667
2668                 /* Access the old string */
2669                 old = &message__buf[message__ptr[i]];
2670
2671                 /* Compare */
2672                 if (!streq(old, str)) continue;
2673
2674                 /* Get the next message index, advance */
2675                 x = message__next++;
2676
2677                 /* Handle wrap */
2678                 if (message__next == MESSAGE_MAX) message__next = 0;
2679
2680                 /* Kill last message if needed */
2681                 if (message__next == message__last) message__last++;
2682
2683                 /* Handle wrap */
2684                 if (message__last == MESSAGE_MAX) message__last = 0;
2685
2686                 /* Assign the starting address */
2687                 message__ptr[x] = message__ptr[i];
2688
2689                 /* Success */
2690                 /* return; */
2691                 goto end_of_message_add;
2692
2693         }
2694
2695
2696         /*** Step 3 -- Ensure space before end of buffer ***/
2697
2698         /* Kill messages and Wrap if needed */
2699         if (message__head + n + 1 >= MESSAGE_BUF)
2700         {
2701                 /* Kill all "dead" messages */
2702                 for (i = message__last; TRUE; i++)
2703                 {
2704                         /* Wrap if needed */
2705                         if (i == MESSAGE_MAX) i = 0;
2706
2707                         /* Stop before the new message */
2708                         if (i == message__next) break;
2709
2710                         /* Kill "dead" messages */
2711                         if (message__ptr[i] >= message__head)
2712                         {
2713                                 /* Track oldest message */
2714                                 message__last = i + 1;
2715                         }
2716                 }
2717
2718                 /* Wrap "tail" if needed */
2719                 if (message__tail >= message__head) message__tail = 0;
2720
2721                 /* Start over */
2722                 message__head = 0;
2723         }
2724
2725
2726         /*** Step 4 -- Ensure space before next message ***/
2727
2728         /* Kill messages if needed */
2729         if (message__head + n + 1 > message__tail)
2730         {
2731                 /* Grab new "tail" */
2732                 message__tail = message__head + n + 1;
2733
2734                 /* Advance tail while possible past first "nul" */
2735                 while (message__buf[message__tail-1]) message__tail++;
2736
2737                 /* Kill all "dead" messages */
2738                 for (i = message__last; TRUE; i++)
2739                 {
2740                         /* Wrap if needed */
2741                         if (i == MESSAGE_MAX) i = 0;
2742
2743                         /* Stop before the new message */
2744                         if (i == message__next) break;
2745
2746                         /* Kill "dead" messages */
2747                         if ((message__ptr[i] >= message__head) &&
2748                                 (message__ptr[i] < message__tail))
2749                         {
2750                                 /* Track oldest message */
2751                                 message__last = i + 1;
2752                         }
2753                 }
2754         }
2755
2756
2757         /*** Step 5 -- Grab a new message index ***/
2758
2759         /* Get the next message index, advance */
2760         x = message__next++;
2761
2762         /* Handle wrap */
2763         if (message__next == MESSAGE_MAX) message__next = 0;
2764
2765         /* Kill last message if needed */
2766         if (message__next == message__last) message__last++;
2767
2768         /* Handle wrap */
2769         if (message__last == MESSAGE_MAX) message__last = 0;
2770
2771
2772
2773         /*** Step 6 -- Insert the message text ***/
2774
2775         /* Assign the starting address */
2776         message__ptr[x] = message__head;
2777
2778         /* Append the new part of the message */
2779         for (i = 0; i < n; i++)
2780         {
2781                 /* Copy the message */
2782                 message__buf[message__head + i] = str[i];
2783         }
2784
2785         /* Terminate */
2786         message__buf[message__head + i] = '\0';
2787
2788         /* Advance the "head" pointer */
2789         message__head += n + 1;
2790
2791         /* recursively add splitted message (added by Mogami) */
2792 end_of_message_add:
2793         if (splitted2 != NULL)
2794           message_add(splitted2);
2795 }
2796
2797
2798
2799 /*
2800  * Hack -- flush
2801  */
2802 static void msg_flush(int x)
2803 {
2804         byte a = TERM_L_BLUE;
2805         bool nagasu = FALSE;
2806
2807         if ((auto_more && !p_ptr->now_damaged) || num_more < 0){
2808                 int i;
2809                 for (i = 0; i < 8; i++)
2810                 {
2811                         if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2812                 }
2813                 if (i < 8)
2814                 {
2815                         if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2816                 }
2817                 else
2818                 {
2819                         nagasu = TRUE;
2820                 }
2821         }
2822         p_ptr->now_damaged = FALSE;
2823
2824         if (!p_ptr->playing || !nagasu)
2825         {
2826                 /* Pause for response */
2827                 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2828
2829                 /* Get an acceptable keypress */
2830                 while (1)
2831                 {
2832                         int cmd = inkey();
2833                         if (cmd == ESCAPE) {
2834                             num_more = -9999; /*auto_moreのとき、全て流す。 */
2835                             break;
2836                         } else if (cmd == ' ') {
2837                             num_more = 0; /*1画面だけ流す。 */
2838                             break;
2839                         } else if ((cmd == '\n') || (cmd == '\r')) {
2840                             num_more--; /*1行だけ流す。 */
2841                             break;
2842                         }
2843                         if (quick_messages) break;
2844                         bell();
2845                 }
2846         }
2847
2848         /* Clear the line */
2849         Term_erase(0, 0, 255);
2850 }
2851
2852
2853 void msg_erase(void)
2854 {
2855         msg_print(NULL);
2856 }
2857
2858
2859 /*
2860  * Output a message to the top line of the screen.
2861  *
2862  * Break long messages into multiple pieces (40-72 chars).
2863  *
2864  * Allow multiple short messages to "share" the top line.
2865  *
2866  * Prompt the user to make sure he has a chance to read them.
2867  *
2868  * These messages are memorized for later reference (see above).
2869  *
2870  * We could do "Term_fresh()" to provide "flicker" if needed.
2871  *
2872  * The global "msg_flag" variable can be cleared to tell us to
2873  * "erase" any "pending" messages still on the screen.
2874  *
2875  * Note that we must be very careful about using the
2876  * "msg_print()" functions without explicitly calling the special
2877  * "msg_print(NULL)" function, since this may result in the loss
2878  * of information if the screen is cleared, or if anything is
2879  * displayed on the top line.
2880  *
2881  * Note that "msg_print(NULL)" will clear the top line
2882  * even if no messages are pending.  This is probably a hack.
2883  */
2884 void msg_print(concptr msg)
2885 {
2886         static int p = 0;
2887         int n;
2888         char *t;
2889         char buf[1024];
2890
2891         if (current_world_ptr->timewalk_m_idx) return;
2892
2893         /* Hack -- Reset */
2894         if (!msg_flag) {
2895                 /* Clear the line */
2896                 Term_erase(0, 0, 255);
2897                 p = 0;
2898         }
2899
2900         /* Original Message Length */
2901         n = (msg ? strlen(msg) : 0);
2902
2903         /* Hack -- flush when requested or needed */
2904         if (p && (!msg || ((p + n) > 72)))
2905         {
2906                 msg_flush(p);
2907
2908                 /* Forget it */
2909                 msg_flag = FALSE;
2910
2911                 /* Reset */
2912                 p = 0;
2913         }
2914
2915         /* No message */
2916         if (!msg) return;
2917         if (n > 1000) return;
2918
2919         /* Copy it */
2920         if (!cheat_turn)
2921         {
2922                 strcpy(buf, msg);
2923         }
2924         else
2925         {
2926                 sprintf(buf, ("T:%d - %s"), (int)current_world_ptr->game_turn, msg);
2927         }
2928
2929         /* New Message Length */
2930         n = strlen(buf);
2931
2932         /* Memorize the message */
2933         if (current_world_ptr->character_generated) message_add(buf);
2934
2935         /* Analyze the buffer */
2936         t = buf;
2937
2938         /* Split message */
2939         while (n > 72)
2940         {
2941                 char oops;
2942                 int check, split = 72;
2943
2944 #ifdef JP
2945                 bool k_flag = FALSE;
2946                 int wordlen = 0;
2947
2948                 /* Find the "best" split point */
2949                 for (check = 0; check < 72; check++)
2950                 {
2951                         if (k_flag)
2952                         {
2953                                 k_flag = FALSE;
2954                                 continue;
2955                         }
2956
2957                         /* Found a valid split point */
2958                         if (iskanji(t[check]))
2959                         {
2960                                 k_flag = TRUE;
2961                                 split = check;
2962                         }
2963                         else if (t[check] == ' ')
2964                         {
2965                                 split = check;
2966                                 wordlen = 0;
2967                         }
2968                         else
2969                         {
2970                                 wordlen++;
2971                                 if (wordlen > 20)
2972                                         split = check;
2973                         }
2974                 }
2975 #else
2976                 /* Find the "best" split point */
2977                 for (check = 40; check < 72; check++)
2978                 {
2979                         /* Found a valid split point */
2980                         if (t[check] == ' ') split = check;
2981                 }
2982 #endif
2983
2984                 /* Save the split character */
2985                 oops = t[split];
2986
2987                 /* Split the message */
2988                 t[split] = '\0';
2989
2990                 /* Display part of the message */
2991                 Term_putstr(0, 0, split, TERM_WHITE, t);
2992
2993                 /* Flush it */
2994                 msg_flush(split + 1);
2995
2996                 /* Memorize the piece */
2997                 /* if (current_world_ptr->character_generated) message_add(t); */
2998
2999                 /* Restore the split character */
3000                 t[split] = oops;
3001
3002                 /* Insert a space */
3003                 t[--split] = ' ';
3004
3005                 /* Prepare to recurse on the rest of "buf" */
3006                 t += split; n -= split;
3007         }
3008
3009         /* Display the tail of the message */
3010         Term_putstr(p, 0, n, TERM_WHITE, t);
3011
3012         /* Memorize the tail */
3013         /* if (current_world_ptr->character_generated) message_add(t); */
3014
3015         p_ptr->window |= (PW_MESSAGE);
3016         update_output();
3017
3018         /* Remember the message */
3019         msg_flag = TRUE;
3020
3021         /* Remember the position */
3022 #ifdef JP
3023         p += n;
3024 #else
3025         p += n + 1;
3026 #endif
3027
3028         /* Optional refresh */
3029         if (fresh_message) Term_fresh();
3030 }
3031
3032 void msg_print_wizard(int cheat_type, concptr msg)
3033 {
3034         if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
3035         if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
3036         if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
3037         if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
3038
3039         concptr cheat_mes[] = {"ITEM", "MONS", "DUNG", "MISC"};
3040         char buf[1024];
3041         sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
3042         msg_print(buf);
3043
3044         if (cheat_diary_output)
3045         {
3046                 do_cmd_write_nikki(NIKKI_WIZARD_LOG, 0, buf);
3047         }
3048
3049 }
3050
3051 /*
3052  * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
3053  */
3054 static int screen_depth = 0;
3055
3056
3057 /*
3058  * Save the screen, and increase the "icky" depth.
3059  *
3060  * This function must match exactly one call to "screen_load()".
3061  */
3062 void screen_save(void)
3063 {
3064         /* Hack -- Flush messages */
3065         msg_print(NULL);
3066
3067         /* Save the screen (if legal) */
3068         if (screen_depth++ == 0) Term_save();
3069
3070         /* Increase "icky" depth */
3071         current_world_ptr->character_icky++;
3072 }
3073
3074
3075 /*
3076  * Load the screen, and decrease the "icky" depth.
3077  *
3078  * This function must match exactly one call to "screen_save()".
3079  */
3080 void screen_load(void)
3081 {
3082         /* Hack -- Flush messages */
3083         msg_print(NULL);
3084
3085         /* Load the screen (if legal) */
3086         if (--screen_depth == 0) Term_load();
3087
3088         /* Decrease "icky" depth */
3089         current_world_ptr->character_icky--;
3090 }
3091
3092
3093 /*
3094  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
3095  */
3096 void msg_format(concptr fmt, ...)
3097 {
3098         va_list vp;
3099
3100         char buf[1024];
3101
3102         /* Begin the Varargs Stuff */
3103         va_start(vp, fmt);
3104
3105         /* Format the args, save the length */
3106         (void)vstrnfmt(buf, 1024, fmt, vp);
3107
3108         /* End the Varargs Stuff */
3109         va_end(vp);
3110
3111         /* Display */
3112         msg_print(buf);
3113 }
3114
3115 /*
3116  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
3117  */
3118 void msg_format_wizard(int cheat_type, concptr fmt, ...)
3119 {
3120         if(!cheat_room && cheat_type == CHEAT_DUNGEON) return;
3121         if(!cheat_peek && cheat_type == CHEAT_OBJECT) return;
3122         if(!cheat_hear && cheat_type == CHEAT_MONSTER) return;
3123         if(!cheat_xtra && cheat_type == CHEAT_MISC) return;
3124
3125         va_list vp;
3126         char buf[1024];
3127
3128         /* Begin the Varargs Stuff */
3129         va_start(vp, fmt);
3130
3131         /* Format the args, save the length */
3132         (void)vstrnfmt(buf, 1024, fmt, vp);
3133
3134         /* End the Varargs Stuff */
3135         va_end(vp);
3136
3137         /* Display */
3138         msg_print_wizard(cheat_type, buf);
3139 }
3140
3141
3142
3143 /*
3144  * Display a string on the screen using an attribute.
3145  *
3146  * At the given location, using the given attribute, if allowed,
3147  * add the given string.  Do not clear the line.
3148  */
3149 void c_put_str(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
3150 {
3151         /* Position cursor, Dump the attr/text */
3152         Term_putstr(col, row, -1, attr, str);
3153 }
3154
3155 /*
3156  * As above, but in "white"
3157  */
3158 void put_str(concptr str, TERM_LEN row, TERM_LEN col)
3159 {
3160         /* Spawn */
3161         Term_putstr(col, row, -1, TERM_WHITE, str);
3162 }
3163
3164
3165
3166 /*
3167  * Display a string on the screen using an attribute, and clear
3168  * to the end of the line.
3169  */
3170 void c_prt(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
3171 {
3172         /* Clear line, position cursor */
3173         Term_erase(col, row, 255);
3174
3175         /* Dump the attr/text */
3176         Term_addstr(-1, attr, str);
3177 }
3178
3179 /*
3180  * As above, but in "white"
3181  */
3182 void prt(concptr str, TERM_LEN row, TERM_LEN col)
3183 {
3184         /* Spawn */
3185         c_prt(TERM_WHITE, str, row, col);
3186 }
3187
3188
3189
3190
3191 /*
3192  * Print some (colored) text to the screen at the current cursor position,
3193  * automatically "wrapping" existing text (at spaces) when necessary to
3194  * avoid placing any text into the last column, and clearing every line
3195  * before placing any text in that line.  Also, allow "newline" to force
3196  * a "wrap" to the next line.  Advance the cursor as needed so sequential
3197  * calls to this function will work correctly.
3198  *
3199  * Once this function has been called, the cursor should not be moved
3200  * until all the related "c_roff()" calls to the window are complete.
3201  *
3202  * This function will correctly handle any width up to the maximum legal
3203  * value of 256, though it works best for a standard 80 character width.
3204  */
3205 void c_roff(byte a, concptr str)
3206 {
3207         int x, y;
3208
3209         int w, h;
3210
3211         concptr s;
3212
3213         /* Obtain the size */
3214         (void)Term_get_size(&w, &h);
3215
3216         /* Obtain the cursor */
3217         (void)Term_locate(&x, &y);
3218
3219         /* Hack -- No more space */
3220         if( y == h - 1 && x > w - 3) return;
3221
3222         /* Process the string */
3223         for (s = str; *s; s++)
3224         {
3225                 char ch;
3226
3227 #ifdef JP
3228                 int k_flag = iskanji(*s);
3229 #endif
3230                 /* Force wrap */
3231                 if (*s == '\n')
3232                 {
3233                         /* Wrap */
3234                         x = 0;
3235                         y++;
3236
3237                         /* No more space */
3238                         if( y == h ) break;
3239
3240                         /* Clear line, move cursor */
3241                         Term_erase(x, y, 255);
3242
3243                         break;
3244                 }
3245
3246                 /* Clean up the char */
3247 #ifdef JP
3248                 ch = ((k_flag || isprint(*s)) ? *s : ' ');
3249 #else
3250                 ch = (isprint(*s) ? *s : ' ');
3251 #endif
3252
3253
3254                 /* Wrap words as needed */
3255 #ifdef JP
3256                 if (( x >= ( (k_flag) ? w - 2 : w - 1 ) ) && (ch != ' '))
3257 #else
3258                 if ((x >= w - 1) && (ch != ' '))
3259 #endif
3260
3261                 {
3262                         int i, n = 0;
3263
3264                         TERM_COLOR av[256];
3265                         char cv[256];
3266
3267                         /* Wrap word */
3268                         if (x < w)
3269 #ifdef JP
3270                         {
3271                         /* 現在が半角文字の場合 */
3272                         if( !k_flag )
3273 #endif
3274                         {
3275                                 /* Scan existing text */
3276                                 for (i = w - 2; i >= 0; i--)
3277                                 {
3278                                         /* Grab existing attr/char */
3279                                         Term_what(i, y, &av[i], &cv[i]);
3280
3281                                         /* Break on space */
3282                                         if (cv[i] == ' ') break;
3283
3284                                         /* Track current word */
3285                                         n = i;
3286 #ifdef JP
3287                                         if (cv[i] == '(') break;
3288 #endif
3289                                 }
3290                         }
3291
3292 #ifdef JP
3293                         else
3294                         {
3295                                 /* 現在が全角文字のとき */
3296                                 /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
3297                                 if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0
3298 #if 0                   /* 一般的には「ィ」「ー」は禁則の対象外 */
3299                                         || strncmp(s, "ィ", 2) == 0 || strncmp(s, "ー", 2) == 0
3300 #endif
3301                                ){
3302                                         Term_what(x  , y, &av[x  ], &cv[x  ]);
3303                                         Term_what(x-1, y, &av[x-1], &cv[x-1]);
3304                                         Term_what(x-2, y, &av[x-2], &cv[x-2]);
3305                                         n = x - 2;
3306                                         cv[ x ] = '\0';
3307                                 }
3308                         }
3309                         }
3310 #endif
3311                         /* Special case */
3312                         if (n == 0) n = w;
3313
3314                         /* Clear line */
3315                         Term_erase(n, y, 255);
3316
3317                         /* Wrap */
3318                         x = 0;
3319                         y++;
3320
3321                         /* No more space */
3322                         if( y == h ) break;
3323
3324                         /* Clear line, move cursor */
3325                         Term_erase(x, y, 255);
3326
3327                         /* Wrap the word (if any) */
3328                         for (i = n; i < w - 1; i++)
3329                         {
3330 #ifdef JP
3331                                 if( cv[i] == '\0' ) break;
3332 #endif
3333                                 /* Dump */
3334                                 Term_addch(av[i], cv[i]);
3335
3336                                 /* Advance (no wrap) */
3337                                 if (++x > w) x = w;
3338                         }
3339                 }
3340
3341                 /* Dump */
3342 #ifdef JP
3343                 Term_addch((byte)(a|0x10), ch);
3344 #else
3345                 Term_addch(a, ch);
3346 #endif
3347
3348
3349 #ifdef JP
3350                 if (k_flag)
3351                 {
3352                         s++;
3353                         x++;
3354                         ch = *s;
3355                         Term_addch((byte)(a|0x20), ch);
3356                 }
3357 #endif
3358                 /* Advance */
3359                 if (++x > w) x = w;
3360         }
3361 }
3362
3363 /*
3364  * As above, but in "white"
3365  */
3366 void roff(concptr str)
3367 {
3368         /* Spawn */
3369         c_roff(TERM_WHITE, str);
3370 }
3371
3372
3373
3374
3375 /*
3376  * Clear part of the screen
3377  */
3378 void clear_from(int row)
3379 {
3380         int y;
3381
3382         /* Erase requested rows */
3383         for (y = row; y < Term->hgt; y++)
3384         {
3385                 /* Erase part of the screen */
3386                 Term_erase(0, y, 255);
3387         }
3388 }
3389
3390
3391
3392
3393 /*
3394  * Get some string input at the cursor location.
3395  * Assume the buffer is initialized to a default string.
3396  *
3397  * The default buffer is in Overwrite mode and displayed in yellow at
3398  * first.  Normal chars clear the yellow text and append the char in
3399  * white text.
3400  *
3401  * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
3402  * If the text is still displayed in yellow (Overwite mode), it will
3403  * turns into white (Insert mode) when cursor moves.
3404  *
3405  * DELETE (^D) deletes a char at the cursor position.
3406  * BACKSPACE (^H) deletes a char at the left of cursor position.
3407  * ESCAPE clears the buffer and the window and returns FALSE.
3408  * RETURN accepts the current buffer contents and returns TRUE.
3409  */
3410 bool askfor_aux(char *buf, int len, bool numpad_cursor)
3411 {
3412         int y, x;
3413         int pos = 0;
3414
3415         /*
3416          * Text color
3417          * TERM_YELLOW : Overwrite mode
3418          * TERM_WHITE : Insert mode
3419          */
3420         byte color = TERM_YELLOW;
3421
3422         /* Locate the cursor position */
3423         Term_locate(&x, &y);
3424
3425         /* Paranoia -- check len */
3426         if (len < 1) len = 1;
3427
3428         /* Paranoia -- check column */
3429         if ((x < 0) || (x >= 80)) x = 0;
3430
3431         /* Restrict the length */
3432         if (x + len > 80) len = 80 - x;
3433
3434         /* Paranoia -- Clip the default entry */
3435         buf[len] = '\0';
3436
3437
3438         /* Process input */
3439         while (TRUE)
3440         {
3441                 int skey;
3442
3443                 /* Display the string */
3444                 Term_erase(x, y, len);
3445                 Term_putstr(x, y, -1, color, buf);
3446
3447                 /* Place cursor */
3448                 Term_gotoxy(x + pos, y);
3449
3450                 /* Get a special key code */
3451                 skey = inkey_special(numpad_cursor);
3452
3453                 /* Analyze the key */
3454                 switch (skey)
3455                 {
3456                 case SKEY_LEFT:
3457                 case KTRL('b'):
3458                 {
3459                         int i = 0;
3460
3461                         /* Now on insert mode */
3462                         color = TERM_WHITE;
3463
3464                         /* No move at beginning of line */
3465                         if (0 == pos) break;
3466
3467                         while (TRUE)
3468                         {
3469                                 int next_pos = i + 1;
3470
3471 #ifdef JP
3472                                 if (iskanji(buf[i])) next_pos++;
3473 #endif
3474
3475                                 /* Is there the cursor at next position? */ 
3476                                 if (next_pos >= pos) break;
3477
3478                                 /* Move to next */
3479                                 i = next_pos;
3480                         }
3481
3482                         /* Get previous position */
3483                         pos = i;
3484
3485                         break;
3486                 }
3487
3488                 case SKEY_RIGHT:
3489                 case KTRL('f'):
3490                         /* Now on insert mode */
3491                         color = TERM_WHITE;
3492
3493                         /* No move at end of line */
3494                         if ('\0' == buf[pos]) break;
3495
3496 #ifdef JP
3497                         /* Move right */
3498                         if (iskanji(buf[pos])) pos += 2;
3499                         else pos++;
3500 #else
3501                         pos++;
3502 #endif
3503
3504                         break;
3505
3506                 case ESCAPE:
3507                         /* Cancel input */
3508                         buf[0] = '\0';
3509                         return FALSE;
3510
3511                 case '\n':
3512                 case '\r':
3513                         /* Success */
3514                         return TRUE;
3515
3516                 case '\010':
3517                         /* Backspace */
3518                 {
3519                         int i = 0;
3520
3521                         /* Now on insert mode */
3522                         color = TERM_WHITE;
3523
3524                         /* No move at beginning of line */
3525                         if (0 == pos) break;
3526
3527                         while (TRUE)
3528                         {
3529                                 int next_pos = i + 1;
3530
3531 #ifdef JP
3532                                 if (iskanji(buf[i])) next_pos++;
3533 #endif
3534
3535                                 /* Is there the cursor at next position? */ 
3536                                 if (next_pos >= pos) break;
3537
3538                                 /* Move to next */
3539                                 i = next_pos;
3540                         }
3541
3542                         /* Get previous position */
3543                         pos = i;
3544
3545                         /* Fall through to 'Delete key' */
3546                 }
3547
3548                 case 0x7F:
3549                 case KTRL('d'):
3550                         /* Delete key */
3551                 {
3552                         int dst, src;
3553
3554                         /* Now on insert mode */
3555                         color = TERM_WHITE;
3556
3557                         /* No move at end of line */
3558                         if ('\0' == buf[pos]) break;
3559
3560                         /* Position of next character */
3561                         src = pos + 1;
3562
3563 #ifdef JP
3564                         /* Next character is one more byte away */
3565                         if (iskanji(buf[pos])) src++;
3566 #endif
3567
3568                         dst = pos;
3569
3570                         /* Move characters at src to dst */
3571                         while ('\0' != (buf[dst++] = buf[src++]))
3572                                 /* loop */;
3573
3574                         break;
3575                 }
3576
3577                 default:
3578                 {
3579                         /* Insert a character */
3580
3581                         char tmp[100];
3582                         char c;
3583
3584                         /* Ignore special keys */
3585                         if (skey & SKEY_MASK) break;
3586
3587                         /* Get a character code */
3588                         c = (char)skey;
3589
3590                         if (color == TERM_YELLOW)
3591                         {
3592                                 /* Overwrite default string */
3593                                 buf[0] = '\0';
3594
3595                                 /* Go to insert mode */
3596                                 color = TERM_WHITE;
3597                         }
3598
3599                         /* Save right part of string */
3600                         strcpy(tmp, buf + pos);
3601 #ifdef JP
3602                         if (iskanji(c))
3603                         {
3604                                 char next;
3605
3606                                 /* Bypass macro processing */
3607                                 inkey_base = TRUE;
3608                                 next = inkey();
3609
3610                                 if (pos + 1 < len)
3611                                 {
3612                                         buf[pos++] = c;
3613                                         buf[pos++] = next;
3614                                 }
3615                                 else
3616                                 {
3617                                         bell();
3618                                 }
3619                         }
3620                         else
3621 #endif
3622                         {
3623 #ifdef JP
3624                                 if (pos < len && (isprint(c) || iskana(c)))
3625 #else
3626                                 if (pos < len && isprint(c))
3627 #endif
3628                                 {
3629                                         buf[pos++] = c;
3630                                 }
3631                                 else
3632                                 {
3633                                         bell();
3634                                 }
3635                         }
3636
3637                         /* Terminate */
3638                         buf[pos] = '\0';
3639
3640                         /* Write back the left part of string */
3641                         my_strcat(buf, tmp, len + 1);
3642
3643                         break;
3644                 } /* default: */
3645
3646                 }
3647
3648         } /* while (TRUE) */
3649 }
3650
3651
3652 /*
3653  * Get some string input at the cursor location.
3654  *
3655  * Allow to use numpad keys as cursor keys.
3656  */
3657 bool askfor(char *buf, int len)
3658 {
3659         return askfor_aux(buf, len, TRUE);
3660 }
3661
3662
3663 /*
3664  * Get a string from the user
3665  *
3666  * The "prompt" should take the form "Prompt: "
3667  *
3668  * Note that the initial contents of the string is used as
3669  * the default response, so be sure to "clear" it if needed.
3670  *
3671  * We clear the input, and return FALSE, on "ESCAPE".
3672  */
3673 bool get_string(concptr prompt, char *buf, int len)
3674 {
3675         bool res;
3676         msg_print(NULL);
3677
3678         /* Display prompt */
3679         prt(prompt, 0, 0);
3680
3681         /* Ask the user for a string */
3682         res = askfor(buf, len);
3683
3684         /* Clear prompt */
3685         prt("", 0, 0);
3686         return (res);
3687 }
3688
3689
3690 /*
3691  * Verify something with the user
3692  *
3693  * The "prompt" should take the form "Query? "
3694  *
3695  * Note that "[y/n]" is appended to the prompt.
3696  */
3697 bool get_check(concptr prompt)
3698 {
3699         return get_check_strict(prompt, 0);
3700 }
3701
3702 /*
3703  * Verify something with the user strictly
3704  *
3705  * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
3706  * mode & CHECK_NO_ESCAPE   : don't allow ESCAPE key
3707  * mode & CHECK_NO_HISTORY  : no message_add
3708  * mode & CHECK_DEFAULT_Y   : accept any key as y, except n and Esc.
3709  */
3710 bool get_check_strict(concptr prompt, BIT_FLAGS mode)
3711 {
3712         int i;
3713         char buf[80];
3714         bool flag = FALSE;
3715
3716         if (auto_more)
3717         {
3718                 p_ptr->window |= PW_MESSAGE;
3719                 handle_stuff();
3720                 num_more = 0;
3721         }
3722         msg_print(NULL);
3723
3724         if (!rogue_like_commands)
3725                 mode &= ~CHECK_OKAY_CANCEL;
3726
3727
3728         /* Hack -- Build a "useful" prompt */
3729         if (mode & CHECK_OKAY_CANCEL)
3730         {
3731                 my_strcpy(buf, prompt, sizeof(buf)-15);
3732                 strcat(buf, "[(O)k/(C)ancel]");
3733         }
3734         else if (mode & CHECK_DEFAULT_Y)
3735         {
3736                 my_strcpy(buf, prompt, sizeof(buf)-5);
3737                 strcat(buf, "[Y/n]");
3738         }
3739         else
3740         {
3741                 my_strcpy(buf, prompt, sizeof(buf)-5);
3742                 strcat(buf, "[y/n]");
3743         }
3744
3745         /* Prompt for it */
3746         prt(buf, 0, 0);
3747
3748         if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
3749         {
3750                 /* HACK : Add the line to message buffer */
3751                 message_add(buf);
3752                 p_ptr->window |= (PW_MESSAGE);
3753                 handle_stuff();
3754         }
3755
3756         /* Get an acceptable answer */
3757         while (TRUE)
3758         {
3759                 i = inkey();
3760
3761                 if (!(mode & CHECK_NO_ESCAPE))
3762                 {
3763                         if (i == ESCAPE)
3764                         {
3765                                 flag = FALSE;
3766                                 break;
3767                         }
3768                 }
3769
3770                 if (mode & CHECK_OKAY_CANCEL)
3771                 {
3772                         if (i == 'o' || i == 'O')
3773                         {
3774                                 flag = TRUE;
3775                                 break;
3776                         }
3777                         else if (i == 'c' || i == 'C')
3778                         {
3779                                 flag = FALSE;
3780                                 break;
3781                         }
3782                 }
3783                 else
3784                 {
3785                         if (i == 'y' || i == 'Y')
3786                         {
3787                                 flag = TRUE;
3788                                 break;
3789                         }
3790                         else if (i == 'n' || i == 'N')
3791                         {
3792                                 flag = FALSE;
3793                                 break;
3794                         }
3795                 }
3796
3797                 if (mode & CHECK_DEFAULT_Y)
3798                 {
3799                         flag = TRUE;
3800                         break;
3801                 }
3802
3803                 bell();
3804         }
3805
3806         /* Erase the prompt */
3807         prt("", 0, 0);
3808
3809         /* Return the flag */
3810         return flag;
3811 }
3812
3813
3814 /*
3815  * Prompts for a keypress
3816  *
3817  * The "prompt" should take the form "Command: "
3818  *
3819  * Returns TRUE unless the character is "Escape"
3820  */
3821 bool get_com(concptr prompt, char *command, bool z_escape)
3822 {
3823         msg_print(NULL);
3824
3825         /* Display a prompt */
3826         prt(prompt, 0, 0);
3827
3828         /* Get a key */
3829         if (get_com_no_macros)
3830                 *command = (char)inkey_special(FALSE);
3831         else
3832                 *command = inkey();
3833
3834         /* Clear the prompt */
3835         prt("", 0, 0);
3836
3837         /* Handle "cancel" */
3838         if (*command == ESCAPE) return (FALSE);
3839         if (z_escape && ((*command == 'z') || (*command == 'Z'))) return (FALSE);
3840
3841         /* Success */
3842         return (TRUE);
3843 }
3844
3845
3846 /*
3847  * Request a "quantity" from the user
3848  *
3849  * Hack -- allow "command_arg" to specify a quantity
3850  */
3851 QUANTITY get_quantity(concptr prompt, QUANTITY max)
3852 {
3853         bool res, result;
3854         QUANTITY amt;
3855         char tmp[80];
3856         char buf[80];
3857         COMMAND_CODE code;
3858
3859
3860         /* Use "command_arg" */
3861         if (command_arg)
3862         {
3863                 /* Extract a number */
3864                 amt = command_arg;
3865
3866                 /* Clear "command_arg" */
3867                 command_arg = 0;
3868
3869                 /* Enforce the maximum */
3870                 if (amt > max) amt = max;
3871
3872                 /* Use it */
3873                 return (amt);
3874         }
3875
3876         /* Get the item index */
3877         result = repeat_pull(&code);
3878         amt = (QUANTITY)code;
3879         if ((max != 1) && result)
3880         {
3881                 /* Enforce the maximum */
3882                 if (amt > max) amt = max;
3883
3884                 /* Enforce the minimum */
3885                 if (amt < 0) amt = 0;
3886
3887                 /* Use it */
3888                 return (amt);
3889         }
3890
3891         /* Build a prompt if needed */
3892         if (!prompt)
3893         {
3894                 /* Build a prompt */
3895                 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
3896
3897                 /* Use that prompt */
3898                 prompt = tmp;
3899         }
3900         msg_print(NULL);
3901
3902         /* Display prompt */
3903         prt(prompt, 0, 0);
3904
3905         /* Default to one */
3906         amt = 1;
3907
3908         /* Build the default */
3909         sprintf(buf, "%d", amt);
3910
3911         /*
3912          * Ask for a quantity
3913          * Don't allow to use numpad as cursor key.
3914          */
3915         res = askfor_aux(buf, 6, FALSE);
3916
3917         /* Clear prompt */
3918         prt("", 0, 0);
3919
3920         /* Cancelled */
3921         if (!res) return 0;
3922
3923         /* Extract a number */
3924         amt = (COMMAND_CODE)atoi(buf);
3925
3926         /* A letter means "all" */
3927         if (isalpha(buf[0])) amt = max;
3928
3929         /* Enforce the maximum */
3930         if (amt > max) amt = max;
3931
3932         /* Enforce the minimum */
3933         if (amt < 0) amt = 0;
3934
3935         if (amt) repeat_push((COMMAND_CODE)amt);
3936
3937         /* Return the result */
3938         return (amt);
3939 }
3940
3941
3942 /*
3943  * Pause for user response 
3944  */
3945 void pause_line(int row)
3946 {
3947         prt("", row, 0);
3948         put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
3949
3950         (void)inkey();
3951         prt("", row, 0);
3952 }
3953
3954
3955 /*
3956  * Hack -- special buffer to hold the action of the current keymap
3957  */
3958 static char request_command_buffer[256];
3959
3960
3961
3962 typedef struct
3963 {
3964         concptr name;
3965         byte cmd;
3966         bool fin;
3967 } menu_naiyou;
3968
3969 #ifdef JP
3970 menu_naiyou menu_info[10][10] =
3971 {
3972         {
3973                 {"魔法/特殊能力", 1, FALSE},
3974                 {"行動", 2, FALSE},
3975                 {"道具(使用)", 3, FALSE},
3976                 {"道具(その他)", 4, FALSE},
3977                 {"装備", 5, FALSE},
3978                 {"扉/箱", 6, FALSE},
3979                 {"情報", 7, FALSE},
3980                 {"設定", 8, FALSE},
3981                 {"その他", 9, FALSE},
3982                 {"", 0, FALSE},
3983         },
3984
3985         {
3986                 {"使う(m)", 'm', TRUE},
3987                 {"調べる(b/P)", 'b', TRUE},
3988                 {"覚える(G)", 'G', TRUE},
3989                 {"特殊能力を使う(U/O)", 'U', TRUE},
3990                 {"", 0, FALSE},
3991                 {"", 0, FALSE},
3992                 {"", 0, FALSE},
3993                 {"", 0, FALSE},
3994                 {"", 0, FALSE},
3995                 {"", 0, FALSE}
3996         },
3997
3998         {
3999                 {"休息する(R)", 'R', TRUE},
4000                 {"トラップ解除(D)", 'D', TRUE},
4001                 {"探す(s)", 's', TRUE},
4002                 {"周りを調べる(l/x)", 'l', TRUE},
4003                 {"ターゲット指定(*)", '*', TRUE},
4004                 {"穴を掘る(T/^t)", 'T', TRUE},
4005                 {"階段を上る(<)", '<', TRUE},
4006                 {"階段を下りる(>)", '>', TRUE},
4007                 {"ペットに命令する(p)", 'p', TRUE},
4008                 {"探索モードのON/OFF(S/#)", 'S', TRUE}
4009         },
4010
4011         {
4012                 {"読む(r)", 'r', TRUE},
4013                 {"飲む(q)", 'q', TRUE},
4014                 {"杖を使う(u/Z)", 'u', TRUE},
4015                 {"魔法棒で狙う(a/z)", 'a', TRUE},
4016                 {"ロッドを振る(z/a)", 'z', TRUE},
4017                 {"始動する(A)", 'A', TRUE},
4018                 {"食べる(E)", 'E', TRUE},
4019                 {"飛び道具で撃つ(f/t)", 'f', TRUE},
4020                 {"投げる(v)", 'v', TRUE},
4021                 {"", 0, FALSE}
4022         },
4023
4024         {
4025                 {"拾う(g)", 'g', TRUE},
4026                 {"落とす(d)", 'd', TRUE},
4027                 {"壊す(k/^d)", 'k', TRUE},
4028                 {"銘を刻む({)", '{', TRUE},
4029                 {"銘を消す(})", '}', TRUE},
4030                 {"調査(I)", 'I', TRUE},
4031                 {"アイテム一覧(i)", 'i', TRUE},
4032                 {"", 0, FALSE},
4033                 {"", 0, FALSE},
4034                 {"", 0, FALSE}
4035         },
4036
4037         {
4038                 {"装備する(w)", 'w', TRUE},
4039                 {"装備を外す(t/T)", 't', TRUE},
4040                 {"燃料を補給(F)", 'F', TRUE},
4041                 {"装備一覧(e)", 'e', TRUE},
4042                 {"", 0, FALSE},
4043                 {"", 0, FALSE},
4044                 {"", 0, FALSE},
4045                 {"", 0, FALSE},
4046                 {"", 0, FALSE},
4047                 {"", 0, FALSE}
4048         },
4049
4050         {
4051                 {"開ける(o)", 'o', TRUE},
4052                 {"閉じる(c)", 'c', TRUE},
4053                 {"体当たりする(B/f)", 'B', TRUE},
4054                 {"くさびを打つ(j/S)", 'j', TRUE},
4055                 {"", 0, FALSE},
4056                 {"", 0, FALSE},
4057                 {"", 0, FALSE},
4058                 {"", 0, FALSE},
4059                 {"", 0, FALSE},
4060                 {"", 0, FALSE}
4061         },
4062
4063         {
4064                 {"ダンジョンの全体図(M)", 'M', TRUE},
4065                 {"位置を確認(L/W)", 'L', TRUE},
4066                 {"階の雰囲気(^f)", KTRL('F'), TRUE},
4067                 {"ステータス(C)", 'C', TRUE},
4068                 {"文字の説明(/)", '/', TRUE},
4069                 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
4070                 {"現在の時刻(^t/')", KTRL('T'), TRUE},
4071                 {"現在の知識(~)", '~', TRUE},
4072                 {"プレイ記録(|)", '|', TRUE},
4073                 {"", 0, FALSE}
4074         },
4075
4076         {
4077                 {"オプション(=)", '=', TRUE},
4078                 {"マクロ(@)", '@', TRUE},
4079                 {"画面表示(%)", '%', TRUE},
4080                 {"カラー(&)", '&', TRUE},
4081                 {"設定変更コマンド(\")", '\"', TRUE},
4082                 {"自動拾いをロード($)", '$', TRUE},
4083                 {"システム(!)", '!', TRUE},
4084                 {"", 0, FALSE},
4085                 {"", 0, FALSE},
4086                 {"", 0, FALSE}
4087         },
4088
4089         {
4090                 {"セーブ&中断(^x)", KTRL('X'), TRUE},
4091                 {"セーブ(^s)", KTRL('S'), TRUE},
4092                 {"ヘルプ(?)", '?', TRUE},
4093                 {"再描画(^r)", KTRL('R'), TRUE},
4094                 {"メモ(:)", ':', TRUE},
4095                 {"記念撮影())", ')', TRUE},
4096                 {"記念撮影の表示(()", '(', TRUE},
4097                 {"バージョン情報(V)", 'V', TRUE},
4098                 {"引退する(Q)", 'Q', TRUE},
4099                 {"", 0, FALSE}
4100         },
4101 };
4102 #else
4103 menu_naiyou menu_info[10][10] =
4104 {
4105         {
4106                 {"Magic/Special", 1, FALSE},
4107                 {"Action", 2, FALSE},
4108                 {"Items(use)", 3, FALSE},
4109                 {"Items(other)", 4, FALSE},
4110                 {"Equip", 5, FALSE},
4111                 {"Door/Box", 6, FALSE},
4112                 {"Informations", 7, FALSE},
4113                 {"Options", 8, FALSE},
4114                 {"Other commands", 9, FALSE},
4115                 {"", 0, FALSE},
4116         },
4117
4118         {
4119                 {"Use(m)", 'm', TRUE},
4120                 {"See tips(b/P)", 'b', TRUE},
4121                 {"Study(G)", 'G', TRUE},
4122                 {"Special abilities(U/O)", 'U', TRUE},
4123                 {"", 0, FALSE},
4124                 {"", 0, FALSE},
4125                 {"", 0, FALSE},
4126                 {"", 0, FALSE},
4127                 {"", 0, FALSE},
4128                 {"", 0, FALSE}
4129         },
4130
4131         {
4132                 {"Rest(R)", 'R', TRUE},
4133                 {"Disarm a trap(D)", 'D', TRUE},
4134                 {"Search(s)", 's', TRUE},
4135                 {"Look(l/x)", 'l', TRUE},
4136                 {"Target(*)", '*', TRUE},
4137                 {"Dig(T/^t)", 'T', TRUE},
4138                 {"Go up stairs(<)", '<', TRUE},
4139                 {"Go down stairs(>)", '>', TRUE},
4140                 {"Command pets(p)", 'p', TRUE},
4141                 {"Search mode ON/OFF(S/#)", 'S', TRUE}
4142         },
4143
4144         {
4145                 {"Read a scroll(r)", 'r', TRUE},
4146                 {"Drink a potion(q)", 'q', TRUE},
4147                 {"Use a staff(u/Z)", 'u', TRUE},
4148                 {"Aim a wand(a/z)", 'a', TRUE},
4149                 {"Zap a rod(z/a)", 'z', TRUE},
4150                 {"Activate an equipment(A)", 'A', TRUE},
4151                 {"Eat(E)", 'E', TRUE},
4152                 {"Fire missile weapon(f/t)", 'f', TRUE},
4153                 {"Throw an item(v)", 'v', TRUE},
4154                 {"", 0, FALSE}
4155         },
4156
4157         {
4158                 {"Get items(g)", 'g', TRUE},
4159                 {"Drop an item(d)", 'd', TRUE},
4160                 {"Destroy an item(k/^d)", 'k', TRUE},
4161                 {"Inscribe an item({)", '{', TRUE},
4162                 {"Uninscribe an item(})", '}', TRUE},
4163                 {"Info about an item(I)", 'I', TRUE},
4164                 {"Inventory list(i)", 'i', TRUE},
4165                 {"", 0, FALSE},
4166                 {"", 0, FALSE},
4167                 {"", 0, FALSE}
4168         },
4169
4170         {
4171                 {"Wear(w)", 'w', TRUE},
4172                 {"Take off(t/T)", 't', TRUE},
4173                 {"Refuel(F)", 'F', TRUE},
4174                 {"Equipment list(e)", 'e', TRUE},
4175                 {"", 0, FALSE},
4176                 {"", 0, FALSE},
4177                 {"", 0, FALSE},
4178                 {"", 0, FALSE},
4179                 {"", 0, FALSE},
4180                 {"", 0, FALSE}
4181         },
4182
4183         {
4184                 {"Open(o)", 'o', TRUE},
4185                 {"Close(c)", 'c', TRUE},
4186                 {"Bash a door(B/f)", 'B', TRUE},
4187                 {"Jam a door(j/S)", 'j', TRUE},
4188                 {"", 0, FALSE},
4189                 {"", 0, FALSE},
4190                 {"", 0, FALSE},
4191                 {"", 0, FALSE},
4192                 {"", 0, FALSE},
4193                 {"", 0, FALSE}
4194         },
4195
4196         {
4197                 {"Full map(M)", 'M', TRUE},
4198                 {"Map(L/W)", 'L', TRUE},
4199                 {"Level feeling(^f)", KTRL('F'), TRUE},
4200                 {"Character status(C)", 'C', TRUE},
4201                 {"Identify symbol(/)", '/', TRUE},
4202                 {"Show prev messages(^p)", KTRL('P'), TRUE},
4203                 {"Current time(^t/')", KTRL('T'), TRUE},
4204                 {"Various informations(~)", '~', TRUE},
4205                 {"Play record menu(|)", '|', TRUE},
4206                 {"", 0, FALSE}
4207         },
4208
4209         {
4210                 {"Set options(=)", '=', TRUE},
4211                 {"Interact with macros(@)", '@', TRUE},
4212                 {"Interact w/ visuals(%)", '%', TRUE},
4213                 {"Interact with colors(&)", '&', TRUE},
4214                 {"Enter a user pref(\")", '\"', TRUE},
4215                 {"Reload auto-pick pref($)", '$', TRUE},
4216                 {"", 0, FALSE},
4217                 {"", 0, FALSE},
4218                 {"", 0, FALSE},
4219                 {"", 0, FALSE}
4220         },
4221
4222         {
4223                 {"Save and quit(^x)", KTRL('X'), TRUE},
4224                 {"Save(^s)", KTRL('S'), TRUE},
4225                 {"Help(obsoleted)(?)", '?', TRUE},
4226                 {"Redraw(^r)", KTRL('R'), TRUE},
4227                 {"Take note(:)", ':', TRUE},
4228                 {"Dump screen dump(()", ')', TRUE},
4229                 {"Load screen dump())", '(', TRUE},
4230                 {"Version info(V)", 'V', TRUE},
4231                 {"Quit(Q)", 'Q', TRUE},
4232                 {"", 0, FALSE}
4233         },
4234 };
4235 #endif
4236
4237 typedef struct
4238 {
4239         concptr name;
4240         byte window;
4241         byte number;
4242         byte jouken;
4243         byte jouken_naiyou;
4244 } special_menu_naiyou;
4245
4246 #define MENU_CLASS 1
4247 #define MENU_WILD 2
4248
4249 #ifdef JP
4250 special_menu_naiyou special_menu_info[] =
4251 {
4252         {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4253         {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4254         {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
4255         {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4256         {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4257         {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4258         {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
4259         {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4260         {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
4261         {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
4262         {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
4263         {"", 0, 0, 0, 0},
4264 };
4265 #else
4266 special_menu_naiyou special_menu_info[] =
4267 {
4268         {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4269         {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4270         {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
4271         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4272         {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4273         {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4274         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
4275         {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4276         {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
4277         {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
4278         {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
4279         {"", 0, 0, 0, 0},
4280 };
4281 #endif
4282
4283 static char inkey_from_menu(void)
4284 {
4285         char cmd;
4286         int basey, basex;
4287         int num = 0, max_num, old_num = 0;
4288         int menu = 0;
4289         bool kisuu;
4290
4291         if (p_ptr->y - panel_row_min > 10) basey = 2;
4292         else basey = 13;
4293         basex = 15;
4294
4295         /* Clear top line */
4296         prt("", 0, 0);
4297
4298         screen_save();
4299
4300         while(1)
4301         {
4302                 int i;
4303                 char sub_cmd;
4304                 concptr menu_name;
4305                 if (!menu) old_num = num;
4306                 put_str("+----------------------------------------------------+", basey, basex);
4307                 put_str("|                                                    |", basey+1, basex);
4308                 put_str("|                                                    |", basey+2, basex);
4309                 put_str("|                                                    |", basey+3, basex);
4310                 put_str("|                                                    |", basey+4, basex);
4311                 put_str("|                                                    |", basey+5, basex);
4312                 put_str("+----------------------------------------------------+", basey+6, basex);
4313
4314                 for(i = 0; i < 10; i++)
4315                 {
4316                         int hoge;
4317                         if (!menu_info[menu][i].cmd) break;
4318                         menu_name = menu_info[menu][i].name;
4319                         for(hoge = 0; ; hoge++)
4320                         {
4321                                 if (!special_menu_info[hoge].name[0]) break;
4322                                 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
4323                                 switch(special_menu_info[hoge].jouken)
4324                                 {
4325                                 case MENU_CLASS:
4326                                         if (p_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4327                                         break;
4328                                 case MENU_WILD:
4329                                         if (!current_floor_ptr->dun_level && !p_ptr->inside_arena && !p_ptr->inside_quest)
4330                                         {
4331                                                 if ((byte)p_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4332                                         }
4333                                         break;
4334                                 default:
4335                                         break;
4336                                 }
4337                         }
4338                         put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
4339                 }
4340                 max_num = i;
4341                 kisuu = max_num % 2;
4342                 put_str(_("》", "> "),basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
4343
4344                 /* Place the cursor on the player */
4345                 move_cursor_relative(p_ptr->y, p_ptr->x);
4346
4347                 sub_cmd = inkey();
4348                 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
4349                 {
4350                         if (menu_info[menu][num].fin)
4351                         {
4352                                 cmd = menu_info[menu][num].cmd;
4353                                 use_menu = TRUE;
4354                                 break;
4355                         }
4356                         else
4357                         {
4358                                 menu = menu_info[menu][num].cmd;
4359                                 num = 0;
4360                                 basey += 2;
4361                                 basex += 8;
4362                         }
4363                 }
4364                 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
4365                 {
4366                         if (!menu)
4367                         {
4368                                 cmd = ESCAPE;
4369                                 break;
4370                         }
4371                         else
4372                         {
4373                                 menu = 0;
4374                                 num = old_num;
4375                                 basey -= 2;
4376                                 basex -= 8;
4377                                 screen_load();
4378                                 screen_save();
4379                         }
4380                 }
4381                 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
4382                 {
4383                         if (kisuu)
4384                         {
4385                                 if (num % 2)
4386                                         num = (num + 2) % (max_num - 1);
4387                                 else
4388                                         num = (num + 2) % (max_num + 1);
4389                         }
4390                         else num = (num + 2) % max_num;
4391                 }
4392                 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
4393                 {
4394                         if (kisuu)
4395                         {
4396                                 if (num % 2)
4397                                         num = (num + max_num - 3) % (max_num - 1);
4398                                 else
4399                                         num = (num + max_num - 1) % (max_num + 1);
4400                         }
4401                         else num = (num + max_num - 2) % max_num;
4402                 }
4403                 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
4404                 {
4405                         if ((num % 2) || (num == max_num - 1))
4406                         {
4407                                 num--;
4408                         }
4409                         else if (num < max_num - 1)
4410                         {
4411                                 num++;
4412                         }
4413                 }
4414         }
4415
4416         screen_load();
4417         if (!inkey_next) inkey_next = "";
4418
4419         return (cmd);
4420 }
4421
4422 /*
4423  * Request a command from the user.
4424  *
4425  * Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
4426  * p_ptr->command_arg.  May modify p_ptr->command_new.
4427  *
4428  * Note that "caret" ("^") is treated specially, and is used to
4429  * allow manual input of control characters.  This can be used
4430  * on many machines to request repeated tunneling (Ctrl-H) and
4431  * on the Macintosh to request "Control-Caret".
4432  *
4433  * Note that "backslash" is treated specially, and is used to bypass any
4434  * keymap entry for the following character.  This is useful for macros.
4435  *
4436  * Note that this command is used both in the dungeon and in
4437  * stores, and must be careful to work in both situations.
4438  *
4439  * Note that "p_ptr->command_new" may not work any more.  
4440  */
4441 void request_command(int shopping)
4442 {
4443         int i;
4444
4445         s16b cmd;
4446         int mode;
4447
4448         concptr act;
4449
4450 #ifdef JP
4451         int caretcmd = 0;
4452 #endif
4453         /* Roguelike */
4454         if (rogue_like_commands)
4455         {
4456                 mode = KEYMAP_MODE_ROGUE;
4457         }
4458
4459         /* Original */
4460         else
4461         {
4462                 mode = KEYMAP_MODE_ORIG;
4463         }
4464
4465
4466         /* No command yet */
4467         command_cmd = 0;
4468
4469         /* No "argument" yet */
4470         command_arg = 0;
4471
4472         /* No "direction" yet */
4473         command_dir = 0;
4474
4475         use_menu = FALSE;
4476
4477
4478         /* Get command */
4479         while (1)
4480         {
4481                 /* Hack -- auto-commands */
4482                 if (command_new)
4483                 {
4484                         msg_erase();
4485
4486                         /* Use auto-command */
4487                         cmd = command_new;
4488
4489                         /* Forget it */
4490                         command_new = 0;
4491                 }
4492
4493                 /* Get a keypress in "command" mode */
4494                 else
4495                 {
4496                         /* Hack -- no flush needed */
4497                         msg_flag = FALSE;
4498                         num_more = 0;
4499
4500                         /* Activate "command mode" */
4501                         inkey_flag = TRUE;
4502
4503                         cmd = inkey();
4504
4505                         if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
4506                             && !keymap_act[mode][(byte)(cmd)])
4507                                 cmd = inkey_from_menu();
4508                 }
4509
4510                 /* Clear top line */
4511                 prt("", 0, 0);
4512
4513
4514                 /* Command Count */
4515                 if (cmd == '0')
4516                 {
4517                         COMMAND_ARG old_arg = command_arg;
4518
4519                         /* Reset */
4520                         command_arg = 0;
4521
4522                         /* Begin the input */
4523                         prt(_("回数: ", "Count: "), 0, 0);
4524
4525                         /* Get a command count */
4526                         while (1)
4527                         {
4528                                 /* Get a new keypress */
4529                                 cmd = inkey();
4530
4531                                 /* Simple editing (delete or backspace) */
4532                                 if ((cmd == 0x7F) || (cmd == KTRL('H')))
4533                                 {
4534                                         /* Delete a digit */
4535                                         command_arg = command_arg / 10;
4536
4537                                         /* Show current count */
4538                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4539                                 }
4540
4541                                 /* Actual numeric data */
4542                                 else if (cmd >= '0' && cmd <= '9')
4543                                 {
4544                                         /* Stop count at 9999 */
4545                                         if (command_arg >= 1000)
4546                                         {
4547                                                 /* Warn */
4548                                                 bell();
4549
4550                                                 /* Limit */
4551                                                 command_arg = 9999;
4552                                         }
4553
4554                                         /* Increase count */
4555                                         else
4556                                         {
4557                                                 /* Incorporate that digit */
4558                                                 command_arg = command_arg * 10 + D2I(cmd);
4559                                         }
4560
4561                                         /* Show current count */
4562                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4563                                 }
4564
4565                                 /* Exit on "unusable" input */
4566                                 else
4567                                 {
4568                                         break;
4569                                 }
4570                         }
4571
4572                         /* Hack -- Handle "zero" */
4573                         if (command_arg == 0)
4574                         {
4575                                 /* Default to 99 */
4576                                 command_arg = 99;
4577
4578                                 /* Show current count */
4579                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4580                         }
4581
4582                         /* Hack -- Handle "old_arg" */
4583                         if (old_arg != 0)
4584                         {
4585                                 /* Restore old_arg */
4586                                 command_arg = old_arg;
4587
4588                                 /* Show current count */
4589                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4590                         }
4591
4592                         /* Hack -- white-space means "enter command now" */
4593                         if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
4594                         {
4595                                 /* Get a real command */
4596                                 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
4597                                 {
4598                                         /* Clear count */
4599                                         command_arg = 0;
4600                                         continue;
4601                                 }
4602                         }
4603                 }
4604
4605
4606                 /* Allow "keymaps" to be bypassed */
4607                 if (cmd == '\\')
4608                 {
4609                         /* Get a real command */
4610                         (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
4611
4612                         /* Hack -- bypass keymaps */
4613                         if (!inkey_next) inkey_next = "";
4614                 }
4615
4616
4617                 /* Allow "control chars" to be entered */
4618                 if (cmd == '^')
4619                 {
4620                         /* Get a new command and controlify it */
4621                         if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4622                 }
4623
4624
4625                 /* Look up applicable keymap */
4626                 act = keymap_act[mode][(byte)(cmd)];
4627
4628                 /* Apply keymap if not inside a keymap already */
4629                 if (act && !inkey_next)
4630                 {
4631                         /* Install the keymap (limited buffer size) */
4632                         (void)strnfmt(request_command_buffer, 256, "%s", act);
4633
4634                         /* Start using the buffer */
4635                         inkey_next = request_command_buffer;
4636                         continue;
4637                 }
4638
4639                 if (!cmd) continue;
4640
4641
4642                 /* Use command */
4643                 command_cmd = (byte)cmd;
4644
4645                 break;
4646         }
4647
4648         /* Hack -- Auto-repeat certain commands */
4649         if (always_repeat && (command_arg <= 0))
4650         {
4651                 /* Hack -- auto repeat certain commands */
4652                 if (my_strchr("TBDoc+", (char)command_cmd))
4653                 {
4654                         /* Repeat 99 times */
4655                         command_arg = 99;
4656                 }
4657         }
4658
4659         /* Shopping */
4660         if (shopping == 1)
4661         {
4662                 /* Convert */
4663                 switch (command_cmd)
4664                 {
4665                         /* Command "p" -> "purchase" (get) */
4666                 case 'p': command_cmd = 'g'; break;
4667
4668                         /* Command "m" -> "purchase" (get) */
4669                 case 'm': command_cmd = 'g'; break;
4670
4671                         /* Command "s" -> "sell" (drop) */
4672                 case 's': command_cmd = 'd'; break;
4673                 }
4674         }
4675
4676 #ifdef JP
4677         for (i = 0; i < 256; i++)
4678         {
4679                 concptr s;
4680                 if ((s = keymap_act[mode][i]) != NULL)
4681                 {
4682                         if (*s == command_cmd && *(s+1) == 0)
4683                         {
4684                                 caretcmd = i;
4685                                 break;
4686                         }
4687                 }
4688         }
4689         if (!caretcmd)
4690                 caretcmd = command_cmd;
4691 #endif
4692
4693         /* Hack -- Scan equipment */
4694         for (i = INVEN_RARM; i < INVEN_TOTAL; i++)
4695         {
4696                 concptr s;
4697
4698                 object_type *o_ptr = &p_ptr->inventory_list[i];
4699                 if (!o_ptr->k_idx) continue;
4700
4701                 /* No inscription */
4702                 if (!o_ptr->inscription) continue;
4703
4704                 /* Obtain the inscription */
4705                 s = quark_str(o_ptr->inscription);
4706
4707                 /* Find a '^' */
4708                 s = my_strchr(s, '^');
4709
4710                 /* Process preventions */
4711                 while (s)
4712                 {
4713                         /* Check the "restriction" character */
4714 #ifdef JP
4715                         if ((s[1] == caretcmd) || (s[1] == '*'))
4716 #else
4717                         if ((s[1] == command_cmd) || (s[1] == '*'))
4718 #endif
4719
4720                         {
4721                                 /* Hack -- Verify command */
4722                                 if (!get_check(_("本当ですか? ", "Are you sure? ")))
4723                                 {
4724                                         /* Hack -- Use space */
4725                                         command_cmd = ' ';
4726                                 }
4727                         }
4728
4729                         /* Find another '^' */
4730                         s = my_strchr(s + 1, '^');
4731                 }
4732         }
4733
4734
4735         /* Hack -- erase the message line. */
4736         prt("", 0, 0);
4737 }
4738
4739
4740
4741 /*
4742  * Check a char for "vowel-hood"
4743  */
4744 bool is_a_vowel(int ch)
4745 {
4746         switch (ch)
4747         {
4748         case 'a':
4749         case 'e':
4750         case 'i':
4751         case 'o':
4752         case 'u':
4753         case 'A':
4754         case 'E':
4755         case 'I':
4756         case 'O':
4757         case 'U':
4758                 return (TRUE);
4759         }
4760
4761         return (FALSE);
4762 }
4763
4764
4765
4766 #if 0
4767
4768 /*
4769  * Replace the first instance of "target" in "buf" with "insert"
4770  * If "insert" is NULL, just remove the first instance of "target"
4771  * In either case, return TRUE if "target" is found.
4772  *
4773  * XXX Could be made more efficient, especially in the
4774  * case where "insert" is smaller than "target".
4775  */
4776 static bool insert_str(char *buf, concptr target, concptr insert)
4777 {
4778         int   i, len;
4779         int                b_len, t_len, i_len;
4780
4781         /* Attempt to find the target (modify "buf") */
4782         buf = my_strstr(buf, target);
4783
4784         /* No target found */
4785         if (!buf) return (FALSE);
4786
4787         /* Be sure we have an insertion string */
4788         if (!insert) insert = "";
4789
4790         /* Extract some lengths */
4791         t_len = strlen(target);
4792         i_len = strlen(insert);
4793         b_len = strlen(buf);
4794
4795         /* How much "movement" do we need? */
4796         len = i_len - t_len;
4797
4798         /* We need less space (for insert) */
4799         if (len < 0)
4800         {
4801                 for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
4802         }
4803
4804         /* We need more space (for insert) */
4805         else if (len > 0)
4806         {
4807                 for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
4808         }
4809
4810         /* If movement occured, we need a new terminator */
4811         if (len) buf[b_len+len] = '\0';
4812
4813         /* Now copy the insertion string */
4814         for (i = 0; i < i_len; ++i) buf[i] = insert[i];
4815
4816         /* Successful operation */
4817         return (TRUE);
4818 }
4819
4820
4821 #endif
4822
4823
4824 /*
4825  * GH
4826  * Called from cmd4.c and a few other places. Just extracts
4827  * a direction from the keymap for ch (the last direction,
4828  * in fact) byte or char here? I'm thinking that keymaps should
4829  * generally only apply to single keys, which makes it no more
4830  * than 128, so a char should suffice... but keymap_act is 256...
4831  */
4832 int get_keymap_dir(char ch)
4833 {
4834         int d = 0;
4835
4836         /* Already a direction? */
4837         if (isdigit(ch))
4838         {
4839                 d = D2I(ch);
4840         }
4841         else
4842         {
4843                 BIT_FLAGS mode;
4844                 concptr act, s;
4845
4846                 /* Roguelike */
4847                 if (rogue_like_commands)
4848                 {
4849                         mode = KEYMAP_MODE_ROGUE;
4850                 }
4851
4852                 /* Original */
4853                 else
4854                 {
4855                         mode = KEYMAP_MODE_ORIG;
4856                 }
4857
4858                 /* Extract the action (if any) */
4859                 act = keymap_act[mode][(byte)(ch)];
4860
4861                 /* Analyze */
4862                 if (act)
4863                 {
4864                         /* Convert to a direction */
4865                         for (s = act; *s; ++s)
4866                         {
4867                                 /* Use any digits in keymap */
4868                                 if (isdigit(*s)) d = D2I(*s);
4869                         }
4870                 }
4871         }
4872         if (d == 5) d = 0;
4873
4874         /* Return direction */
4875         return (d);
4876 }
4877
4878
4879 #define REPEAT_MAX              20
4880
4881 /* Number of chars saved */
4882 static int repeat__cnt = 0;
4883
4884 /* Current index */
4885 static int repeat__idx = 0;
4886
4887 /* Saved "stuff" */
4888 static COMMAND_CODE repeat__key[REPEAT_MAX];
4889
4890
4891 void repeat_push(COMMAND_CODE what)
4892 {
4893         /* Too many keys */
4894         if (repeat__cnt == REPEAT_MAX) return;
4895
4896         /* Push the "stuff" */
4897         repeat__key[repeat__cnt++] = what;
4898
4899         /* Prevents us from pulling keys */
4900         ++repeat__idx;
4901 }
4902
4903
4904 bool repeat_pull(COMMAND_CODE *what)
4905 {
4906         /* All out of keys */
4907         if (repeat__idx == repeat__cnt) return (FALSE);
4908
4909         /* Grab the next key, advance */
4910         *what = repeat__key[repeat__idx++];
4911
4912         /* Success */
4913         return (TRUE);
4914 }
4915
4916 void repeat_check(void)
4917 {
4918         COMMAND_CODE what;
4919
4920         /* Ignore some commands */
4921         if (command_cmd == ESCAPE) return;
4922         if (command_cmd == ' ') return;
4923         if (command_cmd == '\r') return;
4924         if (command_cmd == '\n') return;
4925
4926         /* Repeat Last Command */
4927         if (command_cmd == 'n')
4928         {
4929                 /* Reset */
4930                 repeat__idx = 0;
4931
4932                 /* Get the command */
4933                 if (repeat_pull(&what))
4934                 {
4935                         /* Save the command */
4936                         command_cmd = what;
4937                 }
4938         }
4939
4940         /* Start saving new command */
4941         else
4942         {
4943                 /* Reset */
4944                 repeat__cnt = 0;
4945                 repeat__idx = 0;
4946
4947                 what = command_cmd;
4948
4949                 /* Save this command */
4950                 repeat_push(what);
4951         }
4952 }
4953
4954
4955 #ifdef SORT_R_INFO
4956
4957 /*
4958  * Array size for which InsertionSort
4959  * is used instead of QuickSort
4960  */
4961 #define CUTOFF 4
4962
4963
4964 /*
4965  * Exchange two sort-entries
4966  * (should probably be coded inline
4967  * for speed increase)
4968  */
4969 static void swap(tag_type *a, tag_type *b)
4970 {
4971         tag_type temp;
4972
4973         temp = *a;
4974         *a = *b;
4975         *b = temp;
4976 }
4977
4978
4979 /*
4980  * Insertion-Sort algorithm
4981  * (used by the Quicksort algorithm)
4982  */
4983 static void InsertionSort(tag_type elements[], int number)
4984 {
4985         int j, P;
4986
4987         tag_type tmp;
4988
4989         for (P = 1; P < number; P++)
4990         {
4991                 tmp = elements[P];
4992                 for (j = P; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
4993                         elements[j] = elements[j - 1];
4994                 elements[j] = tmp;
4995         }
4996 }
4997
4998
4999 /*
5000  * Helper function for Quicksort
5001  */
5002 static tag_type median3(tag_type elements[], int left, int right)
5003 {
5004         int center = (left + right) / 2;
5005
5006         if (elements[left].tag > elements[center].tag)
5007                 swap(&elements[left], &elements[center]);
5008         if (elements[left].tag > elements[right].tag)
5009                 swap(&elements[left], &elements[right]);
5010         if (elements[center].tag > elements[right].tag)
5011                 swap(&elements[center], &elements[right]);
5012
5013         swap(&elements[center], &elements[right - 1]);
5014         return (elements[right - 1]);
5015 }
5016
5017
5018 /*
5019  * Quicksort algorithm
5020  *
5021  * The "median of three" pivot selection eliminates
5022  * the bad case of already sorted input.
5023  *
5024  * We use InsertionSort for smaller sub-arrays,
5025  * because it is faster in this case.
5026  *
5027  * For details see: "Data Structures and Algorithm
5028  * Analysis in C" by Mark Allen Weiss.
5029  */
5030 static void quicksort(tag_type elements[], int left, int right)
5031 {
5032         int i, j;
5033         tag_type pivot;
5034
5035         if (left + CUTOFF <= right)
5036         {
5037                 pivot = median3(elements, left, right);
5038
5039                 i = left; j = right -1;
5040
5041                 while (TRUE)
5042                 {
5043                         while (elements[++i].tag < pivot.tag);
5044                         while (elements[--j].tag > pivot.tag);
5045
5046                         if (i < j)
5047                                 swap(&elements[i], &elements[j]);
5048                         else
5049                                 break;
5050                 }
5051
5052                 /* Restore pivot */
5053                 swap(&elements[i], &elements[right - 1]);
5054
5055                 quicksort(elements, left, i - 1);
5056                 quicksort(elements, i + 1, right);
5057         }
5058         else
5059         {
5060                 /* Use InsertionSort on small arrays */
5061                 InsertionSort(elements + left, right - left + 1);
5062         }
5063 }
5064
5065
5066 /*
5067  * Frontend for the sorting algorithm
5068  *
5069  * Sorts an array of tagged pointers
5070  * with <number> elements.
5071  */
5072 void tag_sort(tag_type elements[], int number)
5073 {
5074         quicksort(elements, 0, number - 1);
5075 }
5076
5077 #endif /* SORT_R_INFO */
5078
5079 #ifdef SUPPORT_GAMMA
5080
5081 /* Table of gamma values */
5082 byte gamma_table[256];
5083
5084 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
5085 static s16b gamma_helper[256] =
5086 {
5087 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
5088 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
5089 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
5090 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
5091 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
5092 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
5093 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
5094 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
5095 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
5096 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
5097 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
5098 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
5099 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
5100 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
5101 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
5102 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
5103 };
5104
5105
5106 /* 
5107  * Build the gamma table so that floating point isn't needed.
5108  * 
5109  * Note gamma goes from 0->256.  The old value of 100 is now 128.
5110  */
5111 void build_gamma_table(int gamma)
5112 {
5113         int i, n;
5114         
5115         /*
5116          * value is the current sum.
5117          * diff is the new term to add to the series.
5118          */
5119         long value, diff;
5120         
5121         /* Hack - convergence is bad in these cases. */
5122         gamma_table[0] = 0;
5123         gamma_table[255] = 255;
5124         
5125         for (i = 1; i < 255; i++)
5126         {
5127                 /* 
5128                  * Initialise the Taylor series
5129                  *
5130                  * value and diff have been scaled by 256
5131                  */
5132                 
5133                 n = 1;
5134                 value = 256 * 256;
5135                 diff = ((long)gamma_helper[i]) * (gamma - 256);
5136                 
5137                 while (diff)
5138                 {
5139                         value += diff;
5140                         n++;
5141                         
5142                         
5143                         /*
5144                          * Use the following identiy to calculate the gamma table.
5145                          * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
5146                          *
5147                          * n is the current term number.
5148                          * 
5149                          * The gamma_helper array contains a table of
5150                          * ln(x/256) * 256
5151                          * This is used because a^b = exp(b*ln(a))
5152                          *
5153                          * In this case:
5154                          * a is i / 256
5155                          * b is gamma.
5156                          *
5157                          * Note that everything is scaled by 256 for accuracy,
5158                          * plus another factor of 256 for the final result to
5159                          * be from 0-255.  Thus gamma_helper[] * gamma must be
5160                          * divided by 256*256 each itteration, to get back to
5161                          * the original power series.
5162                          */
5163                         diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
5164                 }
5165                 
5166                 /* 
5167                  * Store the value in the table so that the
5168                  * floating point pow function isn't needed .
5169                  */
5170                 gamma_table[i] = ((long)(value / 256) * i) / 256;
5171         }
5172 }
5173
5174 #endif /* SUPPORT_GAMMA */
5175
5176
5177 /*
5178  * Add a series of keypresses to the "queue".
5179  *
5180  * Return any errors generated by Term_keypress() in doing so, or SUCCESS
5181  * if there are none.
5182  *
5183  * Catch the "out of space" error before anything is printed.
5184  *
5185  * NB: The keys added here will be interpreted by any macros or keymaps.
5186  */
5187 errr type_string(concptr str, uint len)
5188 {
5189         errr err = 0;
5190         concptr s;
5191
5192         term *old = Term;
5193
5194         /* Paranoia - no string. */
5195         if (!str) return -1;
5196
5197         /* Hack - calculate the string length here if none given. */
5198         if (!len) len = strlen(str);
5199
5200         /* Activate the main window, as all pastes go there. */
5201         Term_activate(term_screen);
5202
5203         for (s = str; s < str+len; s++)
5204         {
5205                 /* Catch end of string */
5206                 if (*s == '\0') break;
5207
5208                 err = Term_keypress(*s);
5209
5210                 /* Catch errors */
5211                 if (err) break;
5212         }
5213
5214         /* Activate the original window. */
5215         Term_activate(old);
5216
5217         return err;
5218 }
5219
5220
5221
5222 void roff_to_buf(concptr str, int maxlen, char *tbuf, size_t bufsize)
5223 {
5224         int read_pt = 0;
5225         int write_pt = 0;
5226         int line_len = 0;
5227         int word_punct = 0;
5228         char ch[3];
5229         ch[2] = '\0';
5230
5231         while (str[read_pt])
5232         {
5233 #ifdef JP
5234                 bool kinsoku = FALSE;
5235                 bool kanji;
5236 #endif
5237                 int ch_len = 1;
5238
5239                 /* Prepare one character */
5240                 ch[0] = str[read_pt];
5241                 ch[1] = '\0';
5242 #ifdef JP
5243                 kanji  = iskanji(ch[0]);
5244
5245                 if (kanji)
5246                 {
5247                         ch[1] = str[read_pt+1];
5248                         ch_len = 2;
5249
5250                         if (strcmp(ch, "。") == 0 ||
5251                             strcmp(ch, "、") == 0 ||
5252                             strcmp(ch, "ィ") == 0 ||
5253                             strcmp(ch, "ー") == 0)
5254                                 kinsoku = TRUE;
5255                 }
5256                 else if (!isprint(ch[0]))
5257                         ch[0] = ' ';
5258 #else
5259                 if (!isprint(ch[0]))
5260                         ch[0] = ' ';
5261 #endif
5262
5263                 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
5264                 {
5265                         int word_len;
5266
5267                         /* return to better wrapping point. */
5268                         /* Space character at the end of the line need not to be printed. */
5269                         word_len = read_pt - word_punct;
5270 #ifdef JP
5271                         if (kanji && !kinsoku)
5272                                 /* nothing */ ;
5273                         else
5274 #endif
5275                         if (ch[0] == ' ' || word_len >= line_len/2)
5276                                 read_pt++;
5277                         else
5278                         {
5279                                 read_pt = word_punct;
5280                                 if (str[word_punct] == ' ')
5281                                         read_pt++;
5282                                 write_pt -= word_len;
5283                         }
5284
5285                         tbuf[write_pt++] = '\0';
5286                         line_len = 0;
5287                         word_punct = read_pt;
5288                         continue;
5289                 }
5290                 if (ch[0] == ' ')
5291                         word_punct = read_pt;
5292 #ifdef JP
5293                 if (!kinsoku) word_punct = read_pt;
5294 #endif
5295
5296                 /* Not enough buffer size */
5297                 if ((size_t)(write_pt + 3) >= bufsize) break;
5298
5299                 tbuf[write_pt++] = ch[0];
5300                 line_len++;
5301                 read_pt++;
5302 #ifdef JP
5303                 if (kanji)
5304                 {
5305                         tbuf[write_pt++] = ch[1];
5306                         line_len++;
5307                         read_pt++;
5308                 }
5309 #endif
5310         }
5311         tbuf[write_pt] = '\0';
5312         tbuf[write_pt+1] = '\0';
5313
5314         return;
5315 }
5316
5317
5318 /*
5319  * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
5320  * to 'buf' and NUL-terminates the result.  The 'buf' and 'src' strings may
5321  * not overlap.
5322  *
5323  * my_strcpy() returns strlen(src).  This makes checking for truncation
5324  * easy.  Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5325  *
5326  * This function should be equivalent to the strlcpy() function in BSD.
5327  */
5328 size_t my_strcpy(char *buf, concptr src, size_t bufsize)
5329 {
5330 #ifdef JP
5331
5332         char *d = buf;
5333         concptr s = src;
5334         size_t len = 0;
5335
5336         if (bufsize > 0) {
5337                 /* reserve for NUL termination */
5338                 bufsize--;
5339
5340                 /* Copy as many bytes as will fit */
5341                 while (*s && (len < bufsize))
5342                 {
5343                         if (iskanji(*s))
5344                         {
5345                                 if (len + 1 >= bufsize || !*(s+1)) break;
5346                                 *d++ = *s++;
5347                                 *d++ = *s++;
5348                                 len += 2;
5349                         }
5350                         else
5351                         {
5352                                 *d++ = *s++;
5353                                 len++;
5354                         }
5355                 }
5356                 *d = '\0';
5357         }
5358
5359         while(*s++) len++;
5360
5361         return len;
5362
5363 #else
5364
5365         size_t len = strlen(src);
5366         size_t ret = len;
5367         if (bufsize == 0) return ret;
5368
5369         /* Truncate */
5370         if (len >= bufsize) len = bufsize - 1;
5371
5372         /* Copy the string and terminate it */
5373         (void)memcpy(buf, src, len);
5374         buf[len] = '\0';
5375
5376         /* Return strlen(src) */
5377         return ret;
5378
5379 #endif
5380 }
5381
5382
5383 /*
5384  * The my_strcat() tries to append a string to an existing NUL-terminated string.
5385  * It never writes more characters into the buffer than indicated by 'bufsize' and
5386  * NUL-terminates the buffer.  The 'buf' and 'src' strings may not overlap.
5387  *
5388  * my_strcat() returns strlen(buf) + strlen(src).  This makes checking for
5389  * truncation easy.  Example:
5390  * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5391  *
5392  * This function should be equivalent to the strlcat() function in BSD.
5393  */
5394 size_t my_strcat(char *buf, concptr src, size_t bufsize)
5395 {
5396         size_t dlen = strlen(buf);
5397
5398         /* Is there room left in the buffer? */
5399         if (dlen < bufsize - 1)
5400         {
5401                 /* Append as much as possible  */
5402                 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
5403         }
5404         else
5405         {
5406                 /* Return without appending */
5407                 return (dlen + strlen(src));
5408         }
5409 }
5410
5411
5412 /*
5413  * A copy of ANSI strstr()
5414  *
5415  * my_strstr() can handle Kanji strings correctly.
5416  */
5417 char *my_strstr(concptr haystack, concptr needle)
5418 {
5419         int i;
5420         int l1 = strlen(haystack);
5421         int l2 = strlen(needle);
5422
5423         if (l1 >= l2)
5424         {
5425                 for(i = 0; i <= l1 - l2; i++)
5426                 {
5427                         if(!strncmp(haystack + i, needle, l2))
5428                                 return (char *)haystack + i;
5429
5430 #ifdef JP
5431                         if (iskanji(*(haystack + i))) i++;
5432 #endif
5433                 }
5434         }
5435
5436         return NULL;
5437 }
5438
5439
5440 /*
5441  * A copy of ANSI strchr()
5442  *
5443  * my_strchr() can handle Kanji strings correctly.
5444  */
5445 char *my_strchr(concptr ptr, char ch)
5446 {
5447         for ( ; *ptr != '\0'; ptr++)
5448         {
5449                 if (*ptr == ch) return (char *)ptr;
5450
5451 #ifdef JP
5452                 if (iskanji(*ptr)) ptr++;
5453 #endif
5454         }
5455
5456         return NULL;
5457 }
5458
5459
5460 /*
5461  * Convert string to lower case
5462  */
5463 void str_tolower(char *str)
5464 {
5465         /* Force to be lower case string */
5466         for (; *str; str++)
5467         {
5468 #ifdef JP
5469                 if (iskanji(*str))
5470                 {
5471                         str++;
5472                         continue;
5473                 }
5474 #endif
5475                 *str = (char)tolower(*str);
5476         }
5477 }
5478
5479
5480 /*
5481  * Get a keypress from the user.
5482  * And interpret special keys as internal code.
5483  *
5484  * This function is a Mega-Hack and depend on pref-xxx.prf's.
5485  * Currently works on Linux(UNIX), Windows, and Macintosh only.
5486  */
5487 int inkey_special(bool numpad_cursor)
5488 {
5489         static const struct {
5490                 concptr keyname;
5491                 int keyflag;
5492         } modifier_key_list[] = {
5493                 {"shift-", SKEY_MOD_SHIFT},
5494                 {"control-", SKEY_MOD_CONTROL},
5495                 {NULL, 0},
5496         };
5497
5498         static const struct {
5499                 bool numpad;
5500                 concptr keyname;
5501                 int keycode;
5502         } special_key_list[] = {
5503                 {FALSE, "Down]", SKEY_DOWN},
5504                 {FALSE, "Left]", SKEY_LEFT},
5505                 {FALSE, "Right]", SKEY_RIGHT},
5506                 {FALSE, "Up]", SKEY_UP},
5507                 {FALSE, "Page_Up]", SKEY_PGUP},
5508                 {FALSE, "Page_Down]", SKEY_PGDOWN},
5509                 {FALSE, "Home]", SKEY_TOP},
5510                 {FALSE, "End]", SKEY_BOTTOM},
5511                 {TRUE, "KP_Down]", SKEY_DOWN},
5512                 {TRUE, "KP_Left]", SKEY_LEFT},
5513                 {TRUE, "KP_Right]", SKEY_RIGHT},
5514                 {TRUE, "KP_Up]", SKEY_UP},
5515                 {TRUE, "KP_Page_Up]", SKEY_PGUP},
5516                 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
5517                 {TRUE, "KP_Home]", SKEY_TOP},
5518                 {TRUE, "KP_End]", SKEY_BOTTOM},
5519                 {TRUE, "KP_2]", SKEY_DOWN},
5520                 {TRUE, "KP_4]", SKEY_LEFT},
5521                 {TRUE, "KP_6]", SKEY_RIGHT},
5522                 {TRUE, "KP_8]", SKEY_UP},
5523                 {TRUE, "KP_9]", SKEY_PGUP},
5524                 {TRUE, "KP_3]", SKEY_PGDOWN},
5525                 {TRUE, "KP_7]", SKEY_TOP},
5526                 {TRUE, "KP_1]", SKEY_BOTTOM},
5527                 {FALSE, NULL, 0},
5528         };
5529
5530         static const struct {
5531                 concptr keyname;
5532                 int keycode;
5533         } gcu_special_key_list[] = {
5534                 {"A", SKEY_UP},
5535                 {"B", SKEY_DOWN},
5536                 {"C", SKEY_RIGHT},
5537                 {"D", SKEY_LEFT},
5538                 {"1~", SKEY_TOP},
5539                 {"4~", SKEY_BOTTOM},
5540                 {"5~", SKEY_PGUP},
5541                 {"6~", SKEY_PGDOWN},
5542                 {NULL, 0},
5543         };
5544
5545         char buf[1024];
5546         concptr str = buf;
5547         char key;
5548         int skey = 0;
5549         int modifier = 0;
5550         int i;
5551         size_t trig_len;
5552
5553         /*
5554          * Forget macro trigger ----
5555          * It's important if we are already expanding macro action
5556          */
5557         inkey_macro_trigger_string[0] = '\0';
5558
5559         /* Get a keypress */
5560         key = inkey();
5561
5562         /* Examine trigger string */
5563         trig_len = strlen(inkey_macro_trigger_string);
5564
5565         /* Already known that no special key */
5566         if (!trig_len) return (int)((unsigned char)key);
5567
5568         /*
5569          * Hack -- Ignore macro defined on ASCII characters.
5570          */
5571         if (trig_len == 1 && parse_macro)
5572         {
5573                 char c = inkey_macro_trigger_string[0];
5574
5575                 /* Cancel macro action on the queue */
5576                 forget_macro_action();
5577
5578                 /* Return the originaly pressed key */
5579                 return (int)((unsigned char)c);
5580         }
5581
5582         /* Convert the trigger */
5583         ascii_to_text(buf, inkey_macro_trigger_string);
5584
5585         /* Check the prefix "\[" */
5586         if (prefix(str, "\\["))
5587         {
5588                 /* Skip "\[" */
5589                 str += 2;
5590
5591                 /* Examine modifier keys */
5592                 while (TRUE)
5593                 {
5594                         for (i = 0; modifier_key_list[i].keyname; i++)
5595                         {
5596                                 if (prefix(str, modifier_key_list[i].keyname))
5597                                 {
5598                                         /* Get modifier key flag */
5599                                         str += strlen(modifier_key_list[i].keyname);
5600                                         modifier |= modifier_key_list[i].keyflag;
5601                                 }
5602                         }
5603
5604                         /* No more modifier key found */
5605                         if (!modifier_key_list[i].keyname) break;
5606                 }
5607
5608                 /* numpad_as_cursorkey option force numpad keys to input numbers */
5609                 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
5610
5611                 /* Get a special key code */
5612                 for (i = 0; special_key_list[i].keyname; i++)
5613                 {
5614                         if ((!special_key_list[i].numpad || numpad_cursor) &&
5615                             streq(str, special_key_list[i].keyname))
5616                         {
5617                                 skey = special_key_list[i].keycode;
5618                                 break;
5619                         }
5620                 }
5621
5622                 /* A special key found */
5623                 if (skey)
5624                 {
5625                         /* Cancel macro action on the queue */
5626                         forget_macro_action();
5627
5628                         /* Return special key code and modifier flags */
5629                         return (skey | modifier);
5630                 }
5631         }
5632
5633         if (prefix(str, "\\e["))
5634         {
5635                 str += 3;
5636
5637                 for (i = 0; gcu_special_key_list[i].keyname; i++)
5638                 {
5639                         if (streq(str, gcu_special_key_list[i].keyname))
5640                         {
5641                                 return gcu_special_key_list[i].keycode;
5642                         }
5643                 }
5644         }
5645
5646         /* No special key found? */
5647
5648         /* Don't bother with this trigger no more */
5649         inkey_macro_trigger_string[0] = '\0';
5650
5651         /* Return normal keycode */
5652         return (int)((unsigned char)key);
5653 }
5654