aboutsummaryrefslogtreecommitdiff
path: root/iconv
ModeNameSize
-rw-r--r--Makefile1480logplain
-rw-r--r--Versions138logplain
-rw-r--r--gconv.c2256logplain
-rw-r--r--gconv.h3758logplain
-rw-r--r--gconv_builtin.c2569logplain
-rw-r--r--gconv_builtin.h3580logplain
-rw-r--r--gconv_close.c1666logplain
-rw-r--r--gconv_conf.c15697logplain
-rw-r--r--gconv_db.c21469logplain
-rw-r--r--gconv_dl.c6270logplain
-rw-r--r--gconv_int.h5809logplain
-rw-r--r--gconv_open.c3245logplain
-rw-r--r--gconv_simple.c19462logplain
-rw-r--r--iconv.c2574logplain
-rw-r--r--iconv.h1806logplain
-rw-r--r--iconv_close.c1256logplain
-rw-r--r--iconv_open.c2606logplain
-rw-r--r--iconv_prog.c14491logplain
-rw-r--r--loop.c7941logplain
-rw-r--r--skeleton.c10714logplain
href='#n118'>118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
/* History.c -- standalone history library */

/* Copyright (C) 1989 Free Software Foundation, Inc.

   This file contains the GNU History Library (the Library), a set of
   routines for managing the text of previously typed lines.

   The Library is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 1, or (at your option)
   any later version.

   The Library is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   The GNU General Public License is often shipped with GNU software, and
   is generally kept in a file called COPYING or LICENSE.  If you do not
   have a copy of the license, write to the Free Software Foundation,
   675 Mass Ave, Cambridge, MA 02139, USA. */

/* The goal is to make the implementation transparent, so that you
   don't have to know what data types are used, just what functions
   you can call.  I think I have done that. */

/* Remove these declarations when we have a complete libgnu.a. */
#if !defined (STATIC_MALLOC)
extern char *xmalloc (), *xrealloc ();
#else
static char *xmalloc (), *xrealloc ();
#endif

#include "sysdep.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>

#if defined (__GNUC__)
#  define alloca __builtin_alloca
#else
#  if defined (sparc) || defined (HAVE_ALLOCA_H)
#    include <alloca.h>
#  endif /* sparc || HAVE_ALLOCA_H */
#endif /* !__GNU_C__ */

#include "history.h"

#ifndef savestring
#define savestring(x) (char *)strcpy (xmalloc (1 + strlen (x)), (x))
#endif

#ifndef whitespace
#define whitespace(c) (((c) == ' ') || ((c) == '\t'))
#endif

#ifndef digit
#define digit(c)  ((c) >= '0' && (c) <= '9')
#endif

#ifndef member
#define member(c, s) ((c) ? index ((s), (c)) : 0)
#endif

/* **************************************************************** */
/*								    */
/*			History Functions			    */
/*								    */
/* **************************************************************** */

/* An array of HIST_ENTRY.  This is where we store the history. */
static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;

/* Non-zero means that we have enforced a limit on the amount of
   history that we save. */
int history_stifled = 0;

/* If HISTORY_STIFLED is non-zero, then this is the maximum number of
   entries to remember. */
int max_input_history;

/* The current location of the interactive history pointer.  Just makes
   life easier for outside callers. */
static int history_offset = 0;

/* The number of strings currently stored in the input_history list. */
int history_length = 0;

/* The current number of slots allocated to the input_history. */
static int history_size = 0;

/* The number of slots to increase the_history by. */
#define DEFAULT_HISTORY_GROW_SIZE 50

/* The character that represents the start of a history expansion
   request.  This is usually `!'. */
char history_expansion_char = '!';

/* The character that invokes word substitution if found at the start of
   a line.  This is usually `^'. */
char history_subst_char = '^';

/* During tokenization, if this character is seen as the first character
   of a word, then it, and all subsequent characters upto a newline are
   ignored.  For a Bourne shell, this should be '#'.  Bash special cases
   the interactive comment character to not be a comment delimiter. */
