Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 3a9bb55684
Fetching contributors…

Cannot retrieve contributors at this time

file 1572 lines (1448 sloc) 35.493 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 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
/* calc.c */
/* Copyright 1995 by Steve Kirkendall */

char id_calc[] = "$Id: calc.c,v 2.65 1999/04/08 22:09:25 steve Exp $";

#include "elvis.h"
#include <setjmp.h>
#ifdef TRY
# include <getopt.h>
# undef o_true
# define o_true "True"
# undef o_false
# define o_false "False"
# undef isdigit
# undef isupper
# undef islower
# undef isalnum
# undef toupper
# undef tolower
# if USE_PROTOTYPES
    extern int isdigit(int c);
    extern int isupper(int c);
    extern int islower(int c);
    extern int isalnum(int c);
    extern int toupper(int c);
    extern int tolower(int c);
# endif
#endif


#if USE_PROTOTYPES
static int copyname(CHAR *dest, CHAR *src, BOOLEAN num);
static BOOLEAN func(CHAR *name, CHAR *arg);
static BOOLEAN apply(void);
static CHAR *applyall(int prec);
#endif

#ifndef TRY
static CHAR *feature[] =
{
# ifdef PROTOCOL_HTTP
toCHAR("http"),
# endif
# ifdef PROTOCOL_FTP
toCHAR("ftp"),
# endif
# ifdef FEATURE_SHOWTAG
toCHAR("showtag"),
# endif
# ifdef FEATURE_LPR
toCHAR("lpr"),
# endif
# ifdef FEATURE_ALIAS
toCHAR("alias"),
# endif
# ifdef FEATURE_MKEXRC
toCHAR("mkexrc"),
# endif
# ifdef FEATURE_COMPLETE
toCHAR("complete"),
#endif
# ifdef FEATURE_RAM
toCHAR("ram"),
# endif
# ifdef FEATURE_BACKTICK
toCHAR("backtick"),
# endif
NULL
};
#endif

/* This array describes the operators */
static struct
{
char *name; /* name of the operator */
short prec; /* natural precedence of the operator */
char code; /* function code for applying operator */
char subcode;/* details, depend on function */
} opinfo[] =
{
{"Func",1, 'f', '('},
{";", 2, 'c', ';'},
{",", 2, 'c', ','},
{"||", 4, 'b', '|'},
{"&&", 5, 'b', '&'},
{"!=", 9, 's', '!'},
{"==", 9, 's', '='},
{"<=", 10, 's', 'l'},
{">=", 10, 's', 'g'},
{"<<", 11, 'i', '<'},
{">>", 11, 'i', '>'},
{":", 3, 't', ':'},
{"?", 2, 't', '?'},
{"|", 6, 'i', '|'},
{"^", 7, 'i', '^'},
{"&", 8, 'i', '&'},
{"=", 9, 's', '='},
{"<", 10, 's', '<'},
{">", 10, 's', '>'},
{"+", 12, 'i', '+'},
{"-", 12, 'i', '-'},
{"%", 13, 'i', '%'},
{"*", 13, 'i', '*'},
{"/", 13, 'i', '/'},
{"!", 14, 'u', '!'},
{"~", 14, 'u', '~'},
};


/* The following variables are used during the evaluation of each expression */
static struct
{
CHAR *first; /* first argument to operator */
int idx; /* index into opinfo of the operator */
int prec; /* precedence of operator */
} opstack[10];
static int ops; /* stack pointer for opstack[] */

/* The following variables are used for storing the parenthesis level */
static CHAR *parstack[20];

/* ultimately, the result returned by calculate() */
static CHAR result[1024];
#define RESULT_END (&result[QTY(result) - 3])
#define RESULT_AVAIL(from) ((int)(RESULT_END - (CHAR *)(from)))
#define RESULT_OVERFLOW(from, need) (RESULT_AVAIL(from) < (int)(need))


/* This function returns True iff a string looks like an integer */
BOOLEAN calcnumber(str)
CHAR *str; /* a nul-terminated string to check */
{
BOOLEAN dp = False; /* has decimal point been seen yet? */

/* allow a leading "-" */
if (*str == '-')
str++;

/* The only decimal number that can start with '0' is zero */
if (str[0] == '0' && str[1])
return False;

/* Require at least one digit, and don't allow any non-digits */
do
{
if (*str == '.' && dp == False && str[1])
dp = True;
else if (!isdigit(*str))
return False;
} while (*++str);
return True;
}


