1 /*
2 ** cmd_for.c - Loopy logic.
3 **
4 ** Copyright (C) 1999 by Scott C. Gray
5 **
6 ** This program is free software; you can redistribute it and/or modify
7 ** it under the terms of the GNU General Public License as published by
8 ** the Free Software Foundation; either version 2 of the License, or
9 ** (at your option) any later version.
10 **
11 ** This program is distributed in the hope that it will be useful,
12 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ** GNU General Public License for more details.
15 **
16 ** You should have received a copy of the GNU General Public License
17 ** along with this program. If not, write to the Free Software
18 ** Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
19 **
20 ** You may contact the author :
21 ** e-mail: gray@voicenet.com
22 ** grays@xtend-tech.com
23 ** gray@xenotropic.com
24 */
25 #include <stdio.h>
26 #include <ctype.h>
27 #include <setjmp.h>
28 #include <sys/stat.h>
29 #include "sqsh_config.h"
30 #include "sqsh_global.h"
31 #include "sqsh_expand.h"
32 #include "sqsh_error.h"
33 #include "sqsh_varbuf.h"
34 #include "sqsh_env.h"
35 #include "sqsh_cmd.h"
36 #include "sqsh_job.h"
37 #include "sqsh_sig.h"
38 #include "sqsh_buf.h"
39 #include "sqsh_readline.h"
40 #include "sqsh_getopt.h"
41 #include "sqsh_stdin.h"
42 #include "cmd.h"
43 #include "dsp.h"
44 #include "cmd_misc.h"
45 #include "cmd_input.h"
46
cmd_for(argc,argv)47 int cmd_for( argc, argv )
48 int argc;
49 char *argv[];
50 {
51 varbuf_t *for_buf;
52 int ret;
53 char *var_name;
54 int i;
55
56 /*
57 ** Since we will be temporarily replacing some of our global
58 ** settings, we want to set up a save-point to which we can
59 ** restore when we are done.
60 */
61 env_tran( g_env );
62
63 /*
64 ** Before we go any further, read the reaminder of the input
65 ** from the user (up to \done).
66 */
67 for_buf = varbuf_create( 512 );
68
69 if ((ret = cmd_body_input( for_buf )) != CMD_RESETBUF)
70 {
71 varbuf_destroy( for_buf );
72 env_rollback( g_env );
73 return(ret);
74 }
75
76 /*
77 ** Don't need to protect things any more.
78 */
79 env_rollback( g_env );
80
81 if (argc < 4 || strcmp(argv[2], "in") != 0)
82 {
83 fprintf( stderr, "Use: \\for <variable> in <word> [<word> ...]\n" );
84 varbuf_destroy( for_buf );
85 return(CMD_FAIL);
86 }
87
88 var_name = argv[1];
89
90 for (i = 3; i < argc; i++)
91 {
92 /*
93 ** Set the variable to the current argument.
94 */
95 env_set( g_env, var_name, argv[i] );
96
97 /*
98 ** Redirect stdin to the buffer, then process it.
99 */
100 sqsh_stdin_buffer( varbuf_getstr( for_buf ), -1 );
101 ret = cmd_input();
102 sqsh_stdin_pop();
103
104 if (ret == CMD_FAIL ||
105 ret == CMD_ABORT ||
106 ret == CMD_BREAK ||
107 ret == CMD_RETURN)
108 {
109 varbuf_destroy( for_buf );
110 return(ret);
111 }
112 }
113
114 varbuf_destroy( for_buf );
115 return(CMD_LEAVEBUF);
116 }
117