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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
use crate::{
    completions::NuCompleter,
    prompt_update,
    reedline_config::{add_menus, create_keybindings, KeybindingsMode},
    util::eval_source,
    NuHighlighter, NuValidator, NushellPrompt,
};
use crossterm::cursor::SetCursorStyle;
use log::{trace, warn};
use miette::{ErrReport, IntoDiagnostic, Result};
use nu_cmd_base::util::get_guaranteed_cwd;
use nu_cmd_base::{hook::eval_hook, util::get_editor};
use nu_color_config::StyleComputer;
use nu_engine::{convert_env_values, env_to_strings};
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::{
    config::NuCursorShape,
    engine::{EngineState, Stack, StateWorkingSet},
    eval_const::create_nu_constant,
    report_error_new, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned,
    Value, NU_VARIABLE_ID,
};
use nu_utils::utils::perf;
use reedline::{
    CursorConfig, CwdAwareHinter, EditCommand, Emacs, FileBackedHistory, HistorySessionId,
    Reedline, SqliteBackedHistory, Vi,
};
use std::{
    env::temp_dir,
    io::{self, IsTerminal, Write},
    path::PathBuf,
    sync::atomic::Ordering,
    time::{Duration, Instant},
};
use sysinfo::System;

// According to Daniel Imms @Tyriar, we need to do these this way:
// <133 A><prompt><133 B><command><133 C><command output>
// These first two have been moved to prompt_update to get as close as possible to the prompt.
// const PRE_PROMPT_MARKER: &str = "\x1b]133;A\x1b\\";
// const POST_PROMPT_MARKER: &str = "\x1b]133;B\x1b\\";
const PRE_EXECUTE_MARKER: &str = "\x1b]133;C\x1b\\";
// This one is in get_command_finished_marker() now so we can capture the exit codes properly.
// const CMD_FINISHED_MARKER: &str = "\x1b]133;D;{}\x1b\\";
const RESET_APPLICATION_MODE: &str = "\x1b[?1l";

