aboutsummaryrefslogtreecommitdiff
path: root/jim-interactive.c
blob: 00813a71e7f6b3396f4c36b1bdfb3a19d3e8b02c (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
68
69
70
#include "jim.h"
#include <errno.h>

#define MAX_LINE_LEN 512

int Jim_InteractivePrompt(Jim_Interp *interp)
{
    int retcode = JIM_OK;
    Jim_Obj *scriptObjPtr;
    char *buf = Jim_Alloc(MAX_LINE_LEN);

    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) {
        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;

            if (fgets(buf, MAX_LINE_LEN, 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);
        if (retcode == JIM_EXIT) {
            Jim_Free(buf);
            exit(Jim_GetExitCode(interp));
        }
        if (retcode == JIM_ERR) {
            Jim_MakeErrorMessage(interp);
        }
        result = Jim_GetString(Jim_GetResult(interp), &reslen);
        if (reslen) {
            printf("%s\n", result);
        }
    }
  out:
    Jim_Free(buf);
    return 0;
}