/* This function returns True if passed a string which looks like a number,
* and False if it doesn't. This function differs from calcnumber() in that
* this one also converts octal numbers, hex numbers, and literal characters
* to base ten. Note that the length of the string may change.
*/
BOOLEAN calcbase10(str)
CHAR *str;
{
long num;
int i;

/* do the easy tests first */
if (calcnumber(str)) return True;
if (*str != '0' && *str != '\'') return False;

if (str[0] == '\'')
{
if (str[1] == '\\')
{
if (!str[2] || str[3] != '\'')
return False;
switch (str[2])
{
case '0': num = 0; break;
case 'a': num = '\007'; break;
case 'b': num = '\b'; break;
case 'E':
case 'e': num = '\033'; break;
case 'f': num = '\f'; break;
case 'n': num = '\n'; break;
case 'r': num = '\r'; break;
case 't': num = '\t'; break;
default: num = str[2]; break;
}
i = 4;
}
else
{
if (str[1] == '\\' || !str[1] || str[2] != '\'')
return False;
num = str[1];
i = 3;
}
}
else if (str[1] == 'x')
{
/* is it hex? */
for (i = 2, num = 0; ; i++)
{
if (str[i] >= '0' && str[i] <= '9')
num = num * 16 + str[i] - '0';
else if (str[i] >= 'a' && str[i] <= 'f')
num = num * 16 + str[i] - 'a' + 10;
else
break;
}
}
else
{
/* is it octal? */
for (i = 1, num = 0; ; i++)
{
if (str[i] >= '0' && str[i] <= '7')
num = num * 8 + str[i] - '0';
else
break;
}
}

/* If we hit a problem before the end of the string, it isn't a number */
if (str[i]) return False;

/* We have a number! Convert to decimal */
long2CHAR(str, num);
return True;
}


/* This function returns False if the string looks like any kind of "false"
* value, and True otherwise. The false values are "", "0", "false", "no",
* and the value of the `false' option.
*/
BOOLEAN calctrue(str)
CHAR *str; /* the sting to be checked */
{
if (!str || !*str || !CHARcmp(str, toCHAR("0"))
|| !CHARcmp(str, toCHAR("false")) || !CHARcmp(str, toCHAR("no"))
|| (o_false && !CHARcmp(str, o_false)))
{
return False;
}
return True;
}


/* This function copies characters up to the next non-alphanumeric character,
* nul-terminates the copy, and returns the number of characters copied.
*/
static int copyname(dest, src, num)
CHAR *dest; /* where to copy into */
CHAR *src; /* start of alphanumeric string to copy from */
BOOLEAN num; /* treat numbers specially? */
{
int i;

/* copy until non-alphanumeric character is encountered */
if (num && isdigit(*src))
{
for (i = 0; isdigit(*src); i++)
{
if (RESULT_OVERFLOW(dest, 2)) return 0;
*dest++ = *src++;
}
}
else
{
for (i = 0; isalnum(*src) || *src == '_'; i++)
{
if (RESULT_OVERFLOW(dest, 2)) return 0;
*dest++ = *src++;
}
}
*dest = '\0';
return i;
}

