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
|
#define USE_BACKTIC 0 // keep code just in case
#include <string>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include "gr.hh"
#include "extern.hh"
#include "command.hh"
#include "superus.hh"
void display_cmd_being_done_stack(void);
extern char _grTempString[];
extern char *_griVersion_name;
#if USE_BACKTIC
static bool sub_backtic(const char *n, char *out);
#endif
static bool sub_dollar_paren(const char *n, char *out);
static int dollar_paren(const char *s, char *res);
bool get_cmd(char *buf, int max, FILE * fp);
bool postscriptCmd(void);
static void check_usage(const char *s);
bool
tracing()
{ // ?? this could be speeded up a lot ??
double trace;
get_var("..trace..", &trace);
return (trace ? true : false);
}
// do_command_line() -- get, massage, and perform command line
// RETURN false if no more command lines. (Set _done=1 if no
// more command lines and the cmd-file stack empties.)
bool
do_command_line()
{
//printf("at start of do_command_line() _cmdLine is <%s>\n",_cmdLine);
// *** Get command line, storing it in the global _cmdLine ***
if (!get_command_line()) {
_cmdFILE.pop_back();
if (_cmdFILE.size() == 0) {
_done = 1;
return false;
}
return false;
}
// Remove comments, do math expansions, substitute synonyms, etc.
massage_command_line(_cmdLine);
// Handle "return" as special case
if ((_nword > 0)
&& (!strcmp(_word[0], "return"))
&& (!skipping_through_if())) {
_cmdFILE.pop_back();
if (_cmdFILE.size() == 0) {
_done = 1;
return false;
} else {
return false;
}
} else {
// Do what the command instructs.
perform_command_line(NULL, true);
return true;
}
}
// Insert command line as a comment in the PostScript file, after
// removing newpage character to blank, (since latex2e/epsfig breaks
// on newpage).
//
// The 'note' is helpful in debugging.
void
insert_cmd_in_ps(const char *cmd, const char *note)
{
extern bool _store_cmds_in_ps; // DEFINED IN startup.c
if (!_store_cmds_in_ps)
return;
unsigned int first_nonwhite = 0;
while (isspace(*(cmd + first_nonwhite)))
first_nonwhite++;
#if 0 // removed 2001-feb-22 for SF bug #133135
if (!strncmp(cmd + first_nonwhite, "insert", 6))
return; // don't want 'insert' commands (confusing eh)
#endif
strcpy(_grTempString, "gri:");
int ii = 4; // where to start insert
int len = strlen(cmd);
for (int i = 0; i < len; i++) {
if (cmd[i] == PASTE_CHAR)
break;
if (cmd[i] != char(12)) // newpage
_grTempString[ii++] = cmd[i];
}
_grTempString[ii] = '\0';
if (_grTempString[strlen(_grTempString) - 1] == '\n')
_grTempString[strlen(_grTempString) - 1] = '\0';
if (*note != '\0') {
strcat(_grTempString, " # ");
strcat(_grTempString, note);
}
gr_comment(_grTempString);
}
#if 1 // used only if -s256 set
void
insert_source_indicator(char *cl)
{
// BUG must not let overrun
unsigned int len = strlen(cl);
char line[1024];
sprintf(line, " \"%s:%d\"", _cmdFILE.back().get_name(), _cmdFILE.back().get_line());
strcat(cl, line);
if (len > 0 && cl[len - 1] == '\n')
cl[len - 1] = PASTE_CHAR;
else
cl[len] = PASTE_CHAR;
}
#endif
// get_command_line() -- get a command line (skip full-line C comments)
bool
get_command_line(void)
{
write_prompt();
stop_replay_if_error();
// get a line from a file.
if (_cmdFILE.back().get_interactive()) {
//printf("DEBUG. interactive. before, had <%s>\n",_cmdLine);
// Cmd-file is interactive (from keyboard)
if (!gr_textget(_cmdLine, LineLength_1)) {
_done = 1;
return false;
}
//printf("DEBUG. interactive. after, have <%s>\n",_cmdLine);
} else {
// Cmd-file is non-interactive.
if (true == get_cmd(_cmdLine, LineLength_1, _cmdFILE.back().get_fp())) {
if (strlen(_cmdLine) < 1) {
if (((unsigned) superuser()) & FLAG_AUT2) printf("%s:%d debug 2\n",__FILE__,__LINE__);
return false;
} else {
warning("Missing newline at end of command file.");
}
}
// Now ready to do something.
if (!is_create_new_command(_cmdLine)) {
// Print trace info if desired
if (tracing()) {
if (skipping_through_if())
printf("X ");
else
printf("%s", _margin.c_str());
printf("%s\n", _cmdLine);
}
}
}
_cmdFILE.back().increment_line(); // BUG line numbers wrong BUG
if (_cmdFILE.back().get_save2ps())
insert_cmd_in_ps(_cmdLine/*, "doline.cc:154"*/);
if (((unsigned) superuser()) & FLAG_AUT1) {
insert_source_indicator(_cmdLine);
}
if (((unsigned) superuser()) & FLAG_AUT2) printf("%s:%d get_command_line returning [%s]\n",__FILE__,__LINE__,_cmdLine);
return true;
}
// Insert PostScript directly into file.
bool
postscriptCmd()
{
extern FILE *_grPS;
fprintf(_grPS, "%s\n", _cmdLine + skip_space(_cmdLine) + strlen("postscript "));
check_psfile();
return true;
}
// Remove comments, expand rpn, substitute synonyms, etc.
// Return 1 if not end-of-file, or 0 if end-of-file.
bool
remove_source_indicator(char *cmd)
{
extern char source_indicator[];
int len = strlen(cmd);
source_indicator[0] = '\0';
for (int i = 0; i < len; i++) {
if (cmd[i] == PASTE_CHAR) {
int cut_here = i;
i++;
while (isspace(*(cmd + i)) && i < len) // skip whitespace if any
i++;
if (cmd[i] == '"')
strcpy(source_indicator, cmd + i + 1);
cmd[cut_here] = '\0';
int len = strlen(source_indicator);
if (source_indicator[len - 1] == '"')
source_indicator[len - 1] = '\0';
return true;
}
}
return false;
}
bool
massage_command_line(char *cmd)
{
_nword = 0;
if (((unsigned) superuser()) & FLAG_AUT1) {
remove_source_indicator(cmd);
}
remove_comment(cmd);
if (!is_system_command(cmd))
check_usage(cmd);
strcpy(_cmdLineCOPY, cmd + skip_space(cmd));
// For system commands, just substitute synonyms.
if (is_system_command(cmd)) {
strcpy(cmd, _cmdLineCOPY);
std::string cmd_sub;
substitute_synonyms_cmdline(cmd, cmd_sub, false);
strcpy(_cmdLineCOPY, cmd_sub.c_str());
strcpy(cmd, _cmdLineCOPY);
// Chop into words. Note: chop_into_words() destroys it's string, so
// use a copy.
chop_into_words(_cmdLineCOPY, _word, &_nword, MAX_nword);
return true;
}
// Don't massage further if it's a `create new command' or a `postscript'
// command.
if (is_create_new_command(cmd)) {
if (((unsigned) superuser()) & FLAG_NEW) printf("[%s]\n", cmd);
return true;
}
// Expand blanks, by separating words, but only in certain circumstances.
if (!re_compare(_cmdLine, "\\s*cd\\s*.*")
&& !re_compare(_cmdLine, "\\s*delete\\s*.*")
&& !re_compare(_cmdLine, "\\s*ls\\s*.*")
&& !re_compare(_cmdLine, "\\s*insert\\s*.*")
&& !re_compare(_cmdLine, "\\s*close\\s*.*")
&& !re_compare(_cmdLine, "\\s*open\\s*.*") // removed 2.5.5; re-inserted 2.6.0
&& !re_compare(_cmdLine, "\\s*postscript\\s*.*") ) {
expand_blanks(cmd);
}
remove_trailing_blanks(cmd);
_error_in_cmd = false;
if (strlen(cmd) < 1) {
_nword = 0;
return true;
}
strcpy(_cmdLineCOPY, cmd + skip_space(cmd));
strcpy(cmd, _cmdLineCOPY);
if (strlen(cmd) < 1) {
_nword = 0;
return true;
}
// Copy back into cmd. This must be done before substituting synonyms,
// so that code like `defined (\syn)' will work.
if (!re_compare(_cmdLine, "\\s*postscript\\s*.*")
&& !re_compare(_cmdLine, "\\s*new\\s*.*")) {
strcpy(cmd, _cmdLineCOPY);
}
// Substitute synonyms; copy back into cmd.
if (((unsigned) superuser()) & FLAG_SYN) printf("[%s]\n", cmd);
// Don't substitute synonyms for these commands: `new \syn ...' `delete
// \syn ...'
if (re_compare(_cmdLine, "\\s*open\\s*.*")) {
std::string cmd_sub;
substitute_synonyms_cmdline(cmd, cmd_sub, false);
strcpy(cmd, cmd_sub.c_str());
} else {
if (!re_compare(_cmdLine, "\\s*new\\s*.*")
&& !re_compare(_cmdLine, "\\s*delete\\s*.*")
#if 0 // 1999-dec-12
&& !re_compare(_cmdLine, "\\s*read\\s+line\\s*.*")
#else
// && !re_compare(_cmdLine, "\\s*read\\s*.*")
#endif
&& !re_compare(_cmdLine, "\\s*get\\s+env\\s*.*")
) {
std::string cmd_sub;
substitute_synonyms_cmdline(cmd, cmd_sub, true);
strcpy(cmd, cmd_sub.c_str());
remove_trailing_blanks(cmd);
}
}
if (((unsigned) superuser()) & FLAG_SYN) printf("DEBUG %s:%d line is now '%s'\n",__FILE__,__LINE__,cmd);
// Substitute backtic and dollar-paren expressions
#if USE_BACKTIC
sub_backtic(cmd, _cmdLineCOPY);
strcpy(cmd, _cmdLineCOPY);
#endif
sub_dollar_paren(cmd, _cmdLineCOPY);
strcpy(cmd, _cmdLineCOPY);
// Substitute rpn expressions one by one, recopying back to cmd after
// each
if (((unsigned) superuser()) & FLAG_RPN) printf("[%s]\n", cmd);
if (!re_compare(_cmdLine, "\\s*postscript\\s*.*")
&& !re_compare(_cmdLine, "\\s*new\\s*.*")
&& !re_compare(_cmdLine, "\\s*while\\s*.*") ) {
if (((unsigned) superuser()) & FLAG_RPN) printf("DEBUG %s:%d about to substitute rpn in '%s' skipping_through_if= %d\n",__FILE__,__LINE__,cmd,skipping_through_if());
if (!skipping_through_if())
while (substitute_rpn_expressions(cmd, _cmdLineCOPY))
strcpy(cmd, _cmdLineCOPY);
remove_trailing_blanks(cmd);
if (strlen(cmd) < 1)
return true;
strcpy(_cmdLineCOPY, cmd);
}
stop_replay_if_error();
strcpy(cmd, _cmdLineCOPY);
if (((unsigned) superuser()) & FLAG_RPN) printf(" --> [%s]\n", cmd);
// Finally, chop up into words. The words (_word) and number of words
// (_nword) are used all over the place in other functions.
chop_into_words(_cmdLineCOPY, _word, &_nword, MAX_nword);
return true;
}
// Do what command line instructs.
// RETURN true if OK, NO if error
bool
perform_command_line(FILE *fp, bool is_which)
{
//if (((unsigned) superuser()) & FLAG_RPN) printf("\nDEBUG %s:%d begin of perform_command_line\n",__FILE__,__LINE__);
if (strlen(_cmdLine) < 1)
return true; // was ok, just blank
// If it's definition of a new gri command, do that.
if (is_create_new_command(_cmdLine)) {
if (is_which)
create_new_command(_cmdFILE.back().get_fp(), _cmdLine);
else
create_new_command(fp, _cmdLine);
return true;
}
// Handle `return'
if (_nword > 0 && !strcmp(_word[0], "return") && !skipping_through_if()) {
_done = 2;
return true;
}
if (((unsigned) superuser()) & FLAG_RPN) printf("DEBUG %s:%d perform_command_line() has command '%s'\n", __FILE__, __LINE__, _cmdLine);
if (((unsigned) superuser()) & FLAG_RPN) printf("DEBUG %s:%d skipping_through_if is %d (STEP 1)\n", __FILE__, __LINE__, skipping_through_if());
// Handle `end' and `else'
if (handle_if_block()) {
if (((unsigned) superuser()) & FLAG_RPN) printf("DEBUG: %s:%d returning early\n",__FILE__,__LINE__);
return true;
}
if (((unsigned) superuser()) & FLAG_RPN) printf("DEBUG %s:%d skipping_through_if is %d (STEP 2)\n", __FILE__, __LINE__, skipping_through_if());
// Process line if not skipping
if (!skipping_through_if()) {
// First, handle de-referenced synonyms as lvalues (to left
// an assignment operator)
std::string w0(_word[0]);
// de_reference(w0); BUG: MAY PUT BACK LATER
char *cp = strdup(w0.c_str());
_word[0] = cp;
// Handle `\name = "value"' command
if (w0[0] == '\\') {
if (_nword > 2 && is_assignment_op(_word[1])) {
assign_synonym();
free(cp);
return true;
}
}
// Handle math command, e.g.
// .var. = 1
// x += 1
// grid data += 1
// image += 1
// etc., permitting various assignment operators,
// including '=', '+=', etc.
if (word_is(0, "x")
|| word_is(0, "y")
|| word_is(0, "z")
|| word_is(0, "u")
|| word_is(0, "v")
|| word_is(0, "image")
|| word_is(0, "grid")
|| is_var(w0)) {
if (_nword == 3) {
if(word_is(1, "=")
|| word_is(1, "-=")
|| word_is(1, "+=")
|| word_is(1, "*=")
|| word_is(1, "/=")
|| word_is(1, "^=")
|| word_is(1, "_=")) {
//printf("DOING mathCmd\n"); for (int ii=0;ii<_nword;ii++) printf("\t<%s>\n",_word[ii]);
mathCmd();
free(cp);
return true;
}
} else if (_nword == 4
&& word_is(0, "grid") && (word_is(1, "data")
|| word_is(1, "x")
|| word_is(1, "y")) ) {
mathCmd();
free(cp);
return true;
} else if (_nword == 4
&& word_is(0, "image") && (word_is(1, "grayscale")
|| word_is(1, "greyscale")
|| word_is(1, "colorscale")
|| word_is(1, "colourscale"))) {
mathCmd();
free(cp);
return true;
} else {
err("Unknown command. Were you trying to manipulate `\\",
_word[0], "' mathematically?", "\\");
free(cp);
return false;
}
}
// Figure out what command, and do it.
int cmd;
if (0 != (cmd = match_gri_syntax(_cmdLine, 0))) {
// Do the command.
push_cmd_being_done_stack(cmd - 1);
if (!perform_gri_cmd(cmd - 1)) {
err("Can't perform/parse following command");
free(cp);
return false;
}
pop_cmd_being_done_stack();
free(cp);
return true;
} else {
// No syntax registered for this command. Check special cases,
// where it's a stray "break," or "continue"
if (word_is(0, "break")) {
err("Cannot have `break' outside loops");
free(cp);
return false;
} else if (word_is(0, "continue")) {
err("Cannot have `continue' outside loops");
free(cp);
return false;
} else if (string_is_blank(_word[0])) {
free(cp);
return true;
} else {
err("Unknown command encountered.");
free(cp);
return false;
}
}
free(cp);
}
return true;
}
// Stop replay if previous command instructed so (because _error_in_cmd set
// to 1 because of error in last command).
bool
stop_replay_if_error()
{
if (_error_in_cmd && !_cmdFILE.back().get_interactive()) {
ShowStr(" Bad command: `");
ShowStr(_cmdLine);
ShowStr("'\n");
display_cmd_being_done_stack();
fatal_err(NULL);
}
return true; // never actually reached
}
// is_system_command() - return 1 if it's a system command
bool
is_system_command(const char *s)
{
// First, check if '\s*system ...'
s += skip_space(s);
if (!strncmp(s, "system", 6) ? true : false)
return true;
// Second, check if '\s*\\name\s*=\s*system ...'
s += skip_nonspace(s); // name
s += skip_space(s); // space
s += skip_nonspace(s); // =
s += skip_space(s); // space
if (!strncmp(s, "system", 6) ? true : false)
return true;
return false;
}
// systemCmd() - handle request for system command. Certain translations are
// done first. (1) \\n is translated into \n so that commands like the
// following will work:
//
// system gawk 'BEGIN { printf("line1\n") ; printf("line2\n");}'
//
// The problem is that the previous parsing, PRESUMING that NEWLINE is not the name
// of a user synonym, will replace "\n" by "\\n" so that the system would
// otherwise be given the string
//
// system gawk 'BEGIN { printf("line1\\n") ; printf("line2\\n");}'
//
// to process. Furthermore, the shell <<WORD syntax is supported.
//
// Important note: this code is only executed outside newcommands
// and blocks. If already inside a block, this command is *never*
// called; see perform_block() in command.cc
bool
systemCmd()
{
if (skipping_through_if())
return true;
// Much of following code duplicated in assign_synonym(), so if any
// problems crop up, check there too.
char *s = _cmdLine;
s += skip_space(s); // skip any initial space
s += skip_nonspace(s); // skip "system"
s += skip_space(s);
// s now points to first word after "system"
if (*s == '\0' || *s == '\n') {
err("`system' needs a system command to do");
return false;
}
// See if last word starts with "<<"; if so, then the stuff to be done
// appears on the lines following, ended by whatever word follows the
// "<<".
// ... compare set.cc near line 3288.
int i = strlen(s) - 2;
static std::string read_until;
read_until.assign("");
bool using_read_until = false;
while (--i) {
if (!strncmp((s + i), "<<", 2)) {
//printf("- looking for <<\n");
bool quoted_end_string = false;
int spaces = 0;
while (isspace(*(s + i + 2 + spaces))) {
spaces++;
}
if (*(s + i + 2 + spaces) == '"') {
spaces++;
quoted_end_string = true;
}
read_until.assign(s + i + 2 + spaces);
using_read_until = true;
// trim junk from end of the 'read until' string
std::string::size_type cut_at;
if (quoted_end_string)
cut_at = read_until.find("\"");
else
cut_at = read_until.find(" ");
//printf("READING UNTIL '%s' ... i.e.\n", read_until.c_str());
if (cut_at != STRING_NPOS)
read_until.STRINGERASE(cut_at, read_until.size() - cut_at);
if (read_until.size() < 1) {
err("`system ... <<STOP_STRING' found no STOP_STRING");
return false;
}
//printf("reading until '%s'\n",read_until.c_str());
break;
}
}
static std::string cmd; // might save time in loops
cmd.assign(s);
if (using_read_until) {
// It is of the <<WORD form
cmd.append("\n");
//printf("%s:%d ABOUT TO GOBBLE\n",__FILE__,__LINE__);
while (get_command_line()) {
//printf("%s:%d cmd line is [%s]\n",__FILE__,__LINE__,_cmdLine);
// Trim filename/fileline indicator
unsigned int l = strlen(_cmdLine);
for (unsigned int ii = 0; ii < l; ii++) {
if (_cmdLine[ii] == PASTE_CHAR) {
_cmdLine[ii] = '\0';
break;
}
}
if (!strncmp(_cmdLine + skip_space(_cmdLine), read_until.c_str(), read_until.size())) {
cmd.append(_cmdLine + skip_space(_cmdLine));
cmd.append("\n");
break;
}
cmd.append(_cmdLine);
cmd.append("\n");
}
static std::string cmd_sub;
substitute_synonyms_cmdline(cmd.c_str(), cmd_sub, false);
cmd = cmd_sub;
} else {
// No, it is not of the <<WORD form
std::string::size_type loc = 0;
//printf("system command BEFORE [%s]\n",cmd.c_str());
while (STRING_NPOS != (loc = cmd.find("\\\\", loc))) {
cmd.STRINGERASE(loc, 2);
cmd.insert(loc, "\\");
}
//printf("AFTER [%s]\n",cmd.c_str());
}
int status = call_the_OS(cmd.c_str(), __FILE__, __LINE__);
PUT_VAR("..exit_status..", (double) status);
sprintf(_grTempString, "%d status\n", status);
RETURN_VALUE(_grTempString);
return true;
}
static void
show_startup_msg()
{
std::string fullfilename(_lib_directory.c_str());
// Must check for '/' as file separator, on some machines.
#if !defined(VMS)
#if defined(MSDOS)
// Insert a '\' if required
if (fullfilename[fullfilename.length() - 1] != '\\') {
fullfilename += "\\";
}
#else
// Insert a '/' if required
if (fullfilename[fullfilename.length() - 1] != '/') {
fullfilename += "/";
}
#endif
#endif
fullfilename += "startup.msg";
FILE *fp = fopen(fullfilename.c_str(), "r");
if (fp) {
GriString inLine(128);
while (!inLine.line_from_FILE(fp)) {
ShowStr(inLine.getValue());
}
fclose(fp);
}
}
// write_prompt - write a prompt if keyboard input
void
write_prompt()
{
if (!_cmdFILE.back().get_interactive())
return;
// Write prompt if reading from keyboard
if (_first == true) {
#if 0
extern char _gri_number[], _gri_date[];
// On very first call, print the opening message.
sprintf(_grTempString, "\
gri - scientific graphic program (version %s)\n", _gri_number);
gr_textput(_grTempString);
sprintf(_grTempString, "\
Copyright %s by Dan E. Kelley. All rights reserved.\n",
_gri_date);
gr_textput("\
http://phys.ocean.dal.ca/~kelley/gri/gri1.html\n");
gr_textput(_grTempString);
sprintf(_grTempString, "\
Type `help' for a list of commands\n");
gr_textput(_grTempString);
gr_textput(_prompt.c_str());
#else
extern bool _no_startup_message;
if (!_no_startup_message)
show_startup_msg();
gr_textput(_prompt.c_str());
#endif
_first = false;
} else {
gr_textput(_prompt.c_str());
}
}
// remove_comment() -- fix command line 1) check that input line read OK 2)
// remove the '\n' from fgets 3) remove trailing comments 4) remove trailing
// blanks or tabs
//
// Return true if there WAS a comment and it was the FIRST non-whitespace thing.
bool
remove_comment(char *s)
{
//printf("\tremove_comment(%s)\n",s);
int len = strlen(s);
#if 0
// Discard trailing newlines (or control-M characters, which
// are added to newline in PC-ish systems), by converting
// them to nulls
while (len > 1 && (s[len - 1] == '\n' || s[len - 1] == '\r'))
s[--len] = '\0';
#endif
bool is_continued = false;
if (len > 1 && s[len - 1] == '\\' && s[len - 2] == '\\')
is_continued = true;
// Discard comment on end
if (len > 0) {
bool in_dquote = false;
bool in_squote = false;
for (int i = 0; i < len; i++) {
if (s[i] == '"') {
if (!in_squote)
in_dquote = !in_dquote;
continue;
}
if (s[i] == '\'') {
if (!in_dquote)
in_squote = !in_squote;
continue;
}
if (!in_dquote
&& !in_squote
&& ((s[i] == '/' && s[i+1] == '/') || s[i] == '#')) {
//printf("remove_comment [%s] ->\n", s);
s[i] = '\0';
//printf(" [%s]\n", s);
if (is_continued) {
s[i++] = '\\';
s[i++] = '\\';
}
len = i;
break;
}
}
// Set a flag if there is now nothing but whitespace.
for (int ii = 0; ii < len; ii++) {
//printf("\tEXAMINE [%c]\n", s[ii]);
if (!isspace(s[ii])) {
//printf("\t\tRETURNING false [%s]\n", s);
return false;
}
}
//printf("\t\tRETURNING true [%s]\n", s);
return true;
}
//printf("\t\tRETURNING BOTTOM false [%s]\n", s);
return false;
}
static void
check_usage(const char *s)
{
if (s[0] == '`')
return; // defining new command
#if 0 // 2.5.5 allows e.g \.argv[0].
register int i, len;
int inquote = 0;
len = strlen(s);
for (i = 0; i < len; i++) {
if (s[i] == '"')
inquote = !inquote;
if (!inquote && s[i] == '[' && !(i == 0 || s[i - 1] == '\\')) {
sprintf(_grTempString, "\
Warning: '[' character found in command. This character is in the\n\
manual to indicate optional items, and is not allowed in commands\n\
except inside system calls\n\
Command: '%s'\n", s);
ShowStr(_grTempString);
sprintf(_grTempString, "\
");
ShowStr(_grTempString);
int j;
for (j = 0; j <= i; j++) {
_grTempString[j] = ' ';
}
_grTempString[j] = '\0';
strcat(_grTempString, "^ Bad character\n");
ShowStr(_grTempString);
}
}
#endif
}
#if USE_BACKTIC
// Substitute backtic style system expressions, as in Bourne and
// Bourne-again shells. Assume string 'out' is long enough.
static bool
sub_backtic(const char *in, char *out)
{
#if !defined(HAVE_POPEN)
err("Cannot substitute backtics because computer lacks popen() C subroutine");
#else
int len = strlen(in);
int out_index = 0;
if (len < 2) {
strcpy(out, in);
return true;
}
char *cmd = new char[LineLength];
if (!cmd) OUT_OF_MEMORY;
for (int i = 0; i < len; i++) {
if (in[i] == '`') {
// Search for closing backtic
for (int j = i + 1; j < len; j++) {
if (in[j] == '`') {
strcpy(cmd, in + i + 1);
cmd[j - i - 1] = '\0';
if (((unsigned) superuser()) & FLAG_SYS) {
ShowStr("The `` mechanism is sending this to the OS:\n");
ShowStr(cmd);
ShowStr("\n");
}
FILE *pipefile = (FILE *) popen(cmd, "r");
if (pipefile) {
char *result = new char[LineLength];
if (!result) OUT_OF_MEMORY;
char *thisline = new char[LineLength];
if (!thisline) OUT_OF_MEMORY;
strcpy(result, "");
while (NULL != fgets(thisline, LineLength_1, pipefile))
strcat(result, thisline);
pclose(pipefile);
// Skip null and possible final newline
int len_result = strlen(result);
if (result[len_result - 1] == '\n')
len_result--;
for (int k = 0; k < len_result; k++)
out[out_index++] = result[k];
delete [] result;
delete [] thisline;
} else {
err("The `` system call failed. Cannot access system.");
delete [] cmd;
return false;
}
i = j;
break;
} else {
if (j == len - 1) {
// If got to end, then was not a backtic
// command after all, so copy the input
strcpy(out, in);
delete [] cmd;
return true;
}
}
}
} else {
out[out_index++] = in[i];
}
} // i;
out[out_index] = '\0';
delete [] cmd;
return true;
#endif
}
#endif
// Substitute $() style system expressions, as in Bourne and
// Bourne-again shells. Assume string 'out' is long enough.
static bool
sub_dollar_paren(const char *in, char *out)
{
unsigned int len = strlen(in);
if (len < 3) {
strcpy(out, in);
return true;
}
out[0] = '\0'; // so can strcat onto it
GriString in_copy(in);
bool inserted_something = false;
while (1) {
std::vector<int> start; // where \$( sequences start
std::vector<int> depth; // depth of these sequences
int level = 0, max_level = 0;
unsigned int i;
for (i = 3; i < len; i++) {
if (in_copy[i] == '('
&& in_copy[i - 1] == '$'
&& in_copy[i - 2] == '\\') {
start.push_back(i - 2);
depth.push_back(++level);
} else if (in_copy[i] == ')' && in_copy[i-1] != '\\')
level--;
if (level > max_level)
max_level = level;
}
if (max_level == 0)
break;
for (i = 0; i < start.size(); i++) {
if (depth[i] == max_level) {
inserted_something = true;
// Process this one, the left-most maximumally nested case
char res[1024]; // hope enough
int skip = dollar_paren(in_copy.getValue() + start[i], res);
GriString tmp(in_copy.size() + strlen(res) + 1); // long enough
strncpy(tmp.getValue(), in_copy.getValue(), start[i]);
tmp[start[i]] = '\0'; // trim
tmp.catSTR(res);
tmp.catSTR(in_copy.getValue() + start[i] + skip);
in_copy.fromSTR(tmp.getValue());
for (i = 0; i < start.size(); i++) {
start.pop_back();
depth.pop_back();
}
break;
}
}
}
if (inserted_something == false)
strcpy(out, in);
else
strcpy(out, in_copy.getValue());
return true;
}
// Evaluate a single \$(CMD) sequence, *assumed* to not be nested.
//
// On input, 's' points to the starting backslash.
// On output, 'res' holds the result and the return value indicates
// the how many characters to skip in the input string, to
// get to the matching ) character.
//
// BUG: 'res' is *assumed* to be long enough to hold system output
static int
dollar_paren(const char *s, char *res)
{
#if !defined(HAVE_POPEN)
err("Cannot do \\$(CMD) because computer lacks popen() C subroutine");
return 0;
#else
// Search for closing paren
res[0] = '\0'; // so can cat onto it
GriString ss(s + 3); // so can insert null-terminate within
unsigned int i;
for (i = 0; i < ss.size(); i++) {
if (ss[i] == ')') {
ss[i] = '\0'; // cut closing paren
if (((unsigned) superuser()) & FLAG_SYS) {
ShowStr("The $() mechanism is sending this to the OS:\n");
ShowStr(ss.getValue());
ShowStr("\n");
}
FILE *pipefile = (FILE *) popen(ss.getValue(), "r");
if (!pipefile) {
err("The $() system call failed. Cannot access system.");
return -1;
}
char *thisline = new char[LineLength];
if (!thisline) OUT_OF_MEMORY;
while (NULL != fgets(thisline, LineLength_1, pipefile))
strcat(res, thisline);
pclose(pipefile);
remove_trailing_blanks(res);
delete [] thisline;
break; // done with this system-cmd
} else if (i == ss.size() - 1) {
err("Got to end-of-line with no ')' to match '\\$('");
return -1;
}
}
return int(i + 4); // 4 chars in embracing sequence
#endif
}
// expand_blanks() -- place 1 blank before each math token
void
expand_blanks(char *s)
{
int inquote = 0;
char *sp; // points to src
char *cp; // points to modified copy
char last = '\0'; // last character
sp = s;
cp = _grTempString;
while (*sp != '\0') {
if (*sp == '"') {
if (inquote)
inquote--;
else
inquote++;
}
#if 1 // 2.060
// Handle special case of synonym name with brace,
// e.g. \{some name} or \{time:unit} (as in netCDF)
if (*sp == '{' && last == '\\') {
do
*cp++ = *sp++;
while (*sp != '}' && *sp && *sp != '\n');
*cp++ = *sp++;
last = *sp;
continue;
}
#endif
// Handle e.g. ==, _-, <=, etc
if (!inquote
&& *(sp+1) == '='
&& (*sp == '='
|| *sp == '_'
|| *sp == '^'
|| *sp == '<'
|| *sp == '>'
|| *sp == '!'
|| *sp == '/' )) {
*cp++ = ' '; // insert space before
*cp++ = *sp++; // the prefix char
*cp++ = *sp; // the '=' char
*cp++ = ' '; // insert space after
} else if (!inquote
&& *sp == '=' && *(sp + 1) == '"') {
// e.g. read columns x="lon"
*cp++ = ' ';
*cp++ = *sp++;
*cp++ = ' ';
*cp++ = *sp;
inquote++;
} else if (!inquote
&& (*sp == '+' || *sp == '-')
&& (last != 'e'
&& last != 'E'
&& last != 'd'
&& last != 'D')) {
*cp++ = ' ';
*cp++ = *sp;
if (*(sp + 1) == '=') { // += or -=
*cp++ = '=';
sp++;
} else if (!isdigit(*(sp + 1)) && *(sp + 1) != '.') {
// No extra space if next is a number
*cp++ = ' '; // modified 20 Apr 1995, vsn 2.036
}
} else if (!inquote
&& ( *sp == '{'
|| *sp == '}'
|| *sp == '!'
|| *sp == ',')) {
*cp++ = ' ';
*cp++ = *sp;
*cp++ = ' ';
} else {
*cp++ = *sp;
}
last = *sp;
sp++;
}
*cp = '\0';
strcpy(s, _grTempString);
}
bool
superuserCmd()
{
PUT_VAR("..superuser..", 1.0);
return true;
}
bool
unsuperuserCmd()
{
PUT_VAR("..superuser..", 0.0);
return true;
}
// Get command line from file, storing result in null-terminated string (even
// if EOF). The line is considered to end at a NEWLINE.
// Return true if got EOF
bool
get_cmd(char *buf, int max, FILE *fp)
{
int i = 0;
int thisc, lastc = 0;
bool in_quote = false;
// Scan characters one by one
do {
thisc = fgetc(fp);
if (thisc == '"' && lastc != '\\')
in_quote = in_quote ? false : true;
// Check for EOF
if (thisc == EOF) {
*(buf + i) = '\0';
if (((unsigned) superuser()) & FLAG_AUT2) printf("%s:%d get_cmd hit EOF, now returning TRUE with [%s]\n",__FILE__,__LINE__,buf);
return true;
}
// See if NEWLINE (even if quoted)
if (thisc == '\n') {
// Is newline to be ignored, for continuation?
if (lastc == '\\') {
i -= 2;
_cmdFILE.back().increment_line();
continue;
} else {
*(buf + i) = '\0';
if (((unsigned) superuser()) & FLAG_AUT2) printf("%s:%d get_cmd IN MIDDLE returning FALSE with [%s]\n",__FILE__,__LINE__,buf);
return false;
}
}
// Assign ordinary character
*(buf + i) = thisc;
lastc = thisc;
} while (i++ < max);
*(buf + i - 1) = '\0'; // didn't get to end - bad
printf("%s:%d get_cmd AT END returning FALSE with [%s]\n",__FILE__,__LINE__,buf);
return false;
}
|