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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
use crate::prompt_update::{
    POST_EXECUTION_MARKER_PREFIX, POST_EXECUTION_MARKER_SUFFIX, PRE_EXECUTION_MARKER,
    RESET_APPLICATION_MODE, VSCODE_CWD_PROPERTY_MARKER_PREFIX, VSCODE_CWD_PROPERTY_MARKER_SUFFIX,
    VSCODE_POST_EXECUTION_MARKER_PREFIX, VSCODE_POST_EXECUTION_MARKER_SUFFIX,
    VSCODE_PRE_EXECUTION_MARKER,
};
use crate::{
    completions::NuCompleter,
    nu_highlight::NoOpHighlighter,
    prompt_update,
    reedline_config::{add_menus, create_keybindings, KeybindingsMode},
    util::eval_source,
    NuHighlighter, NuValidator, NushellPrompt,
};
use crossterm::cursor::SetCursorStyle;
use log::{error, trace, warn};
use miette::{ErrReport, IntoDiagnostic, Result};
use nu_cmd_base::{
    hook::eval_hook,
    util::{get_editor, get_guaranteed_cwd},
};
use nu_color_config::StyleComputer;
#[allow(deprecated)]
use nu_engine::{convert_env_values, current_dir_str, env_to_strings};
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::{
    config::NuCursorShape,
    engine::{EngineState, Stack, StateWorkingSet},
    report_error_new, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned,
    Value,
};
use nu_utils::{
    filesystem::{have_permission, PermissionResult},
    perf,
};
use reedline::{
    CursorConfig, CwdAwareHinter, DefaultCompleter, EditCommand, Emacs, FileBackedHistory,
    HistorySessionId, Reedline, SqliteBackedHistory, Vi,
};
use std::{
    collections::HashMap,
    env::temp_dir,
    io::{self, IsTerminal, Write},
    panic::{catch_unwind, AssertUnwindSafe},
    path::{Path, PathBuf},
    sync::Arc,
    time::{Duration, Instant},
};
use sysinfo::System;

/// The main REPL loop, including spinning up the prompt itself.
pub fn evaluate_repl(
    engine_state: &mut EngineState,
    stack: Stack,
    nushell_path: &str,
    prerun_command: Option<Spanned<String>>,
    load_std_lib: Option<Spanned<String>>,
    entire_start_time: Instant,
) -> Result<()> {
    // throughout this code, we hold this stack uniquely.
    // During the main REPL loop, we hand ownership of this value to an Arc,
    // so that it may be read by various reedline plugins. During this, we
    // can't modify the stack, but at the end of the loop we take back ownership
    // from the Arc. This lets us avoid copying stack variables needlessly
    let mut unique_stack = stack.clone();
    let config = engine_state.get_config();
    let use_color = config.use_ansi_coloring;

    confirm_stdin_is_terminal()?;

    let mut entry_num = 0;

    // Let's grab the shell_integration configs
    let shell_integration_osc2 = config.shell_integration_osc2;
    let shell_integration_osc7 = config.shell_integration_osc7;
    let shell_integration_osc9_9 = config.shell_integration_osc9_9;
    let shell_integration_osc133 = config.shell_integration_osc133;
    let shell_integration_osc633 = config.shell_integration_osc633;

    let nu_prompt = NushellPrompt::new(
        shell_integration_osc133,
        shell_integration_osc633,
        engine_state.clone(),
        stack.clone(),
    );

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

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

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

    let mut line_editor = get_line_editor(engine_state, nushell_path, use_color)?;
    let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4()));

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

    let hostname = System::host_name();
    if shell_integration_osc2 {
        run_shell_integration_osc2(None, engine_state, &mut unique_stack, use_color);
    }
    if shell_integration_osc7 {
        run_shell_integration_osc7(
            hostname.as_deref(),
            engine_state,
            &mut unique_stack,
            use_color,
        );
    }
    if shell_integration_osc9_9 {
        run_shell_integration_osc9_9(engine_state, &mut unique_stack, use_color);
    }
    if shell_integration_osc633 {
        run_shell_integration_osc633(engine_state, &mut unique_stack, use_color);
    }

    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
    engine_state.generate_nu_constant();

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

    kitty_protocol_healthcheck(engine_state);

    // Setup initial engine_state and stack state
    let mut previous_engine_state = engine_state.clone();
    let mut previous_stack_arc = Arc::new(unique_stack);
    loop {
        // clone these values so that they can be moved by AssertUnwindSafe
        // If there is a panic within this iteration the last engine_state and stack
        // will be used
        let mut current_engine_state = previous_engine_state.clone();
        // for the stack, we are going to hold to create a child stack instead,
        // avoiding an expensive copy
        let current_stack = Stack::with_parent(previous_stack_arc.clone());
        let temp_file_cloned = temp_file.clone();
        let mut nu_prompt_cloned = nu_prompt.clone();

        let iteration_panic_state = catch_unwind(AssertUnwindSafe(|| {
            let (continue_loop, current_stack, line_editor) = loop_iteration(LoopContext {
                engine_state: &mut current_engine_state,
                stack: current_stack,
                line_editor,
                nu_prompt: &mut nu_prompt_cloned,
                temp_file: &temp_file_cloned,
                use_color,
                entry_num: &mut entry_num,
                hostname: hostname.as_deref(),
            });

            // pass the most recent version of the line_editor back
            (
                continue_loop,
                current_engine_state,
                current_stack,
                line_editor,
            )
        }));
        match iteration_panic_state {
            Ok((continue_loop, es, s, le)) => {
                // setup state for the next iteration of the repl loop
                previous_engine_state = es;
                // we apply the changes from the updated stack back onto our previous stack
                previous_stack_arc =
                    Arc::new(Stack::with_changes_from_child(previous_stack_arc, s));
                line_editor = le;
                if !continue_loop {
                    break;
                }
            }
            Err(_) => {
                // line_editor is lost in the error case so reconstruct a new one
                line_editor = get_line_editor(engine_state, nushell_path, use_color)?;
            }
        }
    }

    Ok(())
}