/* This function implements the built-in "functions". The name indicates
* which function should be performed, and arg is its only argument. The
* result should be a string, and it should be copied over the name; func
* should then return True to indicate success. If the function fails for
* any reason, func() should emit an error message and return False.
*
* The functions supported are:
* strlen(string) return the number of characters in the string.
* tolower(string) returns a lowercase version of string.
* toupper(string) returns an uppercase version of string.
* isnumber(string) return "true" iff string is a decimal number
* htmlsafe(string) return an HTML-encoded version of string
* quote(chars,str) return a copy of str with backslashes before chars
* unquote(chars,str) return a copy of str with backslashes before chars
* hex(number) return a string representing the hex value of number
* octal(number) return a string representing the octal value of number
* char(number) return a single-character string
* exists(file) return "true" iff file exists
* dirperm(file) return a string indicating file attributes.
* dirfile(file) return the filename part of a pathname (including ext)
* dirname(file) return the directory part of a pathname.
* dirdir(file) return the directory, like dirname(file).
* dirext(file) return the filename extension.
* basename(file) return the filename without extension.
* elvispath(file) return the pathname of a file in elvis' path, or ""
* buffer(buf) return "true" iff buffer exist
* feature(name) return "true" iff the named feature is supported
* knownsyntax(file) return language if the file's extension is in elvis.syn
* current(what) return line, column, word, mode, next, prev, or tag
*/
static BOOLEAN func(name, arg)
CHAR *name; /* name of function to apply */
CHAR *arg; /* the argument to the function */
{
CHAR *tmp;
#ifndef TRY
char *c;
int i;
MARK begin;
MARKBUF end;
#endif

if (!CHARcmp(name, toCHAR("strlen")))
{
long2CHAR(name, (long)CHARlen(arg));
return True;
}
else if (!CHARcmp(name, toCHAR("tolower")))
{
for (; *arg; arg++)
*name++ = (isupper(*arg) ? tolower(*arg) : *arg);
*name = '\0';
return True;
}
else if (!CHARcmp(name, toCHAR("toupper")))
{
for (; *arg; arg++)
*name++ = (islower(*arg) ? toupper(*arg) : *arg);
*name = '\0';
return True;
}
else if (!CHARcmp(name, toCHAR("isnumber")))
{
if (RESULT_OVERFLOW(name, 6)) goto Overflow;
CHARcpy(name, calcnumber(arg) ? o_true : o_false);
return True;
}
#ifndef TRY
else if (!CHARcmp(name, toCHAR("htmlsafe")))
{
for (i = 0, tmp = NULL; arg[i]; i++)
{
switch (arg[i])
{
case '&': buildstr(&tmp, "&amp;"); break;
case '<': buildstr(&tmp, "&lt;"); break;
case '>': buildstr(&tmp, "&gt;"); break;
case '"': buildstr(&tmp, "&quot;"); break;
case '\t': buildCHAR(&tmp, ' '); break;
default: buildCHAR(&tmp, arg[i]);
}
}
if (tmp)
{
if (RESULT_OVERFLOW(name, CHARlen(tmp))) goto Overflow;
CHARcpy(name, tmp);
safefree(tmp);
}
else
{
*name = '\0';
}
return True;
}
#endif
else if (!CHARcmp(name, toCHAR("hex")))
{
if (!calcnumber(arg)) goto NeedNumber;
if (RESULT_OVERFLOW(name, 10)) goto Overflow;
sprintf((char *)name, "0x%lx", CHAR2long(arg));
return True;
}
else if (!CHARcmp(name, toCHAR("octal")))
{
if (!calcnumber(arg)) goto NeedNumber;
if (RESULT_OVERFLOW(name, 12)) goto Overflow;
sprintf((char *)name, "0%lo", CHAR2long(arg));
return True;
}
else if (!CHARcmp(name, toCHAR("char")))
{
if (!calcnumber(arg)) goto NeedNumber;
*name++ = (CHAR)CHAR2long(arg);
*name = '\0';
return True;
}
else if (!CHARcmp(name, toCHAR("dirext")))
{
/* find the last '.' in the name */
for (tmp = arg + CHARlen(arg); --tmp >= arg && isalnum(*tmp); )
{
}
if (*tmp != '.')
{
tmp = toCHAR("");
}
CHARcpy(name, tmp);
return True;
}
#ifndef TRY
else if (!CHARcmp(name, toCHAR("quote")))
{
/* divide the arg into "chars" and "str" fields */
tmp = CHARchr(arg, (CHAR)',');
if (!tmp)
{
goto Need2Args;
}
*tmp++ = '\0';

/* build a copy with backslashes */
tmp = addquotes(arg, tmp);

/* if the resulting string fits in buffer, then store it */
if (RESULT_OVERFLOW(name, CHARlen(tmp)))
goto Overflow;
CHARcpy(name, tmp);
safefree(tmp);
return True;
}
else if (!CHARcmp(name, toCHAR("unquote")))
{
/* divide the arg into "chars" and "str" fields */
tmp = CHARchr(arg, (CHAR)',');
if (!tmp)
{
goto Need2Args;
}
*tmp++ = '\0';

/* build a copy with backslashes */
tmp = removequotes(arg, tmp);

/* store the resulting string (it *will* fit) */
CHARcpy(name, tmp);
safefree(tmp);
return True;
}
else if (!CHARcmp(name, toCHAR("exists")))
{
switch (urlperm(tochar8(arg)))
{
case DIR_INVALID:
case DIR_BADPATH:
case DIR_NOTFILE:
case DIR_NEW:
CHARcpy(name, o_false);
break;

default:
CHARcpy(name, o_true);
break;
}
return True;
}
else if (!CHARcmp(name, toCHAR("dirperm")))
{
switch (urlperm(tochar8(arg)))
{
case DIR_INVALID:
CHARcpy(name, toCHAR("invalid"));
break;

case DIR_BADPATH:
CHARcpy(name, toCHAR("badpath"));
break;

case DIR_NOTFILE:
CHARcpy(name, toCHAR("notfile"));
break;

case DIR_NEW:
CHARcpy(name, toCHAR("new"));
break;

case DIR_UNREADABLE:
CHARcpy(name, toCHAR("unreadable"));
break;

case DIR_READONLY:
CHARcpy(name, toCHAR("readonly"));
break;

case DIR_READWRITE:
CHARcpy(name, toCHAR("readwrite"));
break;
}
return True;
}
else if (!CHARcmp(name, toCHAR("dirfile")))
{
CHARcpy(name, toCHAR(dirfile(tochar8(arg))));
return True;
}
else if (!CHARcmp(name, toCHAR("dirname")) || !CHARcmp(name, toCHAR("dirdir")))
{
CHARcpy(name, toCHAR(dirdir(tochar8(arg))));
return True;
}
else if (!CHARcmp(name, toCHAR("basename")))
{
CHARcpy(name, toCHAR(dirfile(tochar8(arg))));
/* find the last '.' in the name */
for (tmp = name + CHARlen(name); --tmp >= name && isalnum(*tmp); )
{
}
if (*tmp == '.')
{
*tmp = '\0';
}
return True;
}
else if (!CHARcmp(name, toCHAR("fileeol")))
{
CHARcpy(name, toCHAR(ioeol(tochar8(arg))));
return True;
}
else if (!CHARcmp(name, toCHAR("elvispath")))
{
tmp = toCHAR(iopath(tochar8(o_elvispath), tochar8(arg), False));
if (!tmp)
*name = '\0';
else
{
if (RESULT_OVERFLOW(name, CHARlen(tmp))) goto Overflow;
CHARcpy(name, tmp);
}
return True;
}
else if (!CHARcmp(name, toCHAR("getcwd")))
{
c = dircwd();
if (RESULT_OVERFLOW(name, strlen(c))) goto Overflow;
CHARcpy(name, toCHAR(c));
return True;
}
else if (!CHARcmp(name, toCHAR("absolute")))
{
c = urllocal(tochar8(arg));
if (c)
c = dirpath(dircwd(), c);
else
c = tochar8(arg);
if (RESULT_OVERFLOW(name, strlen(c))) goto Overflow;
CHARcpy(name, toCHAR(c));
return True;
}
else if (!CHARcmp(name, toCHAR("buffer")))
{
CHARcpy(name, buffind(arg) ? o_true : o_false);
return True;
}
else if (!CHARcmp(name, toCHAR("alias")))
{
# ifdef FEATURE_ALIAS
c = exisalias(tochar8(arg), True);
tmp = (c ? o_true : o_false);
# else
tmp = o_false;
# endif
if (RESULT_OVERFLOW(name, CHARlen(tmp))) goto Overflow;
CHARcpy(name, tmp);
return True;
}
else if (!CHARcmp(name, toCHAR("feature")))
{
/* for now */
CHARcpy(name, o_false);

/* is it the name of a supported display mode? */
i = 0;
do
{
if (!CHARcmp(toCHAR(allmodes[i]->name), arg))
{
CHARcpy(name, o_true);
return True;
}
} while (allmodes[i++] != &dmnormal);

/* is it the name of a supported protocol */
for (i = 0; feature[i] && CHARcmp(feature[i], arg); i++)
{
}
if (feature[i])
CHARcpy(name, o_true);

return True;
}
else if (!CHARcmp(name, toCHAR("knownsyntax")))
{
#ifdef DISPLAY_SYNTAX
tmp = dmsknown(tochar8(arg));
if (!tmp)
*name = '\0';
else if (RESULT_OVERFLOW(name, CHARlen(tmp)))
goto Overflow;
else
CHARcpy(name, tmp);
#else
*name = '\0'; /* no syntax modes are supported */
#endif
return True;
}
else if (!CHARcmp(name, toCHAR("current")))
{
/* The default return value is an empty string */
*name = '\0';

/* Other possible values depend on the arg */
switch (*arg)
{
case 'l': /* line number */
if (windefault)
sprintf(tochar8(name), "%ld", markline(windefault->cursor));
break;

case 'c': /* column number */
if (windefault)
sprintf(tochar8(name), "%ld", (*windefault->md->mark2col)(windefault, windefault->cursor, viiscmd(windefault)) + 1);
break;

case 'w': /* word at cursor */
if (windefault)
{
end = *windefault->cursor;
begin = wordatcursor(&end);
if (begin && RESULT_OVERFLOW(name, markoffset(&end) - markoffset(begin)))
goto Overflow;
if (begin)
{
scanalloc(&tmp, begin);
for (i = (int)(markoffset(&end) - markoffset(begin)); i > 0; i--)
{
*name++ = *tmp;
scannext(&tmp);
}
scanfree(&tmp);
*name = '\0';
}
}
break;

case 'm': /* mode */
if (windefault && !windefault->state->acton)
{
for (c = windefault->state->modename; *c; c++)
{
if (*c != ' ')
*name++ = tolower(*c);
}
}
break;

case 's': /* visible selection */
if (windefault && !windefault->state->acton && windefault->seltop)
{
switch (windefault->seltype)
{
case 'c':
CHARcpy(name, toCHAR("character"));
break;

case 'r':
CHARcpy(name, toCHAR("rectangle"));
break;

default:
CHARcpy(name, toCHAR("line"));
}
}
break;

case 'n': /* next arg */
if (arglist[argnext])
{
if (RESULT_OVERFLOW(name, strlen(arglist[argnext])))
goto Overflow;
for (c = arglist[argnext]; *c; )
{
*name++ = *c++;
}
*name = '\0';
}
break;

case 'p': /* previous arg */
if (argnext >= 2)
{
if (RESULT_OVERFLOW(name, strlen(arglist[argnext - 2])))
goto Overflow;
for (c = arglist[argnext - 2]; *c; )
{
*name++ = *c++;
}
*name = '\0';
}
break;

case 't': /* tag or tagstack */
tmp = NULL;
#ifdef FEATURE_SHOWTAG
if (!CHARcmp(arg, "tag"))
tmp = telabel(windefault->cursor);
else
#endif
if (windefault && windefault->tagstack->origin)
tmp = o_bufname(markbuffer(windefault->tagstack->origin));
if (tmp)
{
if (RESULT_OVERFLOW(name, CHARlen(tmp)))
goto Overflow;
CHARcpy(name, tmp);
}
break;
}
return True;
}
else if (!CHARcmp(name, toCHAR("line")))
{
if (!*arg)
{
/* no arguments, use current line of current file */
if (!windefault)
goto NeedWindefault;
begin = markdup(windefault->cursor);
(void)marksetline(begin, markline(begin));
}
else if (calcnumber(arg))
{
/* just a number, use given line of current file */
if (!windefault)
goto NeedWindefault;
begin = markdup(windefault->cursor);
if (marksetline(begin, atol(tochar8(arg))) == NULL)
goto BadArgs;
}
else
{
/* given name & number, I hope! */
tmp = CHARrchr(arg, ',');
if (!tmp)
goto BadArgs;
*tmp++ = '\0';
end.buffer = buffind(arg);
if (!end.buffer
|| !calcnumber(tmp)
|| marksetline(&end, atol(tochar8(tmp))) == NULL)

goto BadArgs;
begin = markdup(&end);
}

/* one way or another, "begin" is now set to the start of the
* line. Copy it into the buffer (or as much of it as will fit)
*/
for (scanalloc(&tmp, begin);
tmp && *tmp != '\n' && RESULT_AVAIL(name) > 10;
scannext(&tmp))
{
*name++ = *tmp;
}
scanfree(&tmp);
*name = '\0';
return True;
}
else if (!CHARcmp(name, toCHAR("shell")))
{
/* Insert a '!' at the front of arg. (This is safe
* since we know that "shell\0" appears before it.)
*/
*--arg = '!';

/* Run the command and read its output */
if (ioopen(tochar8(arg), 'r', False, False, 't'))
{
arg = name;
while ((i = ioread(arg,RESULT_AVAIL(name))) > 0)
{
if (RESULT_OVERFLOW(arg, i + 1))
goto Overflow;
arg += i;
}
ioclose();
}

/* Remove the last newline */
if (arg != name && arg[-1] == '\n')
arg--;
*arg = '\0';
return True;
}
#endif /* not TRY */

#ifdef TRY
msg(MSG_ERROR, "unknown function %s", name);
#else
msg(MSG_ERROR, "[S]unknown function $1", name);
#endif
return False;

NeedNumber:
#ifdef TRY
msg(MSG_ERROR, "%s requires a numeric argument", name);
#else
msg(MSG_ERROR, "[S]$1 requires a numeric argument", name);
#endif
return False;

#ifndef TRY
Need2Args:
msg(MSG_ERROR, "[S]$1 requires two arguments", name);
return False;
#endif

Overflow:
msg(MSG_ERROR, "result too long");
return False;

#ifndef TRY
NeedWindefault:
msg(MSG_ERROR, "[S]$1 requires both a buffer name and a line number when there is no window", name);
return False;

BadArgs:
msg(MSG_ERROR, "[S]$1 called with bad arguments", name);
return False;
#endif
}