char history_comment_char = '\0';

/* The list of characters which inhibit the expansion of text if found
   immediately following history_expansion_char. */
char *history_no_expand_chars = " \t\n\r=";

/* The logical `base' of the history array.  It defaults to 1. */
int history_base = 1;

/* Begin a session in which the history functions might be used.  This
   initializes interactive variables. */
void
using_history ()
{
  history_offset = history_length;
}

/* Return the number of bytes that the primary history entries are using.
   This just adds up the lengths of the_history->lines. */
int
history_total_bytes ()
{
  register int i, result;

  result = 0;

  for (i = 0; the_history && the_history[i]; i++)
    result += strlen (the_history[i]->line);

  return (result);
}

/* Place STRING at the end of the history list.  The data field
   is  set to NULL. */
void
add_history (string)
     char *string;
{
  HIST_ENTRY *temp;

  if (history_stifled && (history_length == max_input_history))
    {
      register int i;

      /* If the history is stifled, and history_length is zero,
	 and it equals max_input_history, we don't save items. */
      if (!history_length)
	return;

      /* If there is something in the slot, then remove it. */
      if (the_history[0])
	{
	  free (the_history[0]->line);
	  free (the_history[0]);
	}

      for (i = 0; i < history_length; i++)
	the_history[i] = the_history[i + 1];

      history_base++;

    }
  else
    {
      if (!history_size)
	{
	  the_history = (HIST_ENTRY **)
	    xmalloc ((history_size = DEFAULT_HISTORY_GROW_SIZE)
		     * sizeof (HIST_ENTRY *));
	  history_length = 1;

	}
      else
	{
	  if (history_length == (history_size - 1))
	    {
	      the_history = (HIST_ENTRY **)
		xrealloc (the_history,
			  ((history_size += DEFAULT_HISTORY_GROW_SIZE)
			   * sizeof (HIST_ENTRY *)));
	  }
	  history_length++;
	}
    }

  temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  temp->line = savestring (string);
  temp->data = (char *)NULL;

  the_history[history_length] = (HIST_ENTRY *)NULL;
  the_history[history_length - 1] = temp;
}

/* Make the history entry at WHICH have LINE and DATA.  This returns
   the old entry so you can dispose of the data.  In the case of an
   invalid WHICH, a NULL pointer is returned. */
HIST_ENTRY *
replace_history_entry (which, line, data)
     int which;
     char *line;
     char *data;
{
  HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  HIST_ENTRY *old_value;

  if (which >= history_length)
    return ((HIST_ENTRY *)NULL);

  old_value = the_history[which];

  temp->line = savestring (line);
  temp->data = data;
  the_history[which] = temp;

  return (old_value);
}

/* Returns the magic number which says what history element we are
   looking at now.  In this implementation, it returns history_offset. */
int
where_history ()
{
  return (history_offset);
}

/* Search the history for STRING, starting at history_offset.
   If DIRECTION < 0, then the search is through previous entries, else
   through subsequent.  If ANCHORED is non-zero, the string must
   appear at the beginning of a history line, otherwise, the string
   may appear anywhere in the line.  If the string is found, then
   current_history () is the history entry, and the value of this
   function is the offset in the line of that history entry that the
   string was found in.  Otherwise, nothing is changed, and a -1 is
   returned. */

#define ANCHORED_SEARCH 1
#define NON_ANCHORED_SEARCH 0

