@@ -46,20 +46,31 @@ function showButtons() {
4646async function startTerminal (
4747 existing : vscode . Terminal | undefined , name : string , cmd : string
4848) : Promise < vscode . Terminal > {
49+ let terminal : vscode . Terminal | undefined ;
4950 if ( existing ) {
50- existing . dispose ( ) ;
51+ // We try to re-use the existing terminal. But we need to terminate a potentially
52+ // running python process first. If there is no python process, the shell
53+ // complains about the "import sys; sys.exit(0)" command, but we don't care.
54+ if ( ! existing . exitStatus ) {
55+ terminal = existing ;
56+ terminal . sendText ( "import sys; sys.exit(0)" ) ;
57+ } else {
58+ existing . dispose ( ) ;
59+ }
5160 }
52- const terminalOptions : vscode . TerminalOptions = { name : name } ;
53- if ( isWindows ) {
54- // We don't know which shell will be used by default.
55- // If PowerShell is the default, we need to prefix the command with "& ".
56- // Otherwise, the prefix is not allowed and results in a syntax error.
57- // -> Just force cmd.exe.
58- terminalOptions . shellPath = "cmd.exe" ;
61+ if ( ! terminal ) {
62+ const terminalOptions : vscode . TerminalOptions = { name : name } ;
63+ if ( isWindows ) {
64+ // We don't know which shell will be used by default.
65+ // If PowerShell is the default, we need to prefix the command with "& ".
66+ // Otherwise, the prefix is not allowed and results in a syntax error.
67+ // -> Just force cmd.exe.
68+ terminalOptions . shellPath = "cmd.exe" ;
69+ }
70+ terminal = vscode . window . createTerminal ( terminalOptions ) ;
71+ // Sometimes the terminal takes some time to start up before it can start accepting input.
72+ await new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) ) ;
5973 }
60- const terminal = vscode . window . createTerminal ( terminalOptions ) ;
61- // Sometimes the terminal takes some time to start up before it can start accepting input.
62- await new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) ) ;
6374 terminal . show ( false ) ; // focus the terminal
6475 terminal . sendText ( cmd ) ;
6576 return terminal ;
@@ -425,6 +436,16 @@ export async function activate(context: vscode.ExtensionContext) {
425436 disposables . push ( outChannel ) ;
426437
427438 const terminals : { [ name : string ] : TerminalContext } = { } ;
439+ vscode . window . onDidCloseTerminal ( ( t ) => {
440+ // Loop through terminals and delete the entry if it matches the closed terminal
441+ for ( const [ key , termContext ] of Object . entries ( terminals ) ) {
442+ if ( termContext . terminal === t ) {
443+ delete terminals [ key ] ;
444+ console . log ( `Terminal closed and removed from map: ${ t . name } (key: ${ key } )` ) ;
445+ break ;
446+ }
447+ }
448+ } ) ;
428449
429450 installButton ( "Write Your Python Program" , undefined ) ;
430451
0 commit comments