fn get_line_editor(
    engine_state: &mut EngineState,
    nushell_path: &str,
    use_color: bool,
) -> Result<Reedline> {
    let mut start_time = std::time::Instant::now();
    let mut line_editor = Reedline::create();

    // 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, 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, use_color);
    }
    Ok(line_editor)
}

struct LoopContext<'a> {
    engine_state: &'a mut EngineState,
    stack: Stack,
    line_editor: Reedline,
    nu_prompt: &'a mut NushellPrompt,
    temp_file: &'a Path,
    use_color: bool,
    entry_num: &'a mut usize,
    hostname: Option<&'a str>,
}

/// Perform one iteration of the REPL loop
/// Result is bool: continue loop, current reedline
#[inline]
fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
    use nu_cmd_base::hook;
    use reedline::Signal;
    let loop_start_time = std::time::Instant::now();

    let LoopContext {
        engine_state,
        mut stack,
        line_editor,
        nu_prompt,
        temp_file,
        use_color,
        entry_num,
        hostname,
    } = ctx;

    let cwd = get_guaranteed_cwd(engine_state, &stack);

    let mut 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(&mut stack, cwd) {
        report_error_new(engine_state, &err);
    }
    // Check whether $env.NU_USE_IR is set, so that the user can change it in the REPL
    // Temporary while IR eval is optional
    stack.use_ir = stack.has_env_var(engine_state, "NU_USE_IR");
    perf!("merge env", start_time, use_color);

    start_time = std::time::Instant::now();
    engine_state.reset_signals();
    perf!("reset signals", start_time, 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) = engine_state.get_config().hooks.pre_prompt.clone() {
        if let Err(err) = eval_hook(engine_state, &mut stack, None, vec![], &hook, "pre_prompt") {
            report_error_new(engine_state, &err);
        }
    }
    perf!("pre-prompt hook", start_time, use_color);

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

    let engine_reference = Arc::new(engine_state.clone());
    let config = stack.get_config(engine_state);

    start_time = std::time::Instant::now();
    // 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, use_color);

    start_time = std::time::Instant::now();
    // at this line we have cloned the state for the completer and the transient prompt
    // until we drop those, we cannot use the stack in the REPL loop itself
    // See STACK-REFERENCE to see where we have taken a reference
    let stack_arc = Arc::new(stack);

    let mut 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-REFERENCE 1
            stack: stack_arc.clone(),
        }))
        .with_validator(Box::new(NuValidator {
            engine_state: engine_reference.clone(),
        }))
        .with_completer(Box::new(NuCompleter::new(
            engine_reference.clone(),
            // STACK-REFERENCE 2
            stack_arc.clone(),
        )))
        .with_quick_completions(config.quick_completions)
        .with_partial_completions(config.partial_completions)
        .with_ansi_colors(config.use_ansi_coloring)
        .with_cwd(Some(
            engine_state
                .cwd(None)
                .map(|cwd| cwd.into_std_path_buf())
                .unwrap_or_default()
                .to_string_lossy()
                .to_string(),
        ))
        .with_cursor_config(cursor_config);

    perf!("reedline builder", start_time, use_color);

    let style_computer = StyleComputer::from_config(engine_state, &stack_arc);

    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, use_color);

    start_time = std::time::Instant::now();
    trace!("adding menus");
    line_editor =
        add_menus(line_editor, engine_reference, &stack_arc, config).unwrap_or_else(|e| {
            report_error_new(engine_state, &e);
            Reedline::create()
        });

    perf!("reedline adding menus", start_time, use_color);

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

    line_editor = if let Ok((cmd, args)) = buffer_editor {
        let mut command = std::process::Command::new(cmd);
        let envs = env_to_strings(engine_state, &stack_arc).unwrap_or_else(|e| {
            warn!("Couldn't convert environment variable values to strings: {e}");
            HashMap::default()
        });
        command.args(args).envs(envs);
        line_editor.with_buffer_editor(command, temp_file.to_path_buf())
    } else {
        line_editor
    };

    perf!("reedline buffer_editor", start_time, 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, 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, use_color);

    start_time = std::time::Instant::now();
    let config = &engine_state.get_config().clone();
    prompt_update::update_prompt(
        config,
        engine_state,
        &mut Stack::with_parent(stack_arc.clone()),
        nu_prompt,
    );
    let transient_prompt = prompt_update::make_transient_prompt(
        config,
        engine_state,
        &mut Stack::with_parent(stack_arc.clone()),
        nu_prompt,
    );

    perf!("update_prompt", start_time, 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);
    // we got our inputs, we can now drop our stack references
    // This lists all of the stack references that we have cleaned up
    line_editor = line_editor
        // CLEAR STACK-REFERENCE 1
        .with_highlighter(Box::<NoOpHighlighter>::default())
        // CLEAR STACK-REFERENCE 2
        .with_completer(Box::<DefaultCompleter>::default());

    // Let's grab the shell_integration configs
    let shell_integration_osc2 = config.shell_integration_osc2;
    let shell_integration_osc7 = config.shell_integration_osc7;
    let shell_integration_osc9_9 = config.shell_integration_osc9_9;
    let shell_integration_osc133 = config.shell_integration_osc133;
    let shell_integration_osc633 = config.shell_integration_osc633;
    let shell_integration_reset_application_mode = config.shell_integration_reset_application_mode;

    // TODO: we may clone the stack, this can lead to major performance issues
    // so we should avoid it or making stack cheaper to clone.
    let mut stack = Arc::unwrap_or_clone(stack_arc);

    perf!("line_editor setup", start_time, use_color);

    let line_editor_input_time = std::time::Instant::now();
    match input {
        Ok(Signal::Success(s)) => {
            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);
            }

            // For pre_exec_hook
            start_time = Instant::now();

            // 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,
                    &mut stack,
                    None,
                    vec![],
                    &hook,
                    "pre_execution",
                ) {
                    report_error_new(engine_state, &err);
                }
            }

            perf!("pre_execution_hook", start_time, use_color);

            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_osc633 {
                if stack.get_env_var(engine_state, "TERM_PROGRAM")
                    == Some(Value::test_string("vscode"))
                {
                    start_time = Instant::now();

                    run_ansi_sequence(VSCODE_PRE_EXECUTION_MARKER);

                    perf!(
                        "pre_execute_marker (633;C) ansi escape sequence",
                        start_time,
                        use_color
                    );
                } else if shell_integration_osc133 {
                    start_time = Instant::now();

                    run_ansi_sequence(PRE_EXECUTION_MARKER);

                    perf!(
                        "pre_execute_marker (133;C) ansi escape sequence",
                        start_time,
                        use_color
                    );
                }
            } else if shell_integration_osc133 {
                start_time = Instant::now();

                run_ansi_sequence(PRE_EXECUTION_MARKER);

                perf!(
                    "pre_execute_marker (133;C) ansi escape sequence",
                    start_time,
                    use_color
                );
            }

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

            match parse_operation(s.clone(), engine_state, &stack) {
                Ok(operation) => match operation {
                    ReplOperation::AutoCd { cwd, target, span } => {
                        do_auto_cd(target, cwd, &mut stack, engine_state, span);

                        run_finaliziation_ansi_sequence(
                            &stack,
                            engine_state,
                            use_color,
                            shell_integration_osc633,
                            shell_integration_osc133,
                        );
                    }
                    ReplOperation::RunCommand(cmd) => {
                        line_editor = do_run_cmd(
                            &cmd,
                            &mut stack,
                            engine_state,
                            line_editor,
                            shell_integration_osc2,
                            *entry_num,
                            use_color,
                        );

                        run_finaliziation_ansi_sequence(
                            &stack,
                            engine_state,
                            use_color,
                            shell_integration_osc633,
                            shell_integration_osc133,
                        );
                    }
                    // as the name implies, we do nothing in this case
                    ReplOperation::DoNothing => {}
                },
                Err(ref e) => error!("Error parsing operation: {e}"),
            }
            let cmd_duration = cmd_execution_start_time.elapsed();

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

            if history_supports_meta {
                if let Err(e) = fill_in_result_related_history_metadata(
                    &s,
                    engine_state,
                    cmd_duration,
                    &mut stack,
                    &mut line_editor,
                ) {
                    warn!("Could not fill in result related history metadata: {e}");
                }
            }

            if shell_integration_osc2 {
                run_shell_integration_osc2(None, engine_state, &mut stack, use_color);
            }
            if shell_integration_osc7 {
                run_shell_integration_osc7(hostname, engine_state, &mut stack, use_color);
            }
            if shell_integration_osc9_9 {
                run_shell_integration_osc9_9(engine_state, &mut stack, use_color);
            }
            if shell_integration_osc633 {
                run_shell_integration_osc633(engine_state, &mut stack, use_color);
            }
            if shell_integration_reset_application_mode {
                run_shell_integration_reset_application_mode();
            }

            flush_engine_state_repl_buffer(engine_state, &mut line_editor);
        }
        Ok(Signal::CtrlC) => {
            // `Reedline` clears the line content. New prompt is shown
            run_finaliziation_ansi_sequence(
                &stack,
                engine_state,
                use_color,
                shell_integration_osc633,
                shell_integration_osc133,
            );
        }
        Ok(Signal::CtrlD) => {
            // When exiting clear to a new line

            run_finaliziation_ansi_sequence(
                &stack,
                engine_state,
                use_color,
                shell_integration_osc633,
                shell_integration_osc133,
            );

            println!();
            return (false, stack, line_editor);
        }
        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
            }

            run_finaliziation_ansi_sequence(
                &stack,
                engine_state,
                use_color,
                shell_integration_osc633,
                shell_integration_osc133,
            );
        }
    }
    perf!(
        "processing line editor input",
        line_editor_input_time,
        use_color
    );

    perf!(
        "time between prompts in line editor loop",
        loop_start_time,
        use_color
    );

    (true, stack, line_editor)
}

