@@ -14,43 +14,66 @@ bool str_startswith_word(const char *str, const char *head) {
1414 return head [i ] == '\0' && (str [i ] == '\0' || !unichar_isalpha (str [i ]));
1515}
1616
17- bool mp_repl_is_compound_stmt (const char * line ) {
18- // compound if line starts with a certain keyword
19- if (
20- str_startswith_word (line , "if" )
21- || str_startswith_word (line , "while" )
22- || str_startswith_word (line , "for" )
23- || str_startswith_word (line , "try" )
24- || str_startswith_word (line , "with" )
25- || str_startswith_word (line , "def" )
26- || str_startswith_word (line , "class" )
27- || str_startswith_word (line , "@" )
28- ) {
29- return true;
17+ bool mp_repl_continue_with_input (const char * input ) {
18+ // check for blank input
19+ if (input [0 ] == '\0' ) {
20+ return false;
3021 }
3122
32- // also "compound" if unmatched open bracket or triple quote
23+ // check if input starts with a certain keyword
24+ bool starts_with_compound_keyword =
25+ input [0 ] == '@'
26+ || str_startswith_word (input , "if" )
27+ || str_startswith_word (input , "while" )
28+ || str_startswith_word (input , "for" )
29+ || str_startswith_word (input , "try" )
30+ || str_startswith_word (input , "with" )
31+ || str_startswith_word (input , "def" )
32+ || str_startswith_word (input , "class" )
33+ ;
34+
35+ // check for unmatched open bracket or triple quote
36+ // TODO don't look at triple quotes inside single quotes
3337 int n_paren = 0 ;
3438 int n_brack = 0 ;
3539 int n_brace = 0 ;
3640 int in_triple_quote = 0 ;
37- for (const char * l = line ; * l ; l ++ ) {
38- switch (* l ) {
41+ const char * i ;
42+ for (i = input ; * i ; i ++ ) {
43+ switch (* i ) {
3944 case '(' : n_paren += 1 ; break ;
4045 case ')' : n_paren -= 1 ; break ;
4146 case '[' : n_brack += 1 ; break ;
4247 case ']' : n_brack -= 1 ; break ;
4348 case '{' : n_brace += 1 ; break ;
4449 case '}' : n_brace -= 1 ; break ;
50+ case '\'' :
51+ if (in_triple_quote != '"' && i [1 ] == '\'' && i [2 ] == '\'' ) {
52+ i += 2 ;
53+ in_triple_quote = '\'' - in_triple_quote ;
54+ }
55+ break ;
4556 case '"' :
46- if (l [1 ] == '"' && l [2 ] == '"' ) {
47- l += 2 ;
48- in_triple_quote = 1 - in_triple_quote ;
57+ if (in_triple_quote != '\'' && i [1 ] == '"' && i [2 ] == '"' ) {
58+ i += 2 ;
59+ in_triple_quote = '"' - in_triple_quote ;
4960 }
5061 break ;
5162 }
5263 }
53- return n_paren > 0 || n_brack > 0 || n_brace > 0 || in_triple_quote != 0 ;
64+
65+ // continue if unmatched brackets or quotes
66+ if (n_paren > 0 || n_brack > 0 || n_brace > 0 || in_triple_quote != 0 ) {
67+ return true;
68+ }
69+
70+ // continue if compound keyword and last line was not empty
71+ if (starts_with_compound_keyword && i [-1 ] != '\n' ) {
72+ return true;
73+ }
74+
75+ // otherwise, don't continue
76+ return false;
5477}
5578
5679#endif // MICROPY_ENABLE_REPL_HELPERS
0 commit comments