static int
history_search_internal (string, direction, anchored)
     char *string;
     int direction, anchored;
{
  register int i = history_offset;
  register int reverse = (direction < 0);
  register char *line;
  register int index;
  int string_len = strlen (string);

  /* Take care of trivial cases first. */

  if (!history_length || ((i == history_length) && !reverse))
    return (-1);

  if (reverse && (i == history_length))
    i--;

  while (1)
    {
      /* Search each line in the history list for STRING. */

      /* At limit for direction? */
      if ((reverse && i < 0) ||
	  (!reverse && i == history_length))
	return (-1);

      line = the_history[i]->line;
      index = strlen (line);

      /* If STRING is longer than line, no match. */
      if (string_len > index)
	goto next_line;

      /* Handle anchored searches first. */
      if (anchored == ANCHORED_SEARCH)
	{
	  if (strncmp (string, line, string_len) == 0)
	    {
	      history_offset = i;
	      return (0);
	    }

	  goto next_line;
	}

      /* Do substring search. */
      if (reverse)
	{
	  index -= string_len;

	  while (index >= 0)
	    {
	      if (strncmp (string, line + index, string_len) == 0)
		{
		  history_offset = i;
		  return (index);
		}
	      index--;
	    }
	}
      else
	{
	  register int limit = index - string_len + 1;
	  index = 0;

	  while (index < limit)
	    {
	      if (strncmp (string, line + index, string_len) == 0)
		{
		  history_offset = i;
		  return (index);
		}
	      index++;
	    }
	}
    next_line:
      if (reverse)
	i--;
      else
	i++;
    }
}

/* Do a non-anchored search for STRING through the history in DIRECTION. */
int
history_search (string, direction)
     char *string;
     int direction;
{
  return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
}

/* Do an anchored search for string through the history in DIRECTION. */
int
history_search_prefix (string, direction)
     char *string;
     int direction;
{
  return (history_search_internal (string, direction, ANCHORED_SEARCH));
}

/* Remove history element WHICH from the history.  The removed
   element is returned to you so you can free the line, data,
   and containing structure. */
HIST_ENTRY *
remove_history (which)
     int which;
{
  HIST_ENTRY *return_value;

  if (which >= history_length || !history_length)
    return_value = (HIST_ENTRY *)NULL;
  else
    {
      register int i;
      return_value = the_history[which];

      for (i = which; i < history_length; i++)
	the_history[i] = the_history[i + 1];

      history_length--;
    }

  return (return_value);
}

/* Stifle the history list, remembering only MAX number of lines. */
void
stifle_history (max)
     int max;
{
  if (history_length > max)
    {
      register int i, j;

      /* This loses because we cannot free the data. */
      for (i = 0; i < (history_length - max); i++)
	{
	  free (the_history[i]->line);
	  free (the_history[i]);
	}
      history_base = i;
      for (j = 0, i = history_length - max; j < max; i++, j++)
	the_history[j] = the_history[i];
      the_history[j] = (HIST_ENTRY *)NULL;
      history_length = j;
    }
  history_stifled = 1;
  max_input_history = max;
}

/* Stop stifling the history.  This returns the previous amount the history
 was stifled by.  The value is positive if the history was stifled, negative
 if it wasn't. */
int
unstifle_history ()
{
  int result = max_input_history;
  if (history_stifled)
    {
      result = - result;
      history_stifled = 0;
    }
  return (result);
}

/* Return the string that should be used in the place of this
   filename.  This only matters when you don't specify the
   filename to read_history (), or write_history (). */
static char *
history_filename (filename)
     char *filename;
{
  char *return_val = filename ? savestring (filename) : (char *)NULL;

  if (!return_val)
    {
      char *home = (char *)getenv ("HOME");
      if (!home) home = ".";
      return_val = (char *)xmalloc (2 + strlen (home) + strlen (".history"));
      sprintf (return_val, "%s/.history", home);
    }
  return (return_val);
}

/* Add the contents of FILENAME to the history list, a line at a time.
   If FILENAME is NULL, then read from ~/.history.  Returns 0 if
   successful, or errno if not. */
int
read_history (filename)
     char *filename;
{
  return (read_history_range (filename, 0, -1));
}

/* Read a range of lines from FILENAME, adding them to the history list.
   Start reading at the FROM'th line and end at the TO'th.  If FROM
   is zero, start at the beginning.  If TO is less than FROM, read
   until the end of the file.  If FILENAME is NULL, then read from
   ~/.history.  Returns 0 if successful, or errno if not. */