///
/// Put in history metadata not related to the result of running the command
///
fn prepare_history_metadata(
    s: &str,
    hostname: Option<&str>,
    engine_state: &EngineState,
    line_editor: &mut Reedline,
) {
    if !s.is_empty() && line_editor.has_last_command_context() {
        let result = line_editor
            .update_last_command_context(&|mut c| {
                c.start_timestamp = Some(chrono::Utc::now());
                c.hostname = hostname.map(str::to_string);
                c.cwd = engine_state
                    .cwd(None)
                    .ok()
                    .map(|path| path.to_string_lossy().to_string());
                c
            })
            .into_diagnostic();
        if let Err(e) = result {
            warn!("Could not prepare history metadata: {e}");
        }
    }
}

///
/// 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
    #[allow(deprecated)]
    let cwd = nu_engine::env::current_dir_str(engine_state, stack).unwrap_or_default();
    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, true);
    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,
                },
            );
        }
        path.to_string_lossy().to_string()
    };

    if let PermissionResult::PermissionDenied(reason) = have_permission(path.clone()) {
        report_error_new(
            engine_state,
            &ShellError::IOError {
                msg: format!("Cannot change directory to {path}: {reason}"),
            },
        );
        return;
    }

    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
    if let Err(err) = stack.set_cwd(&path) {
        report_error_new(engine_state, &err);
        return;
    };
    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.into_list().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),
    );
    stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown()));
}

