@@ -11,6 +11,7 @@ import (
1111 "os"
1212 "reflect"
1313 "runtime"
14+ "strings"
1415 "sync"
1516 "time"
1617
@@ -467,6 +468,8 @@ func doEval(ir *interp.Interp, code string) (val []interface{}, typ []xreflect.T
467468 }
468469 }()
469470
471+ code = evalSpecialCommands (ir , code )
472+
470473 // Prepare and perform the multiline evaluation.
471474 compiler := ir .Comp
472475
@@ -479,7 +482,7 @@ func doEval(ir *interp.Interp, code string) (val []interface{}, typ []xreflect.T
479482 // Reset the error line so that error messages correspond to the lines from the cell.
480483 compiler .Line = 0
481484
482- // Parse the input code (and don't preform gomacro's macroexpansion).
485+ // Parse the input code (and don't perform gomacro's macroexpansion).
483486 // These may panic but this will be recovered by the deferred recover() above so that the error
484487 // may be returned instead.
485488 nodes := compiler .ParseBytes ([]byte (code ))
@@ -599,3 +602,43 @@ func startHeartbeat(hbSocket Socket, wg *sync.WaitGroup) (shutdown chan struct{}
599602
600603 return quit
601604}
605+
606+ // find and execute special commands in code, remove them from returned string
607+ func evalSpecialCommands (ir * interp.Interp , code string ) string {
608+ lines := strings .Split (code , "\n " )
609+ for i , line := range lines {
610+ line = strings .TrimSpace (line )
611+ if len (line ) != 0 && line [0 ] == '%' {
612+ evalSpecialCommand (ir , line )
613+ lines [i ] = ""
614+ }
615+ }
616+ return strings .Join (lines , "\n " )
617+ }
618+
619+ // execute special command
620+ func evalSpecialCommand (ir * interp.Interp , line string ) {
621+ const help string = "available special commands:\n %go111module {on|off}\n %help"
622+
623+ args := strings .SplitN (line , " " , 2 )
624+ cmd := args [0 ]
625+ arg := ""
626+ if len (args ) > 1 {
627+ arg = args [1 ]
628+ }
629+ switch cmd {
630+
631+ case "%go111module" :
632+ if arg == "on" {
633+ ir .Comp .CompGlobals .Options |= base .OptModuleImport
634+ } else if arg == "off" {
635+ ir .Comp .CompGlobals .Options &^= base .OptModuleImport
636+ } else {
637+ panic (fmt .Errorf ("special command %s: expecting a single argument 'on' or 'off', found: %q" , cmd , arg ))
638+ }
639+ case "%help" :
640+ panic (help )
641+ default :
642+ panic (fmt .Errorf ("unknown special command: %q\n %s" , line , help ))
643+ }
644+ }
0 commit comments