/* This function applies a single operator. Returns False on error. Its
* side effects are that it decrements the "ops" counter, and alters the
* contents of the result buffer.
*/
static BOOLEAN apply()
{
long i, j;
CHAR *first, *second, *third;
char subcode;

assert(ops >= 1);

second = opstack[ops--].first;
first = opstack[ops].first;
subcode = opinfo[opstack[ops].idx].subcode;
switch (opinfo[opstack[ops].idx].code)
{
case 'u': /* unary operators */
/* Unary operators depend only on their second argument.
* The result is concatenated to the first argument, which
* is normally an empty string.
*/
if (subcode == '!')
{
(void)CHARcat(first, calctrue(second) ? o_false : o_true);
}
else /* '~' */
{
if (calcnumber(second))
{
/* bitwise negation */
long2CHAR(first + CHARlen(first), ~CHAR2long(second));
}
else
{
/* stuff a ~ between the strings */
second[-1] = '~';
}
}
break;

case 'i': /* integer operators */
/* If either argument is a non-number, then concatenate them
* with the operator between them. This is tricky because
* the << and >> operators are too large to simply replace
* the '\0' between the strings.
*/
if (!calcnumber(first) || !calcnumber(second))
{
if (subcode == '<' || subcode == '>')
{
/* As a special case, "string << number" and
* "string >> number" truncate the string to
* the length given by the number, keeping
* characters from the left or right.
*/
if (calcnumber(second))
{
/* convert arguments */
i = CHARlen(first);
j = CHAR2long(second);

/* make sure this width wouldn't
* overflow the result buffer.
*/
if (RESULT_OVERFLOW(first, j))
{
msg(MSG_ERROR, "result too long");
return False;
}

/* Pad or truncate */
if (subcode == '<')
{
/* Pad or truncate, keeping
* chars on left. The first
* arg's characters are already
* in the right place, so we
* don't need to copy them.
* Just pad if first is short.
*/
while (i < j)
first[i++] = ' ';
first[j] = '\0';
}
else
{
if (i < j)
{
/* String needs to be
* padded. Shift it
* to right, and then
* pad on the left.
*/
first[j] = '\0';
while (i > 0)
first[--j] = first[--i];
while (j > 0)
first[--j] = ' ';
}
else if (i > j)
{
/* String needs to be
* truncated. Shift it
* to the left.
*/
CHARcpy(first, first + i - j);
}
}
break;
}
msg(MSG_WARNING, "<< and >> only partially implemented");
}
#ifndef TRY
else if (subcode == '/')
{
/* When the / operator is passed strings as
* arguments, it contatenates them as a
* directory name and a file name.
*/
CHARcpy(first, toCHAR(dirpath(tochar8(first), tochar8(second))));
break;
}
#endif
second[-1] = subcode;
}
else
{
i = CHAR2long(first);
j = CHAR2long(second);
switch (subcode)
{
case '*': i *= j; break;
case '+': i += j; break;
case '-': i -= j; break;
case '<': i <<= j; break;
case '>': i >>= j; break;
case '&': i &= j; break;
case '^': i ^= j; break;
case '|': i |= j; break;
case '/': if (j == 0) goto DivZero;
i /= j; break;
case '%': if (j == 0) goto DivZero;
i %= j; break;
}
long2CHAR(first, i);
}
break;

case 's': /* string or integer comparison operators */
/* if both arguments look like numbers, then compare
* numerically; else compare as strings.
*/
if (calcnumber(first) && calcnumber(second))
{
i = CHAR2long(first) - CHAR2long(second);
}
else
{
i = CHARcmp(first, second);
}
switch (subcode)
{
case '<': i = (i < 0); break;
case 'l': i = (i <= 0); break;
case '>': i = (i > 0); break;
case 'g': i = (i >= 0); break;
case '=': i = (i == 0); break;
case '!': i = (i != 0); break;
}
(void)CHARcpy(first, toCHAR(i ? o_true : o_false));
break;

case 'c': /* concatenation operators */
if (subcode == ';')
memmove(second - 1, second, sizeof(CHAR) * (CHARlen(second) + 1));
else
second[-1] = subcode;
break;

case 'b': /* boolean operators */
if (subcode == '&')
{
i = (calctrue(first) && calctrue(second));
}
else /* subcode == '|' */
{
i = (calctrue(first) || calctrue(second));
}
(void)CHARcpy(first, toCHAR(i ? o_true : o_false));
break;

case 't': /* ternary operator */
/* This should be either (bool ? string : string) if we're
* evaluating a ':', or just (bool ? string) if we're
* evaluating a '?'. The '?' and ':' operators are parsed as
* if they were separate binary operators. The '?' has a
* slightly lower precedence than ':', so if we're evaluating
* a ':' we can expect the '?' to be the preceding operator on
* the stack. That's very important!
*/
if (subcode == ':')
{
/* complain if not after a '?' */
if (ops < 1 || opstack[ops - 1].prec != opstack[ops].prec - 1)
{
msg(MSG_ERROR, "bad operator");
return False;
}

/* shift the arguments */
third = second;
second = first;
first = opstack[--ops].first;
}
else
{
/* (bool ? string) is legal -- assume third arg is "" */
third = toCHAR("");
}

/* replace the first boolean with either second or third arg */
CHARcpy(first, calctrue(first) ? second : third);
break;

case 'f': /* functions */
/* use func() to apply the function. */
return func(first, second);
}
return True;

DivZero:
msg(MSG_ERROR, "division by 0");
return False;
}