///
/// 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_osc2: bool,
    entry_num: usize,
    use_color: bool,
) -> 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_osc2 {
        run_shell_integration_osc2(Some(s), engine_state, stack, use_color);
    }

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

    line_editor
}

///
/// Output some things and set environment variables so shells with the right integration
/// can have more information about what is going on (both on startup and after we have
/// run a command)
///
fn run_shell_integration_osc2(
    command_name: Option<&str>,
    engine_state: &EngineState,
    stack: &mut Stack,
    use_color: bool,
) {
    #[allow(deprecated)]
    if let Ok(path) = current_dir_str(engine_state, stack) {
        let start_time = Instant::now();

        // 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 title = match command_name {
            Some(binary_name) => {
                let split_binary_name = binary_name.split_whitespace().next();
                if let Some(binary_name) = split_binary_name {
                    format!("{maybe_abbrev_path}> {binary_name}")
                } else {
                    maybe_abbrev_path.to_string()
                }
            }
            None => maybe_abbrev_path.to_string(),
        };

        // 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;{title}\x07"));

        perf!("set title with command osc2", start_time, use_color);
    }
}

fn run_shell_integration_osc7(
    hostname: Option<&str>,
    engine_state: &EngineState,
    stack: &mut Stack,
    use_color: bool,
) {
    #[allow(deprecated)]
    if let Ok(path) = current_dir_str(engine_state, stack) {
        let start_time = Instant::now();

        // 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("localhost"),
                percent_encoding::CONTROLS
            ),
            if path.starts_with('/') { "" } else { "/" },
            percent_encoding::utf8_percent_encode(&path, percent_encoding::CONTROLS)
        ));

        perf!(
            "communicate path to terminal with osc7",
            start_time,
            use_color
        );
    }
}

