aboutsummaryrefslogtreecommitdiff
path: root/jim-interactive.c
blob: d4272c55759ab315ac06230757324e2c47ee5074 (plain)
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
#include <jim.h>
#include <errno.h>

int Jim_InteractivePrompt(Jim_Interp *interp)
{
    int retcode = JIM_OK;
    Jim_Obj *scriptObjPtr;

    printf("Welcome to Jim version %d.%d, "
           "Copyright (c) 2005-8 Salvatore Sanfilippo" JIM_NL,
           JIM_VERSION / 100, JIM_VERSION % 100);
     Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, "1");
    while (1) {
        char buf[1024];
        const char *result;
        int reslen;

        if (retcode != 0) {
            const char *retcodestr = Jim_ReturnCode(retcode);
            if (*retcodestr == '?') {
                printf("[%d] . ", retcode);
            }
            else {
                printf("[%s] . ", retcodestr);
            }
        } else
            printf(". ");
        fflush(stdout);
        scriptObjPtr = Jim_NewStringObj(interp, "", 0);
        Jim_IncrRefCount(scriptObjPtr);
        while(1) {
            const char *str;
            char state;
            int len;

            errno = 0;
            if ( fgets(buf, 1024, stdin) == NULL) {
                if (errno == EINTR) {
                    continue;
                }
                Jim_DecrRefCount(interp, scriptObjPtr);
                goto out;
            }
            Jim_AppendString(interp, scriptObjPtr, buf, -1);
            str = Jim_GetString(scriptObjPtr, &len);
            if (Jim_ScriptIsComplete(str, len, &state))
                break;
            printf("%c> ", state);
            fflush(stdout);
        }
        retcode = Jim_EvalObj(interp, scriptObjPtr);
        Jim_DecrRefCount(interp, scriptObjPtr);
        result = Jim_GetString(Jim_GetResult(interp), &reslen);
        if (retcode == JIM_ERR) {
            Jim_PrintErrorMessage(interp);
        } else if (retcode == JIM_EXIT) {
            exit(Jim_GetExitCode(interp));
        } else {
            if (reslen) {
                printf("%s\n", result);
            }
        }
    }
out:
    return 0;
}