/* This function iteratively applies all preceding operators with a precedence
* no lower than some given level. Leaves "result" and "ops" altered. Returns
* a pointer to the end of the result, or NULL if error.
*/
static CHAR *applyall(prec)
int prec; /* lowest precedence to apply */
{
while (ops > 0 && opstack[ops - 1].prec >= prec)
{
if (!apply())
{
return (CHAR *)0;
}
}
return opstack[ops].first + CHARlen(opstack[ops].first);
}


/* This function evaluates an expression, as for a :if or :let command.
* Returns the result of the evaluation, or NULL if error.
*/
CHAR *calculate(expr, arg, asmsg)
CHAR *expr; /* an expression to evaluate */
CHAR **arg; /* arguments, to replace $1 through $9 */
BOOLEAN asmsg; /* if True, only evaluate parts that are in parens */
{
CHAR *build; /* the result so far */
int base = 0; /* precedence base, keeps track or () pairs */
int nargs; /* number of arguments in arg[] */
CHAR *tmp;
int i, prec;

/* count the args */
for (nargs = 0; arg && arg[nargs]; nargs++)
{
}

/* reset stack & result */
ops = 0;
opstack[ops].first = build = result;
*build = '\0';


/* process the expression from left to right... */
while (*expr)
{
if (RESULT_OVERFLOW(build, 1)) goto Overflow;
switch (*expr)
{
case ' ':
case '\t':
case '\n':
/* whitespace is ignored unless asmsg */
if (base == 0 && asmsg)
{
*build++ = *expr;
*build = '\0';
}
expr++;
break;

case '"':
if (base == 0 && asmsg)
{
/* For messages, " is just another character */
*build++ = *expr++;
*build = '\0';
}
else
{
/* quoted text is copied verbatim */
while (*++expr && *expr != '"')
{
if (RESULT_OVERFLOW(build, 1))
goto Overflow;
if (*expr != '\\')
{
*build++ = *expr;
continue;
}
switch (*++expr)
{
case 0:
*build++ = '\\';
expr--;
break;

case '\n': break;
case 'a': *build++ = '\007'; break;
case 'b': *build++ = '\b'; break;
case 'E': *build++ = '\033'; break;
case 'f': *build++ = '\f'; break;
case 'n': *build++ = '\n'; break;
case 'r': *build++ = '\r'; break;
case 't': *build++ = '\t'; break;
default: *build++ = *expr;
}
}
if (*expr == '"')
{
expr++;
}
*build = '\0';
}
break;

case '\\':
/* In most contexts, a backslash is treated as a
* literal character. However, it can also be used to
* quote the special characters of a message string:
* dollar sign, parentheses, and the backslash itself.
*/
expr++;
if (build == result || !*expr || !strchr("$()\\", *expr))
{
/* at front of expression, or if followed by
* normal character - literal */
*build++ = '\\';
}
else if (*expr)
{
/* followed by special character - quote */
*build++ = *expr++;
}
*build = '\0';
break;

case '$':
/* if it isn't followed by an alphanumeric character,
* then treat the '$' as a literal character.
*/
expr++;
if (!isalnum(*expr) && *expr != '_')
{
*build++ = '$';
break;
}

/* copy the name into the result buffer temporarily,
* just so we have a nul-terminated copy of it.
*/
i = copyname(build, expr, True);
if (i == 0) goto Overflow;
expr += i;

/* if number instead of a name, then use arg[i] */
if (calcnumber(build))
{
i = CHAR2long(build);
if (i <= 0 || i > nargs)
{
#ifdef TRY
msg(MSG_ERROR, "args must be $1 through $%d", nargs);
#else
msg(MSG_ERROR, "[d]args must be \\$1 through \\$$1", nargs);
#endif
return (CHAR *)0;
}
if (RESULT_OVERFLOW(build, CHARlen(arg[i - 1])))
goto Overflow;
(void)CHARcpy(build, arg[i - 1]);
build += CHARlen(build);
}
else
{
/* try to fetch its value; stuff the value (or an
* empty string) into the result buffer.
*/
tmp = toCHAR(getenv(tochar8(build)));
if (!tmp)
{
/* convert to uppercase & try again */
for (tmp = build; *tmp; tmp++)
*tmp = toupper(*tmp);
tmp = toCHAR(getenv(tochar8(build)));
}
if (tmp)
{
if (RESULT_OVERFLOW(build, CHARlen(tmp)))
goto Overflow;
(void)CHARcpy(build, tmp);
build += CHARlen(build);
}
else
{
*build = '\0';
}
}
break;

case '(':
/* increment the precedence base */
parstack[base / 20] = opstack[ops].first;
base += 20;

/* adjust the start of arguments */
opstack[ops].first = build;

expr++;
break;

case ')':
/* detect mismatched ')' */
if (base == 0)
{
goto Mismatch;
}

/* apply any preceding higher-precedence operators */
build = applyall(base);
if (!build)
{
return (CHAR *)0;
}

/* decrement the precedence base */
base -= 20;
opstack[ops].first = parstack[base / 20];

expr++;
break;

default:
/* It may be an option name, a number, or an operator.
* If it appears to be alphanumeric, then assume it
* is either a number or a name.
*/
if (isalnum(*expr) || *expr == '_')
{
/* Copy the string into the result buffer. */
i = copyname(build, expr, False);
if (i == 0) goto Overflow;
expr += i;

/* if asmsg, then do no further processing of it */
if (base == 0 && asmsg)
{
build += i;
*build = '\0';
break;
}

/* If the string looks like a number, leave it.
* If not a number, then look it up as the name
* of an option, and replace it with the value
* of that option.
*/
if (calcbase10(build))
{
/* number -- keep it */
build += CHARlen(build);
}
else if (*expr == '(')
{
/* function name -- push a '('
* operator with a precedence set
* so that next ')' will cause it
* to be evaluated.
*/
parstack[base / 20] = opstack[ops].first;
opstack[ops].first = build;

/* keep the function name */
build += i;

/* increment the precedence base */
base += 20;

/* compute the precedence of the operator */
prec = 1 + base;

/* store this operator, and start a new
* one right after it.
*/
opstack[ops].idx = 0;
opstack[ops].prec = prec;
opstack[++ops].first = ++build;
*build = '\0';
expr++;
}
else
{
/* option name -- look it up */
tmp = optgetstr(build, NULL);
if (!tmp)
{
#ifdef TRY
msg(MSG_ERROR, "bad option name %s", build);
#else
msg(MSG_ERROR, "[s]bad option name $1", build);
#endif
return (CHAR *)0;
}
if (RESULT_OVERFLOW(build, CHARlen(tmp)))
goto Overflow;
(void)CHARcpy(build, tmp);
build += CHARlen(build);
}
}
else /* not alphanumeric */
{
/* if asmsg, then use it as plain text */
if (base == 0 && asmsg)
{
*build++ = *expr++;
*build = '\0';
break;
}

/* may be a character constant, as in '\t' */
if (expr[0] == '\'')
{
/* copy it into build[] */
build[0] = *expr++;
for (i = 1; *expr && *expr != '\''; )
{
build[i] = *expr++;
if (build[i++] == '\\' && *expr)
build[i++] = *expr++;
}
if (*expr == '\'')
build[i++] = *expr++;
build[i] = '\0';

/* convert to number */
if (calcbase10(build))
{
build += CHARlen(build);
break;
}
else
{
msg(MSG_ERROR, "bad character literal");
return (CHAR *)0;
}
}

/* try to identify an operator. This is slightly
* trickier than it looks -- the order in which
* the comparisons was made had to be fine-tuned
* so it wouldn't think a "!=" was a "!".
*/
for (i = 0;
i < QTY(opinfo) && CHARncmp(opinfo[i].name, expr, strlen(opinfo[i].name));
i++)
{
}
if (i >= QTY(opinfo))
{
#ifdef TRY
msg(MSG_ERROR, "bad operator %c", *expr);
#else
msg(MSG_ERROR, "[C]bad operator $1", *expr);
#endif
return (CHAR *)0;
}

/* compute the precedence of the operator */
prec = opinfo[i].prec + base;

/* apply any preceding operators with equal or
* higher priority.
*/
build = applyall(prec);
if (!build)
{
return (CHAR *)0;
}

/* store this operator, and start a new one
* right after it.
*/
opstack[ops].idx = i;
opstack[ops].prec = prec;
opstack[++ops].first = ++build;
*build = '\0';
expr += strlen(opinfo[i].name);
}
}
}

/* detect situation where more '(' than ')' were given */
if (base > 0)
{
Mismatch:
msg(MSG_ERROR, "\\(\\) mismatch");
return (CHAR *)0;
}

/* evaluate any remaining operators */
build = applyall(0);
if (!build)
{
return (CHAR *)0;
}

/* return the result */
return result;

Overflow:
msg(MSG_ERROR, "result too long");
return (CHAR *)0;
}