fn run_shell_integration_osc9_9(engine_state: &EngineState, stack: &mut Stack, use_color: bool) {
    #[allow(deprecated)]
    if let Ok(path) = current_dir_str(engine_state, stack) {
        let start_time = Instant::now();

        // Otherwise, communicate the path as OSC 9;9 from ConEmu (often used for spawning new tabs in the same dir)
        // This is helpful in Windows Terminal with Duplicate Tab
        run_ansi_sequence(&format!(
            "\x1b]9;9;{}\x1b\\",
            percent_encoding::utf8_percent_encode(&path, percent_encoding::CONTROLS)
        ));

        perf!(
            "communicate path to terminal with osc9;9",
            start_time,
            use_color
        );
    }
}

fn run_shell_integration_osc633(engine_state: &EngineState, stack: &mut Stack, use_color: bool) {
    #[allow(deprecated)]
    if let Ok(path) = current_dir_str(engine_state, stack) {
        // 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")) {
            let start_time = Instant::now();

            // 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!(
                "{}{}{}",
                VSCODE_CWD_PROPERTY_MARKER_PREFIX, path, VSCODE_CWD_PROPERTY_MARKER_SUFFIX
            ));

            perf!(
                "communicate path to terminal with osc633;P",
                start_time,
                use_color
            );
        }
    }
}