int
read_history_range (filename, from, to)
     char *filename;
     int from, to;
{
  register int line_start, line_end;
  char *input, *buffer = (char *)NULL;
  int file, current_line;
  struct stat finfo;
  extern int errno;

  input = history_filename (filename);
  file = open (input, O_RDONLY, 0666);

  if ((file < 0) ||
      (stat (input, &finfo) == -1))
    goto error_and_exit;

  buffer = (char *)xmalloc (finfo.st_size + 1);

  if (read (file, buffer, finfo.st_size) != finfo.st_size)
  error_and_exit:
    {
      if (file >= 0)
	close (file);

      if (buffer)
	free (buffer);

      return (errno);
    }

  close (file);

  /* Set TO to larger than end of file if negative. */
  if (to < 0)
    to = finfo.st_size;

  /* Start at beginning of file, work to end. */
  line_start = line_end = current_line = 0;

  /* Skip lines until we are at FROM. */
  while (line_start < finfo.st_size && current_line < from)
    {
      for (line_end = line_start; line_end < finfo.st_size; line_end++)
	if (buffer[line_end] == '\n')
	  {
	    current_line++;
	    line_start = line_end + 1;
	    if (current_line == from)
	      break;
	  }
    }

  /* If there are lines left to gobble, then gobble them now. */
  for (line_end = line_start; line_end < finfo.st_size; line_end++)
    if (buffer[line_end] == '\n')
      {
	buffer[line_end] = '\0';

	if (buffer[line_start])
	  add_history (buffer + line_start);

	current_line++;

	if (current_line >= to)
	  break;

	line_start = line_end + 1;
      }
  return (0);
}

/* Truncate the history file FNAME, leaving only LINES trailing lines.
   If FNAME is NULL, then use ~/.history. */
history_truncate_file (fname, lines)
     char *fname;
     register int lines;
{
  register int i;
  int file;
  char *buffer = (char *)NULL, *filename;
  struct stat finfo;

  filename = history_filename (fname);
  if (stat (filename, &finfo) == -1)
    goto truncate_exit;

  file = open (filename, O_RDONLY, 0666);

  if (file == -1)
    goto truncate_exit;

  buffer = (char *)xmalloc (finfo.st_size + 1);
  read (file, buffer, finfo.st_size);
  close (file);

  /* Count backwards from the end of buffer until we have passed
     LINES lines. */
  for (i = finfo.st_size; lines && i; i--)
    {
      if (buffer[i] == '\n')
	lines--;
    }

  /* If there are fewer lines in the file than we want to truncate to,
     then we are all done. */
  if (!i)
    goto truncate_exit;

  /* Otherwise, write from the start of this line until the end of the
     buffer. */
  for (--i; i; i--)
    if (buffer[i] == '\n')
      {
	i++;
	break;
      }

  file = open (filename, O_WRONLY | O_TRUNC | O_CREAT, 0666);
  if (file == -1)
    goto truncate_exit;

  write (file, buffer + i, finfo.st_size - i);
  close (file);

 truncate_exit:
  if (buffer)
    free (buffer);

  free (filename);
}

#define HISTORY_APPEND 0
#define HISTORY_OVERWRITE 1

/* Workhorse function for writing history.  Writes NELEMENT entries
   from the history list to FILENAME.  OVERWRITE is non-zero if you
   wish to replace FILENAME with the entries. */
static int
history_do_write (filename, nelements, overwrite)
     char *filename;
     int nelements, overwrite;
{
  extern int errno;
  register int i;
  char *output = history_filename (filename);
  int file, mode;
  char cr = '\n';

  if (overwrite)
    mode = O_WRONLY | O_CREAT | O_TRUNC;
  else
    mode = O_WRONLY | O_APPEND;

  if ((file = open (output, mode, 0666)) == -1)
    return (errno);

  if (nelements > history_length)
    nelements = history_length;

  for (i = history_length - nelements; i < history_length; i++)
    {
      if (write (file, the_history[i]->line, strlen (the_history[i]->line)) < 0)
	break;
      if (write (file, &cr, 1) < 0)
	break;
    }

  close (file);
  return (0);
}
  