#ifndef TRY
/* This function evaluates a section of a buffer, and replaces that section
* with the result. Returns True if successful, or False if there's an error.
*/
BOOLEAN calcsel(from, to)
MARK from;
MARK to;
{
CHAR *expr = bufmemory(from, to);
CHAR *result = calculate(expr, (CHAR **)0, False);

safefree(expr);
if (!result)
{
return False;
}
bufreplace(from, to, result, (long)CHARlen(result));
return True;
}
#endif

#ifdef TRY
# include <stdarg.h>
BUFFER bufdefault;

CHAR *optgetstr(name, desc)
CHAR *name;
OPTDESC **desc;
{
return name;
}

void msg(MSGIMP imp, char *format, ...)
{
va_list argptr;

va_start(argptr, format);
vprintf(format, argptr);
putchar('\n');
va_end(argptr);
}

void main(int argc, char **argv)
{
CHAR expr[200];
CHAR *result;
char flag;
int i;
BOOLEAN msg = False;

/* Parse options */
expr[0] = '\0';
while ((flag = getopt(argc, argv, "e:m")) >= 0)
{
switch (flag)
{
case '?':
fprintf(stderr, "usage: %s [-m] [-e expr] [arg]...\n", argv[0]);
exit(0);
break;

case 'm':
msg = True;
break;

case 'e':
for (i = 0; (expr[i] = optarg[i]) != '\0'; i++)
{
}
break;
}
}

/* were we given an expression on the command line? */
if (*expr)
{
result = calculate(expr, (CHAR **)&argv[optind], msg);
if (result)
puts(tochar8(result));
}
else
{
while (gets(tochar8(expr)))
{
result = calculate(expr, (CHAR **)&argv[optind], msg);
if (result)
puts(tochar8(result));
}
}
exit(result ? 0 : 1);
}
#endif
Something went wrong with that request. Please try again.