nvim-mcp 0.7.2

MCP server for Neovim
Documentation
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
use std::fs;

use tempfile::TempDir;
use tracing::info;
use tracing_test::traced_test;

use crate::neovim::client::{DocumentIdentifier, Position, Range};
use crate::neovim::{NeovimClient, NeovimClientTrait};
use crate::test_utils::*;

// Test helper functions to reduce boilerplate

#[tokio::test]
#[traced_test]
async fn test_tcp_connection_lifecycle() {
    let port = PORT_BASE;
    let address = format!("{HOST}:{port}");

    let child = {
        let _guard = NEOVIM_TEST_MUTEX.lock().unwrap();
        drop(_guard);
        setup_neovim_instance(port).await
    };
    let _guard = NeovimProcessGuard::new(child, address.clone());
    let mut client = NeovimClient::default();

    // Test connection
    let result = client.connect_tcp(&address).await;
    assert!(result.is_ok(), "Failed to connect: {result:?}");

    // Test that we can't connect again while already connected
    let result = client.connect_tcp(&address).await;
    assert!(result.is_err(), "Should not be able to connect twice");

    // Test disconnect
    let result = client.disconnect().await;
    assert!(result.is_ok(), "Failed to disconnect: {result:?}");

    // Test that disconnect fails when not connected
    let result = client.disconnect().await;
    assert!(
        result.is_err(),
        "Should not be able to disconnect when not connected"
    );

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_buffer_operations() {
    let ipc_path = generate_random_ipc_path();

    let (client, _guard) = setup_auto_connected_client_ipc(&ipc_path).await;

    // Test buffer listing
    let result = client.get_buffers().await;
    assert!(result.is_ok(), "Failed to get buffers: {result:?}");

    let buffer_info = result.unwrap();
    assert!(!buffer_info.is_empty());

    // Should have at least one buffer (the initial empty buffer)
    let first_buffer = &buffer_info[0];
    assert!(
        first_buffer.id > 0,
        "Buffer should have valid id: {first_buffer:?}"
    );
    // Line count should be reasonable (buffers typically have at least 1 line)
    assert!(
        first_buffer.line_count > 0,
        "Buffer should have at least one line: {first_buffer:?}"
    );

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_lua_execution() {
    let ipc_path = generate_random_ipc_path();

    let (client, _guard) = setup_auto_connected_client_ipc(&ipc_path).await;

    // Test successful Lua execution
    let result = client.execute_lua("return 42").await;
    assert!(result.is_ok(), "Failed to execute Lua: {result:?}");

    let lua_result = result.unwrap();
    assert!(
        format!("{lua_result:?}").contains("42"),
        "Lua result should contain 42: {lua_result:?}"
    );

    // Test Lua execution with string result
    let result = client.execute_lua("return 'hello world'").await;
    assert!(result.is_ok(), "Failed to execute Lua: {result:?}");

    // Test error handling for invalid Lua
    let result = client.execute_lua("invalid lua syntax !!!").await;
    assert!(result.is_err(), "Should fail for invalid Lua syntax");

    // Test error handling for empty code
    let result = client.execute_lua("").await;
    assert!(result.is_err(), "Should fail for empty Lua code");

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_error_handling() {
    #[cfg(unix)]
    use tokio::net::UnixStream;
    #[cfg(windows)]
    use tokio::net::windows::named_pipe::NamedPipeClient;
    #[cfg(unix)]
    let client = NeovimClient::<UnixStream>::default();
    #[cfg(windows)]
    let client = NeovimClient::<NamedPipeClient>::new();

    // Test operations without connection
    let result = client.get_buffers().await;
    assert!(
        result.is_err(),
        "get_buffers should fail when not connected"
    );

    let result = client.execute_lua("return 1").await;
    assert!(
        result.is_err(),
        "execute_lua should fail when not connected"
    );

    let mut client_mut = client;
    let result = client_mut.disconnect().await;
    assert!(result.is_err(), "disconnect should fail when not connected");
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_connection_constraint() {
    let ipc_path = generate_random_ipc_path();

    // Start neovim instance but don't auto-connect - we need to test manual connection behavior
    let child = setup_neovim_instance_ipc(&ipc_path).await;
    let _guard = NeovimIpcGuard::new(child, ipc_path.clone());
    let mut client = NeovimClient::default();

    // Connect to instance
    let result = client.connect_path(&ipc_path).await;
    assert!(result.is_ok(), "Failed to connect to instance");

    // Try to connect again (should fail)
    let result = client.connect_path(&ipc_path).await;
    assert!(result.is_err(), "Should not be able to connect twice");

    // Disconnect and then connect again (should work)
    let result = client.disconnect().await;
    assert!(result.is_ok(), "Failed to disconnect from instance");

    let result = client.connect_path(&ipc_path).await;
    assert!(result.is_ok(), "Failed to reconnect after disconnect");

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_get_vim_diagnostics() {
    let ipc_path = generate_random_ipc_path();

    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let diagnostic_path = get_testdata_path("diagnostic_problems.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        diagnostic_path.to_str().unwrap(),
    )
    .await;

    let result = client.get_buffer_diagnostics(0).await;
    assert!(result.is_ok(), "Failed to get diagnostics: {result:?}");

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_code_action() {
    let ipc_path = generate_random_ipc_path();

    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let diagnostic_path = get_testdata_path("diagnostic_problems.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        diagnostic_path.to_str().unwrap(),
    )
    .await;

    let result = client.get_buffer_diagnostics(0).await;
    assert!(result.is_ok(), "Failed to get diagnostics: {result:?}");
    let result = result.unwrap();
    info!("Diagnostics: {:?}", result);

    let diagnostic = result.first().expect("Failed to get any diagnostics");
    let result = client
        .lsp_get_code_actions(
            "luals",
            DocumentIdentifier::from_buffer_id(0),
            Range {
                start: Position {
                    line: diagnostic.lnum,
                    character: diagnostic.col,
                },
                end: Position {
                    line: diagnostic.end_lnum,
                    character: diagnostic.end_col,
                },
            },
        )
        .await;
    assert!(result.is_ok(), "Failed to get code actions: {result:?}");
    info!("Code actions: {:?}", result);

    // Guard automatically cleans up when it goes out of scope
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_lsp_resolve_code_action() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_resolve.go");

    // Create a Go file with fmt.Println call that can be inlined
    let go_content = get_testdata_content("main.go");

    fs::write(&temp_file_path, go_content).expect("Failed to write temp Go file");

    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Wait for LSP readiness (diagnostics already waited in auto-connect)
    let lsp_result = client.wait_for_lsp_ready(None, 15000).await;
    assert!(lsp_result.is_ok(), "LSP should be ready");

    // Position cursor inside fmt.Println call (line 6, character 6)
    let result = client
        .lsp_get_code_actions(
            "gopls",
            DocumentIdentifier::from_buffer_id(0),
            Range {
                start: Position {
                    line: 6,      // Inside fmt.Println call
                    character: 6, // After fmt.P
                },
                end: Position {
                    line: 6,
                    character: 6,
                },
            },
        )
        .await;
    assert!(result.is_ok(), "Failed to get code actions: {result:?}");
    let code_actions = result.unwrap();
    info!("Code actions: {:?}", code_actions);

    // Find the "Inline call to Println" action which requires resolution
    let inline_action = code_actions
        .iter()
        .find(|action| action.title().contains("Inline call to Println"));

    if let Some(action) = inline_action {
        info!("Found inline action: {:?}", action.title());

        // Verify this action needs resolution (no edit, has data)
        assert!(
            action.edit().is_none(),
            "Action should not have edit before resolution"
        );

        // Test resolving the code action
        let code_action_json = serde_json::to_string(action).unwrap();
        let code_action_copy: crate::neovim::CodeAction =
            serde_json::from_str(&code_action_json).unwrap();

        let result = client
            .lsp_resolve_code_action("gopls", code_action_copy)
            .await;
        assert!(result.is_ok(), "Failed to resolve code action: {result:?}");
        let resolved_action = result.unwrap();
        info!("Resolved code action: {:?}", resolved_action);

        // Verify the action was properly resolved
        assert!(
            resolved_action.edit().is_some(),
            "Resolved action should have edit field populated"
        );

        let resolved_edit = resolved_action.edit().unwrap();
        let edit_json = serde_json::to_string(resolved_edit).unwrap();
        info!("Resolved workspace edit: {}", edit_json);

        // Verify the edit contains expected transformations for inlining fmt.Println
        assert!(
            edit_json.contains("Fp"),
            "Resolved edit should contain Fp (Printf) transformation"
        );
        assert!(
            edit_json.contains("os.Stdout"),
            "Resolved edit should contain os.Stdout parameter"
        );
        assert!(
            edit_json.contains("\\t\\\"os\\\""),
            "Resolved edit should add os import"
        );

        info!("✅ Code action resolution validated successfully!");
    } else {
        // List available actions for debugging
        info!("Inline action not found, available actions:");
        for (i, action) in code_actions.iter().enumerate() {
            info!("  Action {}: {}", i, action.title());
        }
        panic!("Expected 'Inline call to Println' action not found");
    }

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_lsp_apply_workspace_edit() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_main.go");

    // Create a Go file with code that gopls will want to modernize
    let go_content = get_testdata_content("main.go");
    fs::write(&temp_file_path, go_content).expect("Failed to write temp Go file");

    let ipc_path = generate_random_ipc_path();
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get buffer diagnostics to find modernization opportunities
    let result = client.get_buffer_diagnostics(0).await;
    assert!(result.is_ok(), "Failed to get diagnostics: {result:?}");
    let diagnostics = result.unwrap();
    info!("Diagnostics: {:?}", diagnostics);

    if let Some(diagnostic) = diagnostics.first() {
        // Get code actions for the diagnostic range
        let result = client
            .lsp_get_code_actions(
                "gopls",
                DocumentIdentifier::from_buffer_id(0),
                Range {
                    start: Position {
                        line: diagnostic.lnum,
                        character: diagnostic.col,
                    },
                    end: Position {
                        line: diagnostic.end_lnum,
                        character: diagnostic.end_col,
                    },
                },
            )
            .await;
        assert!(result.is_ok(), "Failed to get code actions: {result:?}");
        let code_actions = result.unwrap();
        info!("Code actions: {:?}", code_actions);

        // Find the "Replace for loop with range" action that has a workspace edit
        let modernize_action = code_actions.iter().find(|action| {
            action.title().contains("Replace for loop with range") && action.has_edit()
        });

        if let Some(action) = modernize_action {
            info!("Found modernize action: {:?}", action.title());

            // Extract the workspace edit from the code action
            let workspace_edit = action.edit().unwrap().clone();
            info!("Workspace edit to apply: {:?}", workspace_edit);

            // Read original content
            let original_content =
                fs::read_to_string(&temp_file_path).expect("Failed to read original file");
            info!("Original content:\n{}", original_content);

            // Apply the workspace edit using the client
            let result = client
                .lsp_apply_workspace_edit("gopls", workspace_edit)
                .await;
            assert!(result.is_ok(), "Failed to apply workspace edit: {result:?}");

            // Save the buffer to persist changes to disk
            let result = client.execute_lua("vim.cmd('write')").await;
            assert!(result.is_ok(), "Failed to save buffer: {result:?}");

            // File operations should be synchronous in Neovim

            // Read the modified content to verify the change
            let modified_content =
                fs::read_to_string(&temp_file_path).expect("Failed to read modified file");
            info!("Modified content:\n{}", modified_content);

            // Verify that the for loop was modernized
            assert!(
                modified_content.contains("for i := range 10"),
                "Expected modernized for loop with 'range 10', got: {modified_content}"
            );
            assert!(
                !modified_content.contains("for i := 0; i < 10; i++"),
                "Original for loop should be replaced, but still found in: {modified_content}"
            );

            info!("✅ Workspace edit successfully applied and verified!");
        } else {
            info!("No modernize action with workspace edit found, available actions:");
            for action in &code_actions {
                info!("  - {}: edit={}", action.title(), action.has_edit());
            }
            panic!("Expected 'Replace for loop with range' action with workspace edit not found");
        }
    } else {
        info!("No diagnostics found for modernization");
    }

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
async fn test_lsp_definition() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_definition.go");

    // Create a Go file with a function definition and call
    let go_content = r#"package main

import "fmt"

func sayHello(name string) string {
    return "Hello, " + name
}

func main() {
    message := sayHello("World")
    fmt.Println(message)
}
"#;

    fs::write(&temp_file_path, go_content).expect("Failed to write Go file");

    // Setup Neovim with gopls
    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Wait for LSP readiness (diagnostics already waited in auto-connect)
    let lsp_result = client.wait_for_lsp_ready(None, 15000).await;
    assert!(lsp_result.is_ok(), "LSP should be ready");

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    info!("LSP clients: {:?}", lsp_clients);
    assert!(!lsp_clients.is_empty(), "No LSP clients found");

    // Test definition lookup for sayHello function call on line 9 (0-indexed)
    // Position cursor on "sayHello" in the function call
    let result = client
        .lsp_definition(
            "gopls",
            DocumentIdentifier::from_buffer_id(1), // First opened file
            Position {
                line: 9,       // Line with sayHello call
                character: 17, // Position on "sayHello"
            },
        )
        .await;

    assert!(result.is_ok(), "Failed to get definition: {result:?}");
    let definition_result = result.unwrap();
    info!("Definition result found: {:?}", definition_result);
    assert!(
        definition_result.is_some(),
        "Definition result should not be empty"
    );
    let definition_result = definition_result.unwrap();

    // Extract the first location from the definition result
    let first_location = match &definition_result {
        crate::neovim::client::LocateResult::Single(loc) => loc,
        crate::neovim::client::LocateResult::Locations(locs) => {
            assert!(!locs.is_empty(), "No definitions found");
            &locs[0]
        }
        crate::neovim::client::LocateResult::LocationLinks(links) => {
            assert!(!links.is_empty(), "No definitions found");
            // For LocationLinks, we create a Location from the target info
            let link = &links[0];
            assert!(
                link.target_uri.contains("test_definition.go"),
                "Definition should point to the same file"
            );
            // The definition should point to line 4 (0-indexed) where the function is defined
            assert_eq!(
                link.target_range.start.line, 4,
                "Definition should point to line 4 where sayHello function is defined"
            );
            return; // Early return for LocationLinks case
        }
    };

    // For Location cases
    assert!(
        first_location.uri.contains("test_definition.go"),
        "Definition should point to the same file"
    );

    // The definition should point to line 4 (0-indexed) where the function is defined
    assert_eq!(
        first_location.range.start.line, 4,
        "Definition should point to line 4 where sayHello function is defined"
    );

    info!("✅ LSP definition lookup successful!");

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
async fn test_lsp_declaration() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_declaration.zig");

    // Create a Zig file with a function declaration and call
    let zig_content = r#"const std = @import("std");

fn sayHello(allocator: std.mem.Allocator, name: []const u8) ![]u8 {
    return std.fmt.allocPrint(allocator, "Hello, {s}!", .{name});
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const message = try sayHello(allocator, "World");
    defer allocator.free(message);

    std.debug.print("{s}\n", .{message});
}
"#;
    fs::write(&temp_file_path, zig_content).expect("Failed to write Zig file");

    // Setup Neovim with zls (Zig Language Server)
    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    info!("LSP clients: {:?}", lsp_clients);
    assert!(!lsp_clients.is_empty(), "No LSP clients found");

    // Test declaration lookup for sayHello function call on line 11 (0-indexed)
    // Position cursor on "sayHello" in the function call
    let result = client
        .lsp_declaration(
            "zls",
            DocumentIdentifier::from_buffer_id(1), // First opened file
            Position {
                line: 11,      // Line with sayHello call (updated for Zig file format)
                character: 26, // Position on "sayHello"
            },
        )
        .await;

    assert!(result.is_ok(), "Failed to get declaration: {result:?}");
    let declaration_result = result.unwrap();
    info!("Declaration result found: {:?}", declaration_result);
    assert!(
        declaration_result.is_some(),
        "Declaration result should not be empty"
    );

    let declaration_result = declaration_result.unwrap();
    // Extract the first location from the declaration result
    let first_location = match &declaration_result {
        crate::neovim::client::LocateResult::Single(loc) => loc,
        crate::neovim::client::LocateResult::Locations(locs) => {
            assert!(!locs.is_empty(), "No declarations found");
            &locs[0]
        }
        crate::neovim::client::LocateResult::LocationLinks(links) => {
            assert!(!links.is_empty(), "No declarations found");
            // For LocationLinks, we create a Location from the target info
            let link = &links[0];
            assert!(
                link.target_uri.contains("test_declaration.zig"),
                "Declaration should point to the same file"
            );
            // The declaration should point to line 2 (0-indexed) where the function is declared
            assert_eq!(
                link.target_range.start.line, 2,
                "Declaration should point to line 2 where sayHello function is declared"
            );
            info!("✅ LSP declaration lookup successful!");
            // Temp directory and file automatically cleaned up when temp_dir is dropped
            return;
        }
    };

    // For regular Locations, verify the declaration points to the function declaration
    assert!(
        first_location.uri.contains("test_declaration.zig"),
        "Declaration should point to the same file"
    );
    assert_eq!(
        first_location.range.start.line, 2,
        "Declaration should point to line 2 where sayHello function is declared"
    );

    info!("✅ LSP declaration lookup successful!");
    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
async fn test_lsp_type_definition() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_type_definition.go");

    // Create a Go file with a custom type and variable using that type
    let go_content = r#"package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    var user Person
    user.Name = "Alice"
    user.Age = 30
    fmt.Printf("User: %+v\n", user)
}
"#;

    fs::write(&temp_file_path, go_content).expect("Failed to write Go file");

    // Setup Neovim with gopls
    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    info!("LSP clients: {:?}", lsp_clients);
    assert!(!lsp_clients.is_empty(), "No LSP clients found");

    // Test type definition lookup for variable "user" on line 10 (0-indexed)
    // Position cursor on "user" variable declaration
    let result = client
        .lsp_type_definition(
            "gopls",
            DocumentIdentifier::from_buffer_id(1), // First opened file
            Position {
                line: 10,     // Line with var user Person
                character: 8, // Position on "user"
            },
        )
        .await;

    assert!(result.is_ok(), "Failed to get type definition: {result:?}");
    let type_definition_result = result.unwrap();
    info!("Type definition result found: {:?}", type_definition_result);
    assert!(
        type_definition_result.is_some(),
        "Type definition result should not be empty"
    );
    let type_definition_result = type_definition_result.unwrap();

    // Extract the first location from the type definition result
    let first_location = match &type_definition_result {
        crate::neovim::client::LocateResult::Single(loc) => loc,
        crate::neovim::client::LocateResult::Locations(locs) => {
            assert!(!locs.is_empty(), "No type definitions found");
            &locs[0]
        }
        crate::neovim::client::LocateResult::LocationLinks(links) => {
            assert!(!links.is_empty(), "No type definitions found");
            // For LocationLinks, we create a Location from the target info
            let link = &links[0];
            assert!(
                link.target_uri.contains("test_type_definition.go"),
                "Type definition should point to the same file"
            );
            // The type definition should point to line 4 (0-indexed) where the Person type is defined
            assert_eq!(
                link.target_range.start.line, 4,
                "Type definition should point to line 4 where Person type is defined"
            );
            return; // Early return for LocationLinks case
        }
    };

    // For Location cases
    assert!(
        first_location.uri.contains("test_type_definition.go"),
        "Type definition should point to the same file"
    );

    // The type definition should point to line 4 (0-indexed) where the Person type is defined
    assert_eq!(
        first_location.range.start.line, 4,
        "Type definition should point to line 4 where Person type is defined"
    );

    info!("✅ LSP type definition lookup successful!");

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
async fn test_lsp_implementation() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_implementation.go");

    // Create a Go file with an interface and its implementation
    let go_content = r#"package main

import "fmt"

type Greeter interface {
    Greet(name string) string
}

type Person struct {
    Title string
}

func (p Person) Greet(name string) string {
    return fmt.Sprintf("Hello %s, I'm %s", name, p.Title)
}

func main() {
    var g Greeter = Person{Title: "Developer"}
    fmt.Println(g.Greet("World"))
}
"#;

    fs::write(&temp_file_path, go_content).expect("Failed to write Go file");

    // Setup Neovim with gopls
    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    info!("LSP clients: {:?}", lsp_clients);
    assert!(!lsp_clients.is_empty(), "No LSP clients found");

    // Test implementation lookup for "Greet" method in Greeter interface at line 5 (0-indexed)
    // Position cursor on "Greet" method declaration
    let result = client
        .lsp_implementation(
            "gopls",
            DocumentIdentifier::from_buffer_id(1), // First opened file
            Position {
                line: 5,      // Line with Greet method declaration
                character: 4, // Position on "Greet"
            },
        )
        .await;

    assert!(result.is_ok(), "Failed to get implementation: {result:?}");
    let implementation_result = result.unwrap();
    info!("Implementation result found: {:?}", implementation_result);

    // Implementation results might be empty for interface methods without implementations,
    // or contain the concrete implementations
    if let Some(implementation_result) = implementation_result {
        // Extract the first location from the implementation result
        let first_location = match &implementation_result {
            crate::neovim::client::LocateResult::Single(loc) => loc,
            crate::neovim::client::LocateResult::Locations(locs) => {
                assert!(!locs.is_empty(), "No implementations found");
                &locs[0]
            }
            crate::neovim::client::LocateResult::LocationLinks(links) => {
                assert!(!links.is_empty(), "No implementations found");
                // For LocationLinks, we create a Location from the target info
                let link = &links[0];
                assert!(
                    link.target_uri.contains("test_implementation.go"),
                    "Implementation should point to the same file"
                );
                // The implementation should point to line 12 (0-indexed) where the method is implemented
                assert_eq!(
                    link.target_range.start.line, 12,
                    "Implementation should point to line 12 where Greet method is implemented"
                );
                return; // Early return for LocationLinks case
            }
        };

        // For Location cases
        assert!(
            first_location.uri.contains("test_implementation.go"),
            "Implementation should point to the same file"
        );

        // The implementation should point to line 12 (0-indexed) where the method is implemented
        assert_eq!(
            first_location.range.start.line, 12,
            "Implementation should point to line 12 where Greet method is implemented"
        );
    }

    info!("✅ LSP implementation lookup successful!");

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_lsp_rename_with_prepare() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_main.go");

    // Create a Go file with code that gopls can analyze
    let go_content = get_testdata_content("main.go");
    fs::write(&temp_file_path, go_content).expect("Failed to write temp Go file");

    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    let gopls_client = lsp_clients
        .iter()
        .find(|c| c.name == "gopls")
        .expect("gopls client should be available");

    info!("Found gopls client: {:?}", gopls_client);

    // Try to rename the Greet function to GreetUser (line 6, character 5)
    let document = DocumentIdentifier::AbsolutePath(temp_file_path.clone());
    let position = Position {
        line: 6,      // Greet function definition line (0-indexed)
        character: 5, // Position of "Greet" function name
    };

    info!("Testing rename of Greet function to GreetUser...");
    let rename_result = client
        .lsp_rename("gopls", document, position, "GreetUser")
        .await;

    info!("Rename result: {:?}", rename_result);

    if let Ok(Some(workspace_edit)) = rename_result {
        info!("✅ LSP rename successful!");
        info!("Workspace edit: {:?}", workspace_edit);

        // Apply the workspace edit to test the functionality
        info!("Applying workspace edit...");
        let apply_result = client
            .lsp_apply_workspace_edit("gopls", workspace_edit)
            .await;

        assert!(
            apply_result.is_ok(),
            "Failed to apply workspace edit: {:?}",
            apply_result
        );
        info!("✅ LSP workspace edit applied successfully!");

        // Save the buffer to persist changes to disk
        let result = client.execute_lua("vim.cmd('write')").await;
        assert!(result.is_ok(), "Failed to save buffer: {result:?}");

        // File operations should be synchronous in Neovim

        // Read the file content to verify the rename was applied
        let updated_content =
            fs::read_to_string(&temp_file_path).expect("Failed to read updated file");
        info!("Updated content:\n{}", updated_content);

        // The function name should have been changed from "Greet" to "GreetUser"
        assert!(
            updated_content.contains("GreetUser"),
            "File should contain the new function name 'GreetUser'"
        );
        assert!(
            !updated_content.contains("func Greet("),
            "File should no longer contain the old function signature 'func Greet('"
        );
    } else {
        panic!("⚠️ LSP rename not supported or position not renameable");
    }

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
#[cfg(any(unix, windows))]
async fn test_lsp_rename_without_prepare() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_main.go");

    // Create a Go file with code that gopls can analyze
    let go_content = get_testdata_content("main.go");
    fs::write(&temp_file_path, go_content).expect("Failed to write temp Go file");

    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    // Get LSP clients
    let lsp_clients = client.lsp_get_clients().await.unwrap();
    let gopls_client = lsp_clients
        .iter()
        .find(|c| c.name == "gopls")
        .expect("gopls client should be available");

    info!("Found gopls client: {:?}", gopls_client);

    // Try to rename the Greet function to SayHello WITHOUT prepare rename (line 6, character 5)
    let document = DocumentIdentifier::AbsolutePath(temp_file_path.clone());
    let position = Position {
        line: 6,      // Greet function definition line (0-indexed)
        character: 5, // Position of "Greet" function name
    };

    info!("Testing rename of Greet function to SayHello (without prepare)...");
    let rename_result = client
        .lsp_rename("gopls", document, position, "SayHello")
        .await;

    info!("Rename result: {:?}", rename_result);

    if let Ok(Some(workspace_edit)) = rename_result {
        info!("✅ LSP rename successful!");
        info!("Workspace edit: {:?}", workspace_edit);

        // Apply the workspace edit to test the functionality
        info!("Applying workspace edit...");
        let apply_result = client
            .lsp_apply_workspace_edit("gopls", workspace_edit)
            .await;

        assert!(
            apply_result.is_ok(),
            "Failed to apply workspace edit: {:?}",
            apply_result
        );
        info!("✅ LSP workspace edit applied successfully!");

        // Save the buffer to persist changes to disk
        let result = client.execute_lua("vim.cmd('write')").await;
        assert!(result.is_ok(), "Failed to save buffer: {result:?}");

        // File operations should be synchronous in Neovim

        // Read the file content to verify the rename was applied
        let updated_content =
            fs::read_to_string(&temp_file_path).expect("Failed to read updated file");
        info!("Updated content:\n{}", updated_content);

        // The function name should have been changed from "Greet" to "SayHello"
        assert!(
            updated_content.contains("SayHello"),
            "File should contain the new function name 'SayHello'"
        );
        assert!(
            !updated_content.contains("func Greet("),
            "File should no longer contain the old function signature 'func Greet('"
        );
    } else {
        panic!("⚠️ LSP rename not supported or position not renameable");
    }

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

// Helper function to set up Neovim instance with LSP for formatting tests
async fn setup_formatting_test_helper() -> (
    TempDir,
    NeovimIpcGuard,
    NeovimClient<tokio::net::UnixStream>,
) {
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_formatting_split.ts");
    // Create a poorly formatted TypeScript file that needs formatting
    let unformatted_ts_content = r#"import {Console} from 'console';
import    * as fs from 'fs';

interface User{
name:string;
age:number;
}

class UserService{
constructor(private users:User[]=[]){}

addUser(user:User):void{
this.users.push(user);
}

getUsers():User[]{
return this.users;
}
}

function main(){
const service=new UserService();
const user:User={name:"Alice",age:30};
service.addUser(user);
console.log(service.getUsers());
}

main();
"#;

    fs::write(&temp_file_path, unformatted_ts_content)
        .expect("Failed to write temp TypeScript file");

    let ipc_path = generate_random_ipc_path();
    let (client, guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        get_testdata_path("cfg_lsp.lua").to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    (temp_dir, guard, client)
}

#[tokio::test]
#[traced_test]
async fn test_lsp_formatting_and_apply_edits() {
    let (_temp_dir, _guard, client) = setup_formatting_test_helper().await;

    use crate::neovim::FormattingOptions;
    let tab_options = FormattingOptions {
        tab_size: 4,
        insert_spaces: false,
        trim_trailing_whitespace: Some(true),
        insert_final_newline: Some(true),
        trim_final_newlines: Some(false),
        extras: std::collections::HashMap::new(),
    };

    // First get the text edits
    let result = client
        .lsp_formatting("ts_ls", DocumentIdentifier::from_buffer_id(0), tab_options)
        .await;

    assert!(result.is_ok(), "Failed to format with tabs: {result:?}");
    let text_edits = result.unwrap();
    assert!(!text_edits.is_empty(), "Should have text edits to apply");

    // Apply the text edits
    let apply_result = client
        .lsp_apply_text_edits(
            "ts_ls",
            DocumentIdentifier::from_buffer_id(0),
            text_edits.clone(),
        )
        .await;

    assert!(
        apply_result.is_ok(),
        "Failed to apply text edits: {apply_result:?}"
    );
    info!(
        "✅ Successfully applied {} text edits using lsp_apply_text_edits",
        text_edits.len()
    );

    // Verify the buffer content changed by checking it
    let content_check = client
        .execute_lua(r#"return table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")"#)
        .await;

    assert!(
        content_check.is_ok(),
        "Failed to get buffer content after applying text edits: {content_check:?}"
    );
    info!("✅ Buffer content updated after applying text edits");
}

#[tokio::test]
#[traced_test]
async fn test_lsp_apply_text_edits() {
    // Create a temporary directory and file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_file_path = temp_dir.path().join("test_apply_edits.ts");

    // Create a poorly formatted TypeScript file that needs formatting
    let unformatted_ts_content = r#"import {Console} from 'console';
function main(){
console.log("Hello World")
}
main();
"#;
    fs::write(&temp_file_path, unformatted_ts_content)
        .expect("Failed to write temp TypeScript file");

    let ipc_path = generate_random_ipc_path();
    let cfg_path = get_testdata_path("cfg_lsp.lua");
    let (client, _guard) = setup_auto_connected_client_ipc_advance(
        &ipc_path,
        cfg_path.to_str().unwrap(),
        temp_file_path.to_str().unwrap(),
    )
    .await;

    use crate::neovim::FormattingOptions;
    let tab_options = FormattingOptions {
        tab_size: 4,
        insert_spaces: false,
        trim_trailing_whitespace: Some(true),
        insert_final_newline: Some(true),
        trim_final_newlines: Some(false),
        extras: std::collections::HashMap::new(),
    };

    // First get the original buffer content
    let original_content = client
        .execute_lua(r#"return table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")"#)
        .await;
    assert!(
        original_content.is_ok(),
        "Failed to get original buffer content: {original_content:?}"
    );
    let original = original_content.unwrap().as_str().unwrap().to_string();
    info!("Original buffer content length: {}", original.len());

    // Test 1: Get text edits first (without applying)
    let text_edits_result = client
        .lsp_formatting(
            "ts_ls",
            DocumentIdentifier::from_buffer_id(0),
            tab_options.clone(),
        )
        .await;
    assert!(
        text_edits_result.is_ok(),
        "Failed to get text edits for formatting: {text_edits_result:?}"
    );

    let text_edits = text_edits_result.unwrap();
    info!("✅ Got {} text edits for formatting", text_edits.len());

    // Test 2: Apply the text edits
    let apply_result = client
        .lsp_apply_text_edits("ts_ls", DocumentIdentifier::from_buffer_id(0), text_edits)
        .await;

    assert!(
        apply_result.is_ok(),
        "Failed to apply text edits: {apply_result:?}"
    );
    info!("✅ Successfully applied text edits");

    // Test 3: Verify the buffer content changed
    let new_content = client
        .execute_lua(r#"return table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")"#)
        .await;
    assert!(
        new_content.is_ok(),
        "Failed to get new buffer content after applying text edits: {new_content:?}"
    );
    let new = new_content.unwrap().as_str().unwrap().to_string();
    info!("New buffer content length: {}", new.len());

    // The content should be different after formatting
    assert_ne!(
        original, new,
        "Buffer content should have changed after applying text edits"
    );

    // Temp directory and file automatically cleaned up when temp_dir is dropped
}

#[tokio::test]
#[traced_test]
async fn test_lsp_range_formatting_and_apply_edits() {
    let (_temp_dir, _guard, client) = setup_formatting_test_helper().await;

    use crate::neovim::FormattingOptions;
    let tab_options = FormattingOptions {
        tab_size: 4,
        insert_spaces: false,
        trim_trailing_whitespace: Some(true),
        insert_final_newline: Some(true),
        trim_final_newlines: Some(false),
        extras: std::collections::HashMap::new(),
    };

    // First get the text edits for a specific range
    let range = Range {
        start: Position {
            line: 0,
            character: 0,
        },
        end: Position {
            line: 5,
            character: 0,
        }, // First few lines
    };
    let result = client
        .lsp_range_formatting(
            "ts_ls",
            DocumentIdentifier::from_buffer_id(0),
            range,
            tab_options,
        )
        .await;

    assert!(
        result.is_ok(),
        "Failed to format range with tabs: {result:?}"
    );
    let text_edits = result.unwrap();
    assert!(
        !text_edits.is_empty(),
        "Should have text edits to apply for range formatting"
    );

    // get the original buffer content
    let original_content = client
        .execute_lua(r#"return table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")"#)
        .await;
    assert!(
        original_content.is_ok(),
        "Failed to get original buffer content: {original_content:?}"
    );
    let original = original_content.unwrap().as_str().unwrap().to_string();
    info!("Original buffer content length: {}", original.len());

    // Apply the text edits
    let apply_result = client
        .lsp_apply_text_edits(
            "ts_ls",
            DocumentIdentifier::from_buffer_id(0),
            text_edits.clone(),
        )
        .await;

    assert!(
        apply_result.is_ok(),
        "Failed to apply text edits from range formatting: {apply_result:?}"
    );
    info!(
        "✅ Successfully applied {} text edits from range formatting using lsp_apply_text_edits",
        text_edits.len()
    );

    // Verify the buffer content changed by checking it
    let new_content = client
        .execute_lua(r#"return table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")"#)
        .await;

    assert!(
        new_content.is_ok(),
        "Failed to get buffer content after applying range text edits: {new_content:?}"
    );
    info!("✅ Buffer content updated after applying range text edits");
    let new = new_content.unwrap().as_str().unwrap().to_string();
    info!("New buffer content length: {}", new.len());

    // The content should be different after formatting
    assert_ne!(
        original, new,
        "Buffer content should have changed after applying text edits"
    );
}