fn run_shell_integration_reset_application_mode() {
    run_ansi_sequence(RESET_APPLICATION_MODE);
}

///
/// 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,
    shell_integration_osc633: bool,
    shell_integration_osc133: bool,
) -> String {
    let exit_code = stack
        .get_env_var(engine_state, "LAST_EXIT_CODE")
        .and_then(|e| e.as_i64().ok());

    if shell_integration_osc633 {
        if stack.get_env_var(engine_state, "TERM_PROGRAM") == Some(Value::test_string("vscode")) {
            // We're in vscode and we have osc633 enabled
            format!(
                "{}{}{}",
                VSCODE_POST_EXECUTION_MARKER_PREFIX,
                exit_code.unwrap_or(0),
                VSCODE_POST_EXECUTION_MARKER_SUFFIX
            )
        } else if shell_integration_osc133 {
            // If we're in VSCode but we don't find the env var, just return the regular markers
            format!(
                "{}{}{}",
                POST_EXECUTION_MARKER_PREFIX,
                exit_code.unwrap_or(0),
                POST_EXECUTION_MARKER_SUFFIX
            )
        } else {
            // We're not in vscode, so we don't need to do anything special
            "\x1b[0m".to_string()
        }
    } else if shell_integration_osc133 {
        format!(
            "{}{}{}",
            POST_EXECUTION_MARKER_PREFIX,
            exit_code.unwrap_or(0),
            POST_EXECUTION_MARKER_SUFFIX
        )
    } else {
        "\x1b[0m".to_string()
    }
}

fn run_ansi_sequence(seq: &str) {
    if let Err(e) = io::stdout().write_all(seq.as_bytes()) {
        warn!("Error writing ansi sequence {e}");
    } else if let Err(e) = io::stdout().flush() {
        warn!("Error flushing stdio {e}");
    }
}

fn run_finaliziation_ansi_sequence(
    stack: &Stack,
    engine_state: &EngineState,
    use_color: bool,
    shell_integration_osc633: bool,
    shell_integration_osc133: bool,
) {
    if shell_integration_osc633 {
        // Only run osc633 if we are in vscode
        if stack.get_env_var(engine_state, "TERM_PROGRAM") == Some(Value::test_string("vscode")) {
            let start_time = Instant::now();

            run_ansi_sequence(&get_command_finished_marker(
                stack,
                engine_state,
                shell_integration_osc633,
                shell_integration_osc133,
            ));

            perf!(
                "post_execute_marker (633;D) ansi escape sequences",
                start_time,
                use_color
            );
        } else if shell_integration_osc133 {
            let start_time = Instant::now();

            run_ansi_sequence(&get_command_finished_marker(
                stack,
                engine_state,
                shell_integration_osc633,
                shell_integration_osc133,
            ));

            perf!(
                "post_execute_marker (133;D) ansi escape sequences",
                start_time,
                use_color
            );
        }
    } else if shell_integration_osc133 {
        let start_time = Instant::now();

        run_ansi_sequence(&get_command_finished_marker(
            stack,
            engine_state,
            shell_integration_osc633,
            shell_integration_osc133,
        ));

        perf!(
            "post_execute_marker (133;D) ansi escape sequences",
            start_time,
            use_color
        );
    }
}

// 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
    );
}

#[cfg(test)]
mod test_auto_cd {
    use super::{do_auto_cd, parse_operation, ReplOperation};
    use nu_protocol::engine::{EngineState, Stack};
    use std::path::Path;
    use tempfile::tempdir;