/* Append NELEMENT entries to FILENAME.  The entries appended are from
   the end of the list minus NELEMENTs up to the end of the list. */
int
append_history (nelements, filename)
     int nelements;
     char *filename;
{
  return (history_do_write (filename, nelements, HISTORY_APPEND));
}

/* Overwrite FILENAME with the current history.  If FILENAME is NULL,
   then write the history list to ~/.history.  Values returned
   are as in read_history ().*/
int
write_history (filename)
     char *filename;
{
  return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
}

/* Return the history entry at the current position, as determined by
   history_offset.  If there is no entry there, return a NULL pointer. */
HIST_ENTRY *
current_history ()
{
  if ((history_offset == history_length) || !the_history)
    return ((HIST_ENTRY *)NULL);
  else
    return (the_history[history_offset]);
}

/* Back up history_offset to the previous history entry, and return
   a pointer to that entry.  If there is no previous entry then return
   a NULL pointer. */
HIST_ENTRY *
previous_history ()
{
  if (!history_offset)
    return ((HIST_ENTRY *)NULL);
  else
    return (the_history[--history_offset]);
}

/* Move history_offset forward to the next history entry, and return
   a pointer to that entry.  If there is no next entry then return a
   NULL pointer. */
HIST_ENTRY *
next_history ()
{
  if (history_offset == history_length)
    return ((HIST_ENTRY *)NULL);
  else
    return (the_history[++history_offset]);
}

/* Return the current history array.  The caller has to be carefull, since this
   is the actual array of data, and could be bashed or made corrupt easily.
   The array is terminated with a NULL pointer. */
HIST_ENTRY **
history_list ()
{
  return (the_history);
}

/* Return the history entry which is logically at OFFSET in the history array.
   OFFSET is relative to history_base. */
HIST_ENTRY *
history_get (offset)
     int offset;
{
  int index = offset - history_base;

  if (index >= history_length ||
      index < 0 ||
      !the_history)
    return ((HIST_ENTRY *)NULL);
  return (the_history[index]);
}

/* Search for STRING in the history list.  DIR is < 0 for searching
   backwards.  POS is an absolute index into the history list at
   which point to begin searching. */
int
history_search_pos (string, dir, pos)
     char *string;
     int dir, pos;
{
  int ret, old = where_history ();
  history_set_pos (pos);
  if (history_search (string, dir) == -1)
    {
      history_set_pos (old);
      return (-1);
    }
  ret = where_history ();
  history_set_pos (old);
  return ret;
}

/* Make the current history item be the one at POS, an absolute index.
   Returns zero if POS is out of range, else non-zero. */
int
history_set_pos (pos)
     int pos;
{
  if (pos > history_length || pos < 0 || !the_history)
    return (0);
  history_offset = pos;
  return (1);
}
 

/* **************************************************************** */
/*								    */
/*			History Expansion			    */
/*								    */
/* **************************************************************** */

/* Hairy history expansion on text, not tokens.  This is of general
   use, and thus belongs in this library. */

/* The last string searched for in a !?string? search. */
static char *search_string = (char *)NULL;

/* Return the event specified at TEXT + OFFSET modifying OFFSET to
   point to after the event specifier.  Just a pointer to the history
   line is returned; NULL is returned in the event of a bad specifier.
   You pass STRING with *INDEX equal to the history_expansion_char that
   begins this specification.
   DELIMITING_QUOTE is a character that is allowed to end the string
   specification for what to search for in addition to the normal
   characters `:', ` ', `\t', `\n', and sometimes `?'.
   So you might call this function like:
   line = get_history_event ("!echo:p", &index, 0);  */