///
/// The main REPL loop, including spinning up the prompt itself.
///
pub fn evaluate_repl(
    engine_state: &mut EngineState,
    stack: &mut Stack,
    nushell_path: &str,
    prerun_command: Option<Spanned<String>>,
    load_std_lib: Option<Spanned<String>>,
    entire_start_time: Instant,
) -> Result<()> {
    use nu_cmd_base::hook;
    use reedline::Signal;
    let config = engine_state.get_config();
    let use_color = config.use_ansi_coloring;

    confirm_stdin_is_terminal()?;

    let mut entry_num = 0;

    let mut nu_prompt = NushellPrompt::new(config.shell_integration);

    let start_time = std::time::Instant::now();
    // Translate environment variables from Strings to Values
    if let Some(e) = convert_env_values(engine_state, stack) {
        report_error_new(engine_state, &e);
    }
    perf(
        "translate env vars",
        start_time,
        file!(),
        line!(),
        column!(),
        use_color,
    );

    // seed env vars
    stack.add_env_var(
        "CMD_DURATION_MS".into(),
        Value::string("0823", Span::unknown()),
    );

    stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown()));

    let mut start_time = std::time::Instant::now();
    let mut line_editor = Reedline::create();
    let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4()));

    // Now that reedline is created, get the history session id and store it in engine_state
    store_history_id_in_engine(engine_state, &line_editor);
    perf(
        "setup reedline",
        start_time,
        file!(),
        line!(),
        column!(),
        use_color,
    );

    if let Some(history) = engine_state.history_config() {
        start_time = std::time::Instant::now();

        line_editor = setup_history(nushell_path, engine_state, line_editor, history)?;

        perf(
            "setup history",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );
    }

    if let Some(s) = prerun_command {
        eval_source(
            engine_state,
            stack,
            s.item.as_bytes(),
            &format!("entry #{entry_num}"),
            PipelineData::empty(),
            false,
        );
        engine_state.merge_env(stack, get_guaranteed_cwd(engine_state, stack))?;
    }

    engine_state.set_startup_time(entire_start_time.elapsed().as_nanos() as i64);

    // Regenerate the $nu constant to contain the startup time and any other potential updates
    let nu_const = create_nu_constant(engine_state, Span::unknown())?;
    engine_state.set_variable_const_val(NU_VARIABLE_ID, nu_const);

    if load_std_lib.is_none() && engine_state.get_config().show_banner {
        eval_source(
            engine_state,
            stack,
            r#"use std banner; banner"#.as_bytes(),
            "show_banner",
            PipelineData::empty(),
            false,
        );
    }

    kitty_protocol_healthcheck(engine_state);

    loop {
        let loop_start_time = std::time::Instant::now();

        let cwd = get_guaranteed_cwd(engine_state, stack);

        start_time = std::time::Instant::now();
        // Before doing anything, merge the environment from the previous REPL iteration into the
        // permanent state.
        if let Err(err) = engine_state.merge_env(stack, cwd) {
            report_error_new(engine_state, &err);
        }
        perf(
            "merge env",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        //Reset the ctrl-c handler
        if let Some(ctrlc) = &mut engine_state.ctrlc {
            ctrlc.store(false, Ordering::SeqCst);
        }
        perf(
            "reset ctrlc",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        let config = engine_state.get_config();

        let engine_reference = std::sync::Arc::new(engine_state.clone());

        // Find the configured cursor shapes for each mode
        let cursor_config = CursorConfig {
            vi_insert: map_nucursorshape_to_cursorshape(config.cursor_shape_vi_insert),
            vi_normal: map_nucursorshape_to_cursorshape(config.cursor_shape_vi_normal),
            emacs: map_nucursorshape_to_cursorshape(config.cursor_shape_emacs),
        };
        perf(
            "get config/cursor config",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();

        line_editor = line_editor
            .use_kitty_keyboard_enhancement(config.use_kitty_protocol)
            // try to enable bracketed paste
            // It doesn't work on windows system: https://github.com/crossterm-rs/crossterm/issues/737
            .use_bracketed_paste(cfg!(not(target_os = "windows")) && config.bracketed_paste)
            .with_highlighter(Box::new(NuHighlighter {
                engine_state: engine_reference.clone(),
                stack: std::sync::Arc::new(stack.clone()),
                config: config.clone(),
            }))
            .with_validator(Box::new(NuValidator {
                engine_state: engine_reference.clone(),
            }))
            .with_completer(Box::new(NuCompleter::new(
                engine_reference.clone(),
                stack.clone(),
            )))
            .with_quick_completions(config.quick_completions)
            .with_partial_completions(config.partial_completions)
            .with_ansi_colors(config.use_ansi_coloring)
            .with_cursor_config(cursor_config);
        perf(
            "reedline builder",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        let style_computer = StyleComputer::from_config(engine_state, stack);

        start_time = std::time::Instant::now();
        line_editor = if config.use_ansi_coloring {
            line_editor.with_hinter(Box::new({
                // As of Nov 2022, "hints" color_config closures only get `null` passed in.
                let style = style_computer.compute("hints", &Value::nothing(Span::unknown()));
                CwdAwareHinter::default().with_style(style)
            }))
        } else {
            line_editor.disable_hints()
        };
        perf(
            "reedline coloring/style_computer",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        line_editor = add_menus(line_editor, engine_reference, stack, config).unwrap_or_else(|e| {
            report_error_new(engine_state, &e);
            Reedline::create()
        });
        perf(
            "reedline menus",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        let buffer_editor = get_editor(engine_state, stack, Span::unknown());

        line_editor = if let Ok((cmd, args)) = buffer_editor {
            let mut command = std::process::Command::new(&cmd);
            command
                .args(args)
                .envs(env_to_strings(engine_state, stack)?);
            line_editor.with_buffer_editor(command, temp_file.clone())
        } else {
            line_editor
        };
        perf(
            "reedline buffer_editor",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        if let Some(history) = engine_state.history_config() {
            start_time = std::time::Instant::now();
            if history.sync_on_enter {
                if let Err(e) = line_editor.sync_history() {
                    warn!("Failed to sync history: {}", e);
                }
            }
            perf(
                "sync_history",
                start_time,
                file!(),
                line!(),
                column!(),
                use_color,
            );
        }

        start_time = std::time::Instant::now();
        // Changing the line editor based on the found keybindings
        line_editor = setup_keybindings(engine_state, line_editor);
        perf(
            "keybindings",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        // Right before we start our prompt and take input from the user,
        // fire the "pre_prompt" hook
        if let Some(hook) = config.hooks.pre_prompt.clone() {
            if let Err(err) = eval_hook(engine_state, stack, None, vec![], &hook, "pre_prompt") {
                report_error_new(engine_state, &err);
            }
        }
        perf(
            "pre-prompt hook",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        // Next, check all the environment variables they ask for
        // fire the "env_change" hook
        let config = engine_state.get_config();
        if let Err(error) =
            hook::eval_env_change_hook(config.hooks.env_change.clone(), engine_state, stack)
        {
            report_error_new(engine_state, &error)
        }
        perf(
            "env-change hook",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        start_time = std::time::Instant::now();
        let config = &engine_state.get_config().clone();
        prompt_update::update_prompt(config, engine_state, stack, &mut nu_prompt);
        let transient_prompt =
            prompt_update::make_transient_prompt(config, engine_state, stack, &nu_prompt);
        perf(
            "update_prompt",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        entry_num += 1;

        start_time = std::time::Instant::now();
        line_editor = line_editor.with_transient_prompt(transient_prompt);
        let input = line_editor.read_line(&nu_prompt);
        let shell_integration = config.shell_integration;

        match input {
            Ok(Signal::Success(s)) => {
                let hostname = System::host_name();
                let history_supports_meta = matches!(
                    engine_state.history_config().map(|h| h.file_format),
                    Some(HistoryFileFormat::Sqlite)
                );

                if history_supports_meta {
                    prepare_history_metadata(&s, &hostname, engine_state, &mut line_editor)?;
                }

                // Right before we start running the code the user gave us, fire the `pre_execution`
                // hook
                if let Some(hook) = config.hooks.pre_execution.clone() {
                    // Set the REPL buffer to the current command for the "pre_execution" hook
                    let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
                    repl.buffer = s.to_string();
                    drop(repl);

                    if let Err(err) =
                        eval_hook(engine_state, stack, None, vec![], &hook, "pre_execution")
                    {
                        report_error_new(engine_state, &err);
                    }
                }

                let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
                repl.cursor_pos = line_editor.current_insertion_point();
                repl.buffer = line_editor.current_buffer_contents().to_string();
                drop(repl);

                if shell_integration {
                    run_ansi_sequence(PRE_EXECUTE_MARKER)?;
                }

                // Actual command execution logic starts from here
                let start_time = Instant::now();

                match parse_operation(s.clone(), engine_state, stack)? {
                    ReplOperation::AutoCd { cwd, target, span } => {
                        do_auto_cd(target, cwd, stack, engine_state, span);
                    }
                    ReplOperation::RunCommand(cmd) => {
                        line_editor = do_run_cmd(
                            &cmd,
                            stack,
                            engine_state,
                            line_editor,
                            shell_integration,
                            entry_num,
                        )?;
                    }
                    // as the name implies, we do nothing in this case
                    ReplOperation::DoNothing => {}
                }

                let cmd_duration = start_time.elapsed();

                stack.add_env_var(
                    "CMD_DURATION_MS".into(),
                    Value::string(format!("{}", cmd_duration.as_millis()), Span::unknown()),
                );

                if history_supports_meta {
                    fill_in_result_related_history_metadata(
                        &s,
                        engine_state,
                        cmd_duration,
                        stack,
                        &mut line_editor,
                    )?;
                }

                if shell_integration {
                    do_shell_integration_finalize_command(hostname, engine_state, stack)?;
                }

                flush_engine_state_repl_buffer(engine_state, &mut line_editor);
            }
            Ok(Signal::CtrlC) => {
                // `Reedline` clears the line content. New prompt is shown
                if shell_integration {
                    run_ansi_sequence(&get_command_finished_marker(stack, engine_state))?;
                }
            }
            Ok(Signal::CtrlD) => {
                // When exiting clear to a new line
                if shell_integration {
                    run_ansi_sequence(&get_command_finished_marker(stack, engine_state))?;
                }
                println!();
                break;
            }
            Err(err) => {
                let message = err.to_string();
                if !message.contains("duration") {
                    eprintln!("Error: {err:?}");
                    // TODO: Identify possible error cases where a hard failure is preferable
                    // Ignoring and reporting could hide bigger problems
                    // e.g. https://github.com/nushell/nushell/issues/6452
                    // Alternatively only allow that expected failures let the REPL loop
                }
                if shell_integration {
                    run_ansi_sequence(&get_command_finished_marker(stack, engine_state))?;
                }
            }
        }
        perf(
            "processing line editor input",
            start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );

        perf(
            "finished repl loop",
            loop_start_time,
            file!(),
            line!(),
            column!(),
            use_color,
        );
    }

    Ok(())
}

///
/// Put in history metadata not related to the result of running the command
///
fn prepare_history_metadata(
    s: &str,
    hostname: &Option<String>,
    engine_state: &EngineState,
    line_editor: &mut Reedline,
) -> Result<()> {
    if !s.is_empty() && line_editor.has_last_command_context() {
        line_editor
            .update_last_command_context(&|mut c| {
                c.start_timestamp = Some(chrono::Utc::now());
                c.hostname = hostname.clone();

                c.cwd = Some(StateWorkingSet::new(engine_state).get_cwd());
                c
            })
            .into_diagnostic()?; // todo: don't stop repl if error here?
    }
    Ok(())
}

///
/// Fills in history item metadata based on the execution result (notably duration and exit code)
///
fn fill_in_result_related_history_metadata(
    s: &str,
    engine_state: &EngineState,
    cmd_duration: Duration,
    stack: &mut Stack,
    line_editor: &mut Reedline,
) -> Result<()> {
    if !s.is_empty() && line_editor.has_last_command_context() {
        line_editor
            .update_last_command_context(&|mut c| {
                c.duration = Some(cmd_duration);
                c.exit_status = stack
                    .get_env_var(engine_state, "LAST_EXIT_CODE")
                    .and_then(|e| e.as_i64().ok());
                c
            })
            .into_diagnostic()?; // todo: don't stop repl if error here?
    }
    Ok(())
}

/// The kinds of operations you can do in a single loop iteration of the REPL
enum ReplOperation {
    /// "auto-cd": change directory by typing it in directly
    AutoCd {
        /// the current working directory
        cwd: String,
        /// the target
        target: PathBuf,
        /// span information for debugging
        span: Span,
    },
    /// run a command
    RunCommand(String),
    /// do nothing (usually through an empty string)
    DoNothing,
}

///
/// Parses one "REPL line" of input, to try and derive intent.
/// Notably, this is where we detect whether the user is attempting an
/// "auto-cd" (writing a relative path directly instead of `cd path`)
///
/// Returns the ReplOperation we believe the user wants to do
///
fn parse_operation(
    s: String,
    engine_state: &EngineState,
    stack: &Stack,
) -> Result<ReplOperation, ErrReport> {
    let tokens = lex(s.as_bytes(), 0, &[], &[], false);
    // Check if this is a single call to a directory, if so auto-cd
    let cwd = nu_engine::env::current_dir_str(engine_state, stack)?;
    let mut orig = s.clone();
    if orig.starts_with('`') {
        orig = trim_quotes_str(&orig).to_string()
    }

    let path = nu_path::expand_path_with(&orig, &cwd);
    if looks_like_path(&orig) && path.is_dir() && tokens.0.len() == 1 {
        Ok(ReplOperation::AutoCd {
            cwd,
            target: path,
            span: tokens.0[0].span,
        })
    } else if !s.trim().is_empty() {
        Ok(ReplOperation::RunCommand(s))
    } else {
        Ok(ReplOperation::DoNothing)
    }
}

///
/// Execute an "auto-cd" operation, changing the current working directory.
///
fn do_auto_cd(
    path: PathBuf,
    cwd: String,
    stack: &mut Stack,
    engine_state: &mut EngineState,
    span: Span,
) {
    let path = {
        if !path.exists() {
            report_error_new(
                engine_state,
                &ShellError::DirectoryNotFound {
                    dir: path.to_string_lossy().to_string(),
                    span,
                },
            );
        }
        let path = nu_path::canonicalize_with(path, &cwd)
            .expect("internal error: cannot canonicalize known path");
        path.to_string_lossy().to_string()
    };

    stack.add_env_var("OLDPWD".into(), Value::string(cwd.clone(), Span::unknown()));

    //FIXME: this only changes the current scope, but instead this environment variable
    //should probably be a block that loads the information from the state in the overlay
    stack.add_env_var("PWD".into(), Value::string(path.clone(), Span::unknown()));
    let cwd = Value::string(cwd, span);

    let shells = stack.get_env_var(engine_state, "NUSHELL_SHELLS");
    let mut shells = if let Some(v) = shells {
        v.as_list()
            .map(|x| x.to_vec())
            .unwrap_or_else(|_| vec![cwd])
    } else {
        vec![cwd]
    };

    let current_shell = stack.get_env_var(engine_state, "NUSHELL_CURRENT_SHELL");
    let current_shell = if let Some(v) = current_shell {
        v.as_int().unwrap_or_default() as usize
    } else {
        0
    };

    let last_shell = stack.get_env_var(engine_state, "NUSHELL_LAST_SHELL");
    let last_shell = if let Some(v) = last_shell {
        v.as_int().unwrap_or_default() as usize
    } else {
        0
    };

    shells[current_shell] = Value::string(path, span);

    stack.add_env_var("NUSHELL_SHELLS".into(), Value::list(shells, span));
    stack.add_env_var(
        "NUSHELL_LAST_SHELL".into(),
        Value::int(last_shell as i64, span),
    );
}

///
/// Run a command as received from reedline. This is where we are actually
/// running a thing!
///
fn do_run_cmd(
    s: &str,
    stack: &mut Stack,
    engine_state: &mut EngineState,
    // we pass in the line editor so it can be dropped in the case of a process exit
    // (in the normal case we don't want to drop it so return it as-is otherwise)
    line_editor: Reedline,
    shell_integration: bool,
    entry_num: usize,
) -> Result<Reedline> {
    trace!("eval source: {}", s);

    let mut cmds = s.split_whitespace();
    if let Some("exit") = cmds.next() {
        let mut working_set = StateWorkingSet::new(engine_state);
        let _ = parse(&mut working_set, None, s.as_bytes(), false);

        if working_set.parse_errors.is_empty() {
            match cmds.next() {
                Some(s) => {
                    if let Ok(n) = s.parse::<i32>() {
                        drop(line_editor);
                        std::process::exit(n);
                    }
                }
                None => {
                    drop(line_editor);
                    std::process::exit(0);
                }
            }
        }
    }

    if shell_integration {
        if let Some(cwd) = stack.get_env_var(engine_state, "PWD") {
            let path = cwd.as_string()?;

            // Try to abbreviate string for windows title
            let maybe_abbrev_path = if let Some(p) = nu_path::home_dir() {
                path.replace(&p.as_path().display().to_string(), "~")
            } else {
                path
            };
            let binary_name = s.split_whitespace().next();

            if let Some(binary_name) = binary_name {
                run_ansi_sequence(&format!("\x1b]2;{maybe_abbrev_path}> {binary_name}\x07"))?;
            }
        }
    }

    eval_source(
        engine_state,
        stack,
        s.as_bytes(),
        &format!("entry #{entry_num}"),
        PipelineData::empty(),
        false,
    );

    Ok(line_editor)
}

///
/// Output some things and set environment variables so shells with the right integration
/// can have more information about what is going on (after we have run a command)
///
fn do_shell_integration_finalize_command(
    hostname: Option<String>,
    engine_state: &EngineState,
    stack: &mut Stack,
) -> Result<()> {
    run_ansi_sequence(&get_command_finished_marker(stack, engine_state))?;
    if let Some(cwd) = stack.get_env_var(engine_state, "PWD") {
        let path = cwd.as_string()?;

        // Supported escape sequences of Microsoft's Visual Studio Code (vscode)
        // https://code.visualstudio.com/docs/terminal/shell-integration#_supported-escape-sequences
        if stack.get_env_var(engine_state, "TERM_PROGRAM") == Some(Value::test_string("vscode")) {
            // If we're in vscode, run their specific ansi escape sequence.
            // This is helpful for ctrl+g to change directories in the terminal.
            run_ansi_sequence(&format!("\x1b]633;P;Cwd={}\x1b\\", path))?;
        } else {
            // Otherwise, communicate the path as OSC 7 (often used for spawning new tabs in the same dir)
            run_ansi_sequence(&format!(
                "\x1b]7;file://{}{}{}\x1b\\",
                percent_encoding::utf8_percent_encode(
                    &hostname.unwrap_or_else(|| "localhost".to_string()),
                    percent_encoding::CONTROLS
                ),
                if path.starts_with('/') { "" } else { "/" },
                percent_encoding::utf8_percent_encode(&path, percent_encoding::CONTROLS)
            ))?;
        }

        // Try to abbreviate string for windows title
        let maybe_abbrev_path = if let Some(p) = nu_path::home_dir() {
            path.replace(&p.as_path().display().to_string(), "~")
        } else {
            path
        };

        // Set window title too
        // https://tldp.org/HOWTO/Xterm-Title-3.html
        // ESC]0;stringBEL -- Set icon name and window title to string
        // ESC]1;stringBEL -- Set icon name to string
        // ESC]2;stringBEL -- Set window title to string
        run_ansi_sequence(&format!("\x1b]2;{maybe_abbrev_path}\x07"))?;
    }
    run_ansi_sequence(RESET_APPLICATION_MODE)?;
    Ok(())
}

///
/// Clear the screen and output anything remaining in the EngineState buffer.
///
fn flush_engine_state_repl_buffer(engine_state: &mut EngineState, line_editor: &mut Reedline) {
    let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
    line_editor.run_edit_commands(&[
        EditCommand::Clear,
        EditCommand::InsertString(repl.buffer.to_string()),
        EditCommand::MoveToPosition {
            position: repl.cursor_pos,
            select: false,
        },
    ]);
    repl.buffer = "".to_string();
    repl.cursor_pos = 0;
}

///
/// Setup history management for Reedline
///
fn setup_history(
    nushell_path: &str,
    engine_state: &mut EngineState,
    line_editor: Reedline,
    history: HistoryConfig,
) -> Result<Reedline> {
    // Setup history_isolation aka "history per session"
    let history_session_id = if history.isolation {
        Reedline::create_history_session_id()
    } else {
        None
    };

    if let Some(path) = crate::config_files::get_history_path(nushell_path, history.file_format) {
        return update_line_editor_history(
            engine_state,
            path,
            history,
            line_editor,
            history_session_id,
        );
    };
    Ok(line_editor)
}

///
/// Setup Reedline keybindingds based on the provided config
///
fn setup_keybindings(engine_state: &EngineState, line_editor: Reedline) -> Reedline {
    return match create_keybindings(engine_state.get_config()) {
        Ok(keybindings) => match keybindings {
            KeybindingsMode::Emacs(keybindings) => {
                let edit_mode = Box::new(Emacs::new(keybindings));
                line_editor.with_edit_mode(edit_mode)
            }
            KeybindingsMode::Vi {
                insert_keybindings,
                normal_keybindings,
            } => {
                let edit_mode = Box::new(Vi::new(insert_keybindings, normal_keybindings));
                line_editor.with_edit_mode(edit_mode)
            }
        },
        Err(e) => {
            report_error_new(engine_state, &e);
            line_editor
        }
    };
}

///
/// Make sure that the terminal supports the kitty protocol if the config is asking for it
///
fn kitty_protocol_healthcheck(engine_state: &EngineState) {
    if engine_state.get_config().use_kitty_protocol && !reedline::kitty_protocol_available() {
        warn!("Terminal doesn't support use_kitty_protocol config");
    }
}

fn store_history_id_in_engine(engine_state: &mut EngineState, line_editor: &Reedline) {
    let session_id = line_editor
        .get_history_session_id()
        .map(i64::from)
        .unwrap_or(0);

    engine_state.history_session_id = session_id;
}

fn update_line_editor_history(
    engine_state: &mut EngineState,
    history_path: PathBuf,
    history: HistoryConfig,
    line_editor: Reedline,
    history_session_id: Option<HistorySessionId>,
) -> Result<Reedline, ErrReport> {
    let history: Box<dyn reedline::History> = match history.file_format {
        HistoryFileFormat::PlainText => Box::new(
            FileBackedHistory::with_file(history.max_size as usize, history_path)
                .into_diagnostic()?,
        ),
        HistoryFileFormat::Sqlite => Box::new(
            SqliteBackedHistory::with_file(
                history_path.to_path_buf(),
                history_session_id,
                Some(chrono::Utc::now()),
            )
            .into_diagnostic()?,
        ),
    };
    let line_editor = line_editor
        .with_history_session_id(history_session_id)
        .with_history_exclusion_prefix(Some(" ".into()))
        .with_history(history);

    store_history_id_in_engine(engine_state, &line_editor);

    Ok(line_editor)
}

fn confirm_stdin_is_terminal() -> Result<()> {
    // Guard against invocation without a connected terminal.
    // reedline / crossterm event polling will fail without a connected tty
    if !std::io::stdin().is_terminal() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "Nushell launched as a REPL, but STDIN is not a TTY; either launch in a valid terminal or provide arguments to invoke a script!",
        ))
        .into_diagnostic();
    }
    Ok(())
}
fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> Option<SetCursorStyle> {
    match shape {
        NuCursorShape::Block => Some(SetCursorStyle::SteadyBlock),
        NuCursorShape::UnderScore => Some(SetCursorStyle::SteadyUnderScore),
        NuCursorShape::Line => Some(SetCursorStyle::SteadyBar),
        NuCursorShape::BlinkBlock => Some(SetCursorStyle::BlinkingBlock),
        NuCursorShape::BlinkUnderScore => Some(SetCursorStyle::BlinkingUnderScore),
        NuCursorShape::BlinkLine => Some(SetCursorStyle::BlinkingBar),
        NuCursorShape::Inherit => None,
    }
}

fn get_command_finished_marker(stack: &Stack, engine_state: &EngineState) -> String {
    let exit_code = stack
        .get_env_var(engine_state, "LAST_EXIT_CODE")
        .and_then(|e| e.as_i64().ok());

    format!("\x1b]133;D;{}\x1b\\", exit_code.unwrap_or(0))
}

fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> {
    io::stdout()
        .write_all(seq.as_bytes())
        .map_err(|e| ShellError::GenericError {
            error: "Error writing ansi sequence".into(),
            msg: e.to_string(),
            span: Some(Span::unknown()),
            help: None,
            inner: vec![],
        })?;
    io::stdout().flush().map_err(|e| ShellError::GenericError {
        error: "Error flushing stdio".into(),
        msg: e.to_string(),
        span: Some(Span::unknown()),
        help: None,
        inner: vec![],
    })
}

// Absolute paths with a drive letter, like 'C:', 'D:\', 'E:\foo'
#[cfg(windows)]
static DRIVE_PATH_REGEX: once_cell::sync::Lazy<fancy_regex::Regex> =
    once_cell::sync::Lazy::new(|| {
        fancy_regex::Regex::new(r"^[a-zA-Z]:[/\\]?").expect("Internal error: regex creation")
    });

// A best-effort "does this string look kinda like a path?" function to determine whether to auto-cd
fn looks_like_path(orig: &str) -> bool {
    #[cfg(windows)]
    {
        if DRIVE_PATH_REGEX.is_match(orig).unwrap_or(false) {
            return true;
        }
    }

    orig.starts_with('.')
        || orig.starts_with('~')
        || orig.starts_with('/')
        || orig.starts_with('\\')
        || orig.ends_with(std::path::MAIN_SEPARATOR)
}

#[cfg(windows)]
#[test]
fn looks_like_path_windows_drive_path_works() {
    assert!(looks_like_path("C:"));
    assert!(looks_like_path("D:\\"));
    assert!(looks_like_path("E:/"));
    assert!(looks_like_path("F:\\some_dir"));
    assert!(looks_like_path("G:/some_dir"));
}

#[cfg(windows)]
#[test]
fn trailing_slash_looks_like_path() {
    assert!(looks_like_path("foo\\"))
}

#[cfg(not(windows))]
#[test]
fn trailing_slash_looks_like_path() {
    assert!(looks_like_path("foo/"))
}

#[test]
fn are_session_ids_in_sync() {
    let engine_state = &mut EngineState::new();
    let history = engine_state.history_config().unwrap();
    let history_path =
        crate::config_files::get_history_path("nushell", history.file_format).unwrap();
    let line_editor = reedline::Reedline::create();
    let history_session_id = reedline::Reedline::create_history_session_id();
    let line_editor = update_line_editor_history(
        engine_state,
        history_path,
        history,
        line_editor,
        history_session_id,
    );
    assert_eq!(
        i64::from(line_editor.unwrap().get_history_session_id().unwrap()),
        engine_state.history_session_id
    );
}