    /// Create a symlink. Works on both Unix and Windows.
    #[cfg(any(unix, windows))]
    fn symlink(original: impl AsRef<Path>, link: impl AsRef<Path>) -> std::io::Result<()> {
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(original, link)
        }
        #[cfg(windows)]
        {
            if original.as_ref().is_dir() {
                std::os::windows::fs::symlink_dir(original, link)
            } else {
                std::os::windows::fs::symlink_file(original, link)
            }
        }
    }

    /// Run one test case on the auto-cd feature. PWD is initially set to
    /// `before`, and after `input` is parsed and evaluated, PWD should be
    /// changed to `after`.
    #[track_caller]
    fn check(before: impl AsRef<Path>, input: &str, after: impl AsRef<Path>) {
        // Setup EngineState and Stack.
        let mut engine_state = EngineState::new();
        let mut stack = Stack::new();
        stack.set_cwd(before).unwrap();

        // Parse the input. It must be an auto-cd operation.
        let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap();
        let ReplOperation::AutoCd { cwd, target, span } = op else {
            panic!("'{}' was not parsed into an auto-cd operation", input)
        };

        // Perform the auto-cd operation.
        do_auto_cd(target, cwd, &mut stack, &mut engine_state, span);
        let updated_cwd = engine_state.cwd(Some(&stack)).unwrap();

        // Check that `updated_cwd` and `after` point to the same place. They
        // don't have to be byte-wise equal (on Windows, the 8.3 filename
        // conversion messes things up),
        let updated_cwd = std::fs::canonicalize(updated_cwd).unwrap();
        let after = std::fs::canonicalize(after).unwrap();
        assert_eq!(updated_cwd, after);
    }

    #[test]
    fn auto_cd_root() {
        let tempdir = tempdir().unwrap();
        let root = if cfg!(windows) { r"C:\" } else { "/" };
        check(&tempdir, root, root);
    }

    #[test]
    fn auto_cd_tilde() {
        let tempdir = tempdir().unwrap();
        let home = nu_path::home_dir().unwrap();
        check(&tempdir, "~", home);
    }

    #[test]
    fn auto_cd_dot() {
        let tempdir = tempdir().unwrap();
        check(&tempdir, ".", &tempdir);
    }

    #[test]
    fn auto_cd_double_dot() {
        let tempdir = tempdir().unwrap();
        let dir = tempdir.path().join("foo");
        std::fs::create_dir_all(&dir).unwrap();
        check(dir, "..", &tempdir);
    }

    #[test]
    fn auto_cd_triple_dot() {
        let tempdir = tempdir().unwrap();
        let dir = tempdir.path().join("foo").join("bar");
        std::fs::create_dir_all(&dir).unwrap();
        check(dir, "...", &tempdir);
    }

    #[test]
    fn auto_cd_relative() {
        let tempdir = tempdir().unwrap();
        let foo = tempdir.path().join("foo");
        let bar = tempdir.path().join("bar");
        std::fs::create_dir_all(&foo).unwrap();
        std::fs::create_dir_all(&bar).unwrap();

        let input = if cfg!(windows) { r"..\bar" } else { "../bar" };
        check(foo, input, bar);
    }

    #[test]
    fn auto_cd_trailing_slash() {
        let tempdir = tempdir().unwrap();
        let dir = tempdir.path().join("foo");
        std::fs::create_dir_all(&dir).unwrap();

        let input = if cfg!(windows) { r"foo\" } else { "foo/" };
        check(&tempdir, input, dir);
    }

    #[test]
    fn auto_cd_symlink() {
        let tempdir = tempdir().unwrap();
        let dir = tempdir.path().join("foo");
        std::fs::create_dir_all(&dir).unwrap();
        let link = tempdir.path().join("link");
        symlink(&dir, &link).unwrap();

        let input = if cfg!(windows) { r".\link" } else { "./link" };
        check(&tempdir, input, link);
    }

    #[test]
    #[should_panic(expected = "was not parsed into an auto-cd operation")]
    fn auto_cd_nonexistent_directory() {
        let tempdir = tempdir().unwrap();
        let dir = tempdir.path().join("foo");

        let input = if cfg!(windows) { r"foo\" } else { "foo/" };
        check(&tempdir, input, dir);
    }
}