char *
get_history_event (string, caller_index, delimiting_quote)
     char *string;
     int *caller_index;
     int delimiting_quote;
{
  register int i = *caller_index;
  int which, sign = 1;
  HIST_ENTRY *entry;

  /* The event can be specified in a number of ways.

     !!   the previous command
     !n   command line N
     !-n  current command-line minus N
     !str the most recent command starting with STR
     !?str[?]
	  the most recent command containing STR

     All values N are determined via HISTORY_BASE. */

  if (string[i] != history_expansion_char)
    return ((char *)NULL);

  /* Move on to the specification. */
  i++;

  /* Handle !! case. */
  if (string[i] == history_expansion_char)
    {
      i++;
      which = history_base + (history_length - 1);
      *caller_index = i;
      goto get_which;
    }

  /* Hack case of numeric line specification. */
 read_which:
  if (string[i] == '-')
    {
      sign = -1;
      i++;
    }

  if (digit (string[i]))
    {
      int start = i;

      /* Get the extent of the digits. */
      for (; digit (string[i]); i++);

      /* Get the digit value. */
      sscanf (string + start, "%d", &which);

      *caller_index = i;

      if (sign < 0)
	which = (history_length + history_base) - which;

    get_which:
      if (entry = history_get (which))
	return (entry->line);

      return ((char *)NULL);
    }

  /* This must be something to search for.  If the spec begins with
     a '?', then the string may be anywhere on the line.  Otherwise,
     the string must be found at the start of a line. */
  {
    int index;
    char *temp;
    int substring_okay = 0;

    if (string[i] == '?')
      {
	substring_okay++;
	i++;
      }

    for (index = i; string[i]; i++)
      if (whitespace (string[i]) ||
	  string[i] == '\n' ||
	  string[i] == ':' ||
	  (substring_okay && string[i] == '?') ||
	  string[i] == delimiting_quote)
	break;

    temp = (char *)alloca (1 + (i - index));
    strncpy (temp, &string[index], (i - index));
    temp[i - index] = '\0';

    if (string[i] == '?')
      i++;

    *caller_index = i;

  search_again:

    index = history_search_internal
      (temp, -1, substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH);

    if (index < 0)
    search_lost:
      {
	history_offset = history_length;
	return ((char *)NULL);
      }

    if (index == 0)
      {
      search_won:
	entry = current_history ();
	history_offset = history_length;
	
	/* If this was a substring search, then remember the string that
	   we matched for word substitution. */
	if (substring_okay)
	  {
	    if (search_string)
	      free (search_string);
	    search_string = savestring (temp);
	  }

	return (entry->line);
      }

    if (history_offset)
      history_offset--;
    else
      goto search_lost;
    
    goto search_again;
  }
}

/* Expand the string STRING, placing the result into OUTPUT, a pointer
   to a string.  Returns:

   0) If no expansions took place (or, if the only change in
      the text was the de-slashifying of the history expansion
      character)
   1) If expansions did take place
  -1) If there was an error in expansion.

  If an error ocurred in expansion, then OUTPUT contains a descriptive
  error message. */
int
history_expand (string, output)
     char *string;
     char **output;
{
  register int j, l = strlen (string);
  int i, word_spec_error = 0;
  int cc, modified = 0;
  char *word_spec, *event;
  int starting_index, only_printing = 0, substitute_globally = 0;

  char *get_history_word_specifier (), *rindex ();

  /* The output string, and its length. */
  int len = 0;
  char *result = (char *)NULL;

  /* Used in add_string; */
  char *temp, tt[2], tbl[3];

  /* Prepare the buffer for printing error messages. */
  result = (char *)xmalloc (len = 255);

  result[0] = tt[1] = tbl[2] = '\0';
  tbl[0] = '\\';
  tbl[1] = history_expansion_char;

  /* Grovel the string.  Only backslash can quote the history escape
     character.  We also handle arg specifiers. */

  /* Before we grovel forever, see if the history_expansion_char appears
     anywhere within the text. */

  /* The quick substitution character is a history expansion all right.  That
     is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
     that is the substitution that we do. */
  if (string[0] == history_subst_char)
    {
      char *format_string = (char *)alloca (10 + strlen (string));

      sprintf (format_string, "%c%c:s%s",
	       history_expansion_char, history_expansion_char,
	       string);
      string = format_string;
      l += 4;
      goto grovel;
    }

  /* If not quick substitution, still maybe have to do expansion. */

  /* `!' followed by one of the characters in history_no_expand_chars
     is NOT an expansion. */
  for (i = 0; string[i]; i++)
    if (string[i] == history_expansion_char)
      if (!string[i + 1] || member (string[i + 1], history_no_expand_chars))
	continue;
      else
	goto grovel;

  free (result);
  *output = savestring (string);
  return (0);

 grovel:

  for (i = j = 0; i < l; i++)
    {
      int tchar = string[i];
      if (tchar == history_expansion_char)
	tchar = -3;

      switch (tchar)
	{
	case '\\':
	  if (string[i + 1] == history_expansion_char)
	    {
	      i++;
	      temp = tbl;
	      goto do_add;
	    }
	  else
	    goto add_char;

	  /* case history_expansion_char: */
	case -3:
	  starting_index = i + 1;
	  cc = string[i + 1];

	  /* If the history_expansion_char is followed by one of the
	     characters in history_no_expand_chars, then it is not a
	     candidate for expansion of any kind. */
	  if (member (cc, history_no_expand_chars))
	    goto add_char;

	  /* There is something that is listed as a `word specifier' in csh
	     documentation which means `the expanded text to this point'.
	     That is not a word specifier, it is an event specifier. */

	  if (cc == '#')
	    goto hack_pound_sign;

	  /* If it is followed by something that starts a word specifier,
	     then !! is implied as the event specifier. */

	  if (member (cc, ":$*%^"))
	    {
	      char fake_s[3];
	      int fake_i = 0;
	      i++;
	      fake_s[0] = fake_s[1] = history_expansion_char;
	      fake_s[2] = '\0';
	      event = get_history_event (fake_s, &fake_i, 0);
	    }
	  else
	    {
	      int quoted_search_delimiter = 0;

	      /* If the character before this `!' is a double or single
		 quote, then this expansion takes place inside of the
		 quoted string.  If we have to search for some text ("!foo"),
		 allow the delimiter to end the search string. */
	      if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
		quoted_search_delimiter = string[i - 1];

	      event = get_history_event (string, &i, quoted_search_delimiter);
	    }
	  
	  if (!event)
	  event_not_found:
	    {
	    int l = 1 + (i - starting_index);

	    temp = (char *)alloca (1 + l);
	    strncpy (temp, string + starting_index, l);
	    temp[l - 1] = 0;
	    sprintf (result, "%s: %s.", temp,
		     word_spec_error ? "Bad word specifier" : "Event not found");
	  error_exit:
	    *output = result;
	    return (-1);
	  }

	  /* If a word specifier is found, then do what that requires. */
	  starting_index = i;

	  word_spec = get_history_word_specifier (string, event, &i);

	  /* There is no such thing as a `malformed word specifier'.  However,
	     it is possible for a specifier that has no match.  In that case,
	     we complain. */
	  if (word_spec == (char *)-1)
	  bad_word_spec:
	  {
	    word_spec_error++;
	    goto event_not_found;
	  }

	  /* If no word specifier, than the thing of interest was the event. */
	  if (!word_spec)
	    temp = event;
	  else
	    {
	      temp = (char *)alloca (1 + strlen (word_spec));
	      strcpy (temp, word_spec);
	      free (word_spec);
	    }

	  /* Perhaps there are other modifiers involved.  Do what they say. */

	hack_specials:

	  if (string[i] == ':')
	    {
	      char *tstr;

	      switch (string[i + 1])
		{
		  /* :p means make this the last executed line.  So we
		     return an error state after adding this line to the
		     history. */
		case 'p':
		  only_printing++;
		  goto next_special;

		  /* :t discards all but the last part of the pathname. */
		case 't':
		  tstr = rindex (temp, '/');
		  if (tstr)
		    temp = ++tstr;
		  goto next_special;

		  /* :h discards the last part of a pathname. */
		case 'h':
		  tstr = rindex (temp, '/');
		  if (tstr)
		    *tstr = '\0';
		  goto next_special;

		  /* :r discards the suffix. */
		case 'r':
		  tstr = rindex (temp, '.');
		  if (tstr)
		    *tstr = '\0';
		  goto next_special;

		  /* :e discards everything but the suffix. */
		case 'e':
		  tstr = rindex (temp, '.');
		  if (tstr)
		    temp = tstr;
		  goto next_special;

		  /* :s/this/that substitutes `this' for `that'. */
		  /* :gs/this/that substitutes `this' for `that' globally. */
		case 'g':
		  if (string[i + 2] == 's')
		    {
		      i++;
		      substitute_globally = 1;
		      goto substitute;
		    }
		  else
		    
		case 's':
		  substitute:
		  {
		    char *this, *that, *new_event;
		    int delimiter = 0;
		    int si, l_this, l_that, l_temp = strlen (temp);

		    if (i + 2 < strlen (string))
		      delimiter = string[i + 2];

		    if (!delimiter)
		      break;

		    i += 3;

		    /* Get THIS. */
		    for (si = i; string[si] && string[si] != delimiter; si++);
		    l_this = (si - i);
		    this = (char *)alloca (1 + l_this);
		    strncpy (this, string + i, l_this);
		    this[l_this] = '\0';

		    i = si;
		    if (string[si])
		      i++;

		    /* Get THAT. */
		    for (si = i; string[si] && string[si] != delimiter; si++);
		    l_that = (si - i);
		    that = (char *)alloca (1 + l_that);
		    strncpy (that, string + i, l_that);
		    that[l_that] = '\0';

		    i = si;
		    if (string[si]) i++;

		    /* Ignore impossible cases. */
		    if (l_this > l_temp)
		      goto cant_substitute;

		    /* Find the first occurrence of THIS in TEMP. */
		    si = 0;
		    for (; (si + l_this) <= l_temp; si++)
		      if (strncmp (temp + si, this, l_this) == 0)
			{
			  new_event =
			    (char *)alloca (1 + (l_that - l_this) + l_temp);
			  strncpy (new_event, temp, si);
			  strncpy (new_event + si, that, l_that);
			  strncpy (new_event + si + l_that,
				   temp + si + l_this,
				   l_temp - (si + l_this));
			  new_event[(l_that - l_this) + l_temp] = '\0';
			  temp = new_event;

			  if (substitute_globally)
			    {
			      si += l_that;
			      l_temp = strlen (temp);
			      substitute_globally++;
			      continue;
			    }

			  goto hack_specials;
			}

		  cant_substitute:

		    if (substitute_globally > 1)
		      {
			substitute_globally = 0;
			goto hack_specials;
		      }

		    goto event_not_found;
		  }

		  /* :# is the line so far.  Note that we have to
		     alloca () it since RESULT could be realloc ()'ed
		     below in add_string. */
		case '#':
		hack_pound_sign:
		  if (result)
		    {
		      temp = (char *)alloca (1 + strlen (result));
		      strcpy (temp, result);
		    }
		  else
		    temp = "";

		next_special:
		  i += 2;
		  goto hack_specials;
		}

	    }
	  /* Believe it or not, we have to back the pointer up by one. */
	  --i;
	  goto add_string;

	  /* A regular character.  Just add it to the output string. */
	default:
	add_char:
	  tt[0] = string[i];
	  temp = tt;
	  goto do_add;

	add_string:
	  modified++;