-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunified.lua
More file actions
1273 lines (1068 loc) · 41.5 KB
/
Copy pathunified.lua
File metadata and controls
1273 lines (1068 loc) · 41.5 KB
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
-- Unified display for diffusion.nvim diff system
-- Shows the NEW file content with virtual text for deletions (like claudecode.nvim)
-- Enhanced with vgit-style word-level highlighting using pure Lua diff engine
--
-- ============================================================================
-- PROVIDER-AGNOSTIC DESIGN VIOLATIONS - REFACTORING REQUIRED
-- ============================================================================
--
-- This file contains provider-specific conditionals that should be configuration-driven.
-- Display logic should not have hardcoded provider checks.
--
-- CRITICAL VIOLATIONS:
-- 1. Protocol-Specific Display Logic (line 63):
-- if diff_entry.protocol == "claude" then
-- -- Claude-specific display behavior
-- end
-- VIOLATION: Display logic should not check specific providers
-- FIX: Use display configuration from diff_entry
--
-- 2. Multiple Protocol Checks (lines 1137, 1154, 1179):
-- protocol = "claude" -- Hardcoded protocol assignment
-- VIOLATION: Test/demo code with hardcoded provider
-- FIX: Use configuration or remove test code
--
-- 3. Missing Display Strategy Abstraction:
-- - No configuration for provider-specific display differences
-- - Display variations should be data-driven, not code-driven
--
-- PLANNED REFACTORING:
-- Phase 1: Remove protocol conditionals
-- Replace: if diff_entry.protocol == "claude" then
-- With: if diff_entry.display_config.show_virtual_text then
--
-- Phase 2: Configuration-driven display
-- display_config = {
-- show_deletions_as_virtual = true,
-- highlight_word_diff = true,
-- show_stats_in_winbar = true
-- }
--
-- Phase 3: Remove hardcoded test protocols
-- - Remove or parameterize test code
-- - Use mock providers for testing
--
-- TARGET: Zero provider checks in display logic, all behavior configuration-driven
-- ============================================================================
local UnifiedDisplay = {}
local DiffStats = require('diffusion.utils.diff_stats')
local DiffEngine = require('diffusion.diff.engine')
-- Module-level caches for performance (avoid per-call allocation)
local _cached_engine = nil
local _cached_logger = nil
local function get_engine()
if not _cached_engine then
_cached_engine = DiffEngine:new()
end
return _cached_engine
end
local function get_logger()
if not _cached_logger then
_cached_logger = require('diffusion.utils.logger'):child("UnifiedDisplay")
end
return _cached_logger
end
-- Efficient filetype mapping - created once at module load
local FILETYPE_MAP = {
js = "javascript",
ts = "typescript",
jsx = "javascriptreact",
tsx = "typescriptreact",
py = "python",
md = "markdown",
sh = "bash",
yaml = "yaml",
yml = "yaml",
json = "json",
html = "html",
css = "css",
scss = "scss",
vue = "vue"
}
-- Namespace for diff highlighting
local ns_id = vim.api.nvim_create_namespace("diffusion_unified_diff")
-- Helper function to efficiently detect and set filetype
local function set_buffer_filetype(bufnr, file_path)
local stripped = file_path:gsub("%s*%(diff%)", "")
local extension = stripped:match("%.([^%.]+)$")
-- DIAG: diff-display filetype detection. Compares our extension-based
-- map against what vim.filetype.match would return — surfaces cases like
-- htmldjango/jinja that the static map misses.
do
local logger = get_logger()
local mapped = extension and (FILETYPE_MAP[extension] or extension) or nil
local native_ok, native_ft = pcall(vim.filetype.match, { filename = stripped })
logger:info("DIAG diff-display set_buffer_filetype", {
file = file_path,
stripped = stripped,
extension = extension,
mapped_ft = mapped,
vim_filetype_match_ft = native_ok and native_ft or nil,
})
end
if extension then
local filetype = FILETYPE_MAP[extension] or extension
local ok, _ = pcall(function() vim.bo[bufnr].filetype = filetype end)
if not ok then
vim.api.nvim_buf_call(bufnr, function()
vim.cmd("filetype detect")
end)
end
else
vim.api.nvim_buf_call(bufnr, function()
vim.cmd("filetype detect")
end)
end
end
function UnifiedDisplay:create(diff_entry, events)
local logger = get_logger()
logger:debug("Creating unified diff view", {
id = diff_entry.id,
file = diff_entry.file_path
})
-- Use cached hunks from DiffManager (generated once during entry creation)
-- This eliminates duplicate git diff generation for provider-agnostic performance
local hunks = diff_entry.hunks or {}
-- Create buffer with vgit-style unified diff (includes removed lines in buffer)
local unified_buf = self:_create_vgit_unified_buffer(diff_entry, hunks)
if not unified_buf then
logger:error("Failed to create unified buffer")
return false
end
-- Store buffer reference
diff_entry.buffers = {
unified_bufnr = unified_buf,
main_bufnr = unified_buf
}
-- Create window and show content
local success = self:_create_unified_window(diff_entry)
if not success then
self:cleanup(diff_entry)
return false
end
-- Apply vgit-style highlighting to the unified buffer (removed lines are in buffer with syntax)
local change_lines = self:_apply_vgit_buffer_highlighting(unified_buf)
-- Setup folding if there are changes
if #change_lines > 0 then
self:_setup_unified_folding(unified_buf, change_lines)
-- Navigate to first change
if diff_entry.windows and diff_entry.windows.unified then
local first_line = type(change_lines[1]) == "table" and change_lines[1].line or change_lines[1]
vim.api.nvim_win_set_cursor(diff_entry.windows.unified, {first_line, 0})
end
end
-- Setup Claude-branded winbar
self:_setup_claude_winbar(diff_entry, hunks)
-- Setup interactive keybindings when provider uses deferred response mode
local behavior = diff_entry.behavior or {}
if behavior.response_mode == "deferred" then
self:_setup_interactive_keybindings(diff_entry, events)
end
logger:info("Unified diff view created", {
id = diff_entry.id,
buffer = unified_buf
})
return true
end
function UnifiedDisplay:update(diff_entry, update_params)
local logger = get_logger()
if not diff_entry.buffers or not diff_entry.buffers.unified_bufnr then
return false
end
-- Update content and regenerate unified diff
if update_params.new_content then
diff_entry.new_content = update_params.new_content
-- Update buffer with new content lines
local lines = vim.split(update_params.new_content, "\n", { plain = true })
if lines[#lines] == "" then
table.remove(lines)
end
-- Step 1: write content immediately (cheap O(n) — keeps display in sync with stream)
local success = pcall(function()
vim.bo[diff_entry.buffers.unified_bufnr].modifiable = true
vim.api.nvim_buf_set_lines(diff_entry.buffers.unified_bufnr, 0, -1, false, lines)
vim.bo[diff_entry.buffers.unified_bufnr].modifiable = false
end)
if success then
-- Step 2: debounce Myers diff regeneration — only run after stream pauses 150ms.
-- Running generate_unified() on every streaming chunk is O(n²) total for an
-- n-character stream. The buffer content is already up-to-date from Step 1;
-- highlighting just lags slightly behind until the stream settles.
if diff_entry._regen_timer then
diff_entry._regen_timer:stop()
diff_entry._regen_timer:close()
diff_entry._regen_timer = nil
end
diff_entry._regen_timer = vim.loop.new_timer()
diff_entry._regen_timer:start(150, 0, vim.schedule_wrap(function()
diff_entry._regen_timer = nil
local bufnr = diff_entry.buffers and diff_entry.buffers.unified_bufnr
if not bufnr or not pcall(vim.api.nvim_buf_is_valid, bufnr) then return end
local diff_engine = get_engine()
local unified = diff_engine:generate_unified(diff_entry.old_content or "", diff_entry.new_content)
local hunks = unified.hunks or {}
diff_entry.hunks = hunks
diff_entry.lnum_changes = unified.lnum_changes
local change_lines = self:_apply_unified_highlighting(bufnr, hunks)
if #change_lines > 0 then
self:_setup_unified_folding(bufnr, change_lines)
end
logger:debug("Updated unified display highlighting", { id = diff_entry.id })
end))
logger:debug("Updated unified display content", { id = diff_entry.id })
end
return success
end
return false
end
function UnifiedDisplay:cleanup(diff_entry)
local logger = get_logger()
-- Cancel any pending Myers regen timer so it doesn't fire after the diff is dismissed
if diff_entry._regen_timer then
diff_entry._regen_timer:stop()
diff_entry._regen_timer:close()
diff_entry._regen_timer = nil
end
logger:debug("Cleaning up unified display", { id = diff_entry.id })
-- Note: Buffer and window cleanup is now handled by DiffManager:_cleanup_diff_resources
-- This function should only clean up display-specific resources
local bufnr = diff_entry.buffers and diff_entry.buffers.unified_bufnr
-- Clear virtual text namespace first
if bufnr and pcall(vim.api.nvim_buf_is_valid, bufnr) then
local ns_id = pcall(vim.api.nvim_create_namespace, "diffusion_unified_diff")
if ns_id and ns_id ~= 0 then
pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns_id, 0, -1)
end
-- Clean up topfill autocmd group
pcall(vim.api.nvim_del_augroup_by_name, "ClaudeCodeUnifiedDiffTopfill_" .. bufnr)
-- Clear any diff-specific variables
pcall(function()
vim.api.nvim_buf_del_var(bufnr, 'diffusion_diff_role')
vim.api.nvim_buf_del_var(bufnr, 'diffusion_diff_id')
end)
end
logger:debug("Unified display cleanup completed", { id = diff_entry.id })
end
-- Private methods
function UnifiedDisplay:_generate_git_diff(diff_entry)
local old_content = diff_entry.old_content or ""
local new_content = diff_entry.new_content or ""
-- Comprehensive content normalization
local normalized_old_content = self:_normalize_content(old_content)
local normalized_new_content = self:_normalize_content(new_content)
-- Create temporary files for git diff
local tmp_dir = vim.fn.tempname()
vim.fn.mkdir(tmp_dir, "p")
local old_tmp = tmp_dir .. "/old"
local new_tmp = tmp_dir .. "/new"
-- Write old content
local old_file = io.open(old_tmp, "w")
if old_file then
old_file:write(normalized_old_content)
old_file:close()
else
return nil
end
-- Write new content
local new_file = io.open(new_tmp, "w")
if new_file then
new_file:write(normalized_new_content)
new_file:close()
else
return nil
end
-- Generate unified diff using git
local result = vim.fn.system({
"git",
"diff",
"--no-index",
"--no-prefix",
"--unified=3",
old_tmp,
new_tmp,
})
local exit_code = vim.v.shell_error
-- Clean up temp files
os.remove(old_tmp)
os.remove(new_tmp)
vim.fn.delete(tmp_dir, "d")
-- Git diff returns exit code 1 when there are differences, which is normal
if exit_code > 1 then
return nil
end
return result
end
-- Normalize content to prevent false whole-file differences
function UnifiedDisplay:_normalize_content(content)
if not content or content == "" then
return ""
end
-- Only normalize line endings, don't change trailing newline behavior
content = content:gsub("\r\n", "\n"):gsub("\r", "\n")
return content
end
function UnifiedDisplay:_parse_unified_diff(diff_output)
local hunks = {}
local current_hunk = nil
for line in diff_output:gmatch("[^\n]*") do
-- Parse hunk header: @@ -old_start,old_count +new_start,new_count @@
local old_start, old_count, new_start, new_count = line:match("^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@")
if old_start then
current_hunk = {
old_start = tonumber(old_start),
old_count = tonumber(old_count) or 1,
new_start = tonumber(new_start),
new_count = tonumber(new_count) or 1,
lines = {},
}
table.insert(hunks, current_hunk)
elseif current_hunk then
-- Skip "No newline at end of file" markers
if not line:match("^\\ No newline at end of file") then
-- Parse diff line content
local prefix = line:sub(1, 1)
local content = line:sub(2)
if prefix == "+" then
table.insert(current_hunk.lines, { type = "add", content = content })
elseif prefix == "-" then
table.insert(current_hunk.lines, { type = "remove", content = content })
elseif prefix == " " then
table.insert(current_hunk.lines, { type = "context", content = content })
end
end
end
end
return hunks
end
function UnifiedDisplay:_create_vgit_unified_buffer(diff_entry, hunks)
-- Determine buffer name
local buffer_name = diff_entry.file_path .. " (diff)"
-- Check if buffer already exists and reuse it
local existing_bufnr = vim.fn.bufnr(buffer_name)
local bufnr
if existing_bufnr ~= -1 and vim.api.nvim_buf_is_valid(existing_bufnr) then
bufnr = existing_bufnr
-- Set buffer to modifiable before clearing content
vim.bo[bufnr].modifiable = true
-- Clear buffer content
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {})
else
-- Create new buffer
bufnr = vim.api.nvim_create_buf(false, true)
if bufnr == 0 then
return nil
end
vim.api.nvim_buf_set_name(bufnr, buffer_name)
end
-- Set buffer options
vim.bo[bufnr].buftype = "nofile"
vim.bo[bufnr].bufhidden = "wipe"
vim.bo[bufnr].modifiable = true
-- Generate vgit-style unified content by inserting removed lines into buffer
local unified_lines = self:_generate_vgit_unified_content(diff_entry.new_content or "", hunks)
if unified_lines[#unified_lines] == "" then
table.remove(unified_lines)
end
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, unified_lines)
-- Make buffer non-modifiable
vim.bo[bufnr].modifiable = false
-- Detect and set filetype for syntax highlighting
set_buffer_filetype(bufnr, diff_entry.file_path)
-- Enable syntax highlighting
vim.api.nvim_buf_call(bufnr, function()
vim.cmd("syntax enable")
end)
-- Set diff-specific variables
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_mode', 'unified')
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_id', diff_entry.id)
return bufnr
end
-- Generate vgit-style unified content by inserting removed lines into the buffer
function UnifiedDisplay:_generate_vgit_unified_content(new_content, hunks)
local lines = vim.split(new_content, "\n", { plain = true })
if lines[#lines] == "" then
table.remove(lines)
end
-- Create final buffer with removed lines inserted (like vgit)
local final_lines = {}
local line_mapping = {} -- Maps final buffer line numbers to their types
local buffer_line_num = 1
-- Sort hunks by old line position for sequential processing
table.sort(hunks, function(a, b) return a.old_start < b.old_start end)
local original_line_ptr = 1
for _, hunk in ipairs(hunks) do
-- Add context lines before this hunk
while original_line_ptr < hunk.new_start do
if lines[original_line_ptr] then
table.insert(final_lines, lines[original_line_ptr])
line_mapping[buffer_line_num] = { type = 'context', original_line = original_line_ptr }
buffer_line_num = buffer_line_num + 1
end
original_line_ptr = original_line_ptr + 1
end
-- Process hunk lines in sequence (removed first, then added/context)
for _, line in ipairs(hunk.lines) do
if line.type == "remove" then
-- Insert removed line in buffer
table.insert(final_lines, line.content)
line_mapping[buffer_line_num] = { type = 'remove', content = line.content }
buffer_line_num = buffer_line_num + 1
elseif line.type == "add" then
-- Insert added line in buffer (this is from the new content)
table.insert(final_lines, line.content)
line_mapping[buffer_line_num] = { type = 'add', content = line.content }
buffer_line_num = buffer_line_num + 1
original_line_ptr = original_line_ptr + 1
elseif line.type == "context" then
-- Context line (unchanged)
if lines[original_line_ptr] then
table.insert(final_lines, lines[original_line_ptr])
line_mapping[buffer_line_num] = { type = 'context', original_line = original_line_ptr }
buffer_line_num = buffer_line_num + 1
end
original_line_ptr = original_line_ptr + 1
end
end
end
-- Add any remaining lines after all hunks
while original_line_ptr <= #lines do
table.insert(final_lines, lines[original_line_ptr])
line_mapping[buffer_line_num] = { type = 'context', original_line = original_line_ptr }
buffer_line_num = buffer_line_num + 1
original_line_ptr = original_line_ptr + 1
end
-- Store line mapping for highlighting
self._line_mapping = line_mapping
return final_lines
end
-- Apply vgit-style highlighting to the unified buffer where removed lines are actual buffer content
function UnifiedDisplay:_apply_vgit_buffer_highlighting(bufnr)
if not self._line_mapping then
return {}
end
-- Setup vgit-style highlight groups
self:_setup_vgit_highlight_groups()
-- Create namespace for diff highlighting
local ns_id = vim.api.nvim_create_namespace("diffusion_unified_vgit_diff")
-- Clear existing highlighting
vim.api.nvim_buf_clear_namespace(bufnr, ns_id, 0, -1)
local change_lines = {}
-- Apply background highlighting to each line based on its type
for line_num, line_info in ipairs(self._line_mapping) do
local line_idx = line_num - 1 -- Convert to 0-indexed for extmarks
if line_info.type == 'remove' then
-- Red background for removed lines (like vgit)
vim.api.nvim_buf_set_extmark(bufnr, ns_id, line_idx, 0, {
line_hl_group = 'DiffDelete',
sign_text = '-',
sign_hl_group = 'GitSignsDelete',
})
table.insert(change_lines, {
line = line_num,
type = 'remove'
})
elseif line_info.type == 'add' then
-- Green background for added lines (like vgit)
vim.api.nvim_buf_set_extmark(bufnr, ns_id, line_idx, 0, {
line_hl_group = 'DiffAdd',
sign_text = '+',
sign_hl_group = 'GitSignsAdd',
})
table.insert(change_lines, {
line = line_num,
type = 'add'
})
end
-- 'context' lines get no special highlighting (syntax highlighting preserved)
end
return change_lines
end
function UnifiedDisplay:_create_content_buffer(diff_entry)
-- Determine buffer name
local buffer_name = diff_entry.file_path .. " (diff)"
-- Check if buffer already exists and reuse it
local existing_bufnr = vim.fn.bufnr(buffer_name)
local bufnr
if existing_bufnr ~= -1 and vim.api.nvim_buf_is_valid(existing_bufnr) then
bufnr = existing_bufnr
-- Set buffer to modifiable before clearing content
vim.bo[bufnr].modifiable = true
-- Clear buffer content
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {})
else
-- Create new buffer
bufnr = vim.api.nvim_create_buf(false, true)
if bufnr == 0 then
return nil
end
vim.api.nvim_buf_set_name(bufnr, buffer_name)
end
-- Set buffer options
vim.bo[bufnr].buftype = "nofile"
vim.bo[bufnr].bufhidden = "wipe"
vim.bo[bufnr].modifiable = true
-- Put Claude's PURE final content in buffer (like claudecode.nvim)
-- This is the key insight: show the NEW content, then highlight additions within it
local content = diff_entry.new_content or ""
local lines = vim.split(content, "\n", { plain = true })
if lines[#lines] == "" then
table.remove(lines)
end
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
-- Make buffer non-modifiable
vim.bo[bufnr].modifiable = false
-- Detect and set filetype based on file extension
set_buffer_filetype(bufnr, diff_entry.file_path)
-- Enable syntax highlighting
vim.api.nvim_buf_call(bufnr, function()
vim.cmd("syntax enable")
end)
-- Set diff-specific variables
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_mode', 'unified')
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_id', diff_entry.id)
return bufnr
end
function UnifiedDisplay:_create_diff_buffer(diff_lines, diff_entry)
-- Determine buffer name
local buffer_name = diff_entry.file_path .. " (diff)"
-- Check if buffer already exists and reuse it
local existing_bufnr = vim.fn.bufnr(buffer_name)
local bufnr
if existing_bufnr ~= -1 and vim.api.nvim_buf_is_valid(existing_bufnr) then
bufnr = existing_bufnr
-- Set buffer to modifiable before clearing content
vim.bo[bufnr].modifiable = true
-- Clear buffer content
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {})
else
-- Create new buffer
bufnr = vim.api.nvim_create_buf(false, true)
if bufnr == 0 then
return nil
end
vim.api.nvim_buf_set_name(bufnr, buffer_name)
end
-- Set buffer options
vim.bo[bufnr].buftype = "nofile"
vim.bo[bufnr].bufhidden = "wipe"
vim.bo[bufnr].modifiable = true
-- Set diff lines content (includes removed lines inserted like vgit)
-- This is different from claudecode - we show ALL content including removals
if diff_lines[#diff_lines] == "" then
table.remove(diff_lines)
end
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, diff_lines)
-- Make buffer non-modifiable
vim.bo[bufnr].modifiable = false
-- Detect and set filetype based on file extension
set_buffer_filetype(bufnr, diff_entry.file_path)
-- Enable syntax highlighting
vim.api.nvim_buf_call(bufnr, function()
vim.cmd("syntax enable")
end)
-- Set diff-specific variables
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_mode', 'unified')
vim.api.nvim_buf_set_var(bufnr, 'diffusion_diff_id', diff_entry.id)
return bufnr
end
function UnifiedDisplay:_create_unified_window(diff_entry)
local bufnr = diff_entry.buffers.unified_bufnr
local success = pcall(function()
-- Unified mode reuses the user's current window — this IS their window,
-- not a disposable one. Mutating window-local opts here permanently
-- taints their config (number/relativenumber/signcolumn/foldcolumn/
-- wrap are not diff-managed and aren't restored on dismiss). Leave
-- them alone; the user's config is the right default for their window.
local win = vim.api.nvim_get_current_win()
vim.api.nvim_win_set_buf(win, bufnr)
diff_entry.windows = {
unified = win,
main = win
}
end)
return success
end
function UnifiedDisplay:_setup_winbar(diff_entry)
if not diff_entry.windows or not diff_entry.windows.unified then
return
end
local win = diff_entry.windows.unified
if not vim.api.nvim_win_is_valid(win) then
return
end
local protocol_icon = self:_get_protocol_icon(diff_entry.protocol)
local filename = vim.fn.fnamemodify(diff_entry.file_path, ":t")
-- Calculate diff stats
local stats = DiffStats.calculate_diff_stats(diff_entry)
local winbar_content = string.format(
"%%#%s#%s%%* → %%#Normal#%s [Unified]%%* | %%#DiffAdd#+%d%%* %%#DiffDelete#-%d%%* %%#DiffChange#~%d%%* lines",
self:_get_protocol_highlight(diff_entry.protocol),
protocol_icon,
filename,
stats.added,
stats.removed,
stats.modified
)
pcall(vim.api.nvim_set_option_value, "winbar", winbar_content, { win = win })
end
-- Yet another line added for precise highlighting functionality
function UnifiedDisplay:_update_buffer_content(bufnr, diff_content)
if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then
return false
end
vim.schedule(function()
-- Temporarily make buffer modifiable
local was_readonly = vim.bo[bufnr].readonly
local was_modifiable = vim.bo[bufnr].modifiable
vim.bo[bufnr].readonly = false
vim.bo[bufnr].modifiable = true
-- Update content
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, diff_content.lines)
-- Restore original settings
vim.bo[bufnr].readonly = was_readonly
vim.bo[bufnr].modifiable = was_modifiable
end)
return true
end
function UnifiedDisplay:_detect_filetype(file_path)
if not file_path then
return 'text'
end
-- Use Neovim's built-in filetype detection
local filetype = vim.filetype.match({ filename = file_path })
return filetype or 'text'
end
function UnifiedDisplay:_get_protocol_icon(protocol)
local icons = {
claude = "🤖",
opencode = "⚡",
codex = "🔧",
unknown = "📝"
}
return icons[protocol] or icons.unknown
end
function UnifiedDisplay:_get_protocol_highlight(protocol)
local highlights = {
claude = "DiagnosticSignWarn",
opencode = "DiagnosticSignInfo",
codex = "DiagnosticSignHint",
unknown = "Normal"
}
return highlights[protocol] or highlights.unknown
end
-- Enhanced unified highlighting with vgit-style word-level highlighting (fixed virtual text)
function UnifiedDisplay:_apply_unified_highlighting(unified_buf, hunks)
-- Use single namespace like claudecode.nvim (this is the key fix!)
local ns_id = vim.api.nvim_create_namespace("diffusion_unified_diff")
-- Setup vgit-style highlight groups for proper removed line highlighting
self:_setup_vgit_highlight_groups()
-- Clear existing highlighting
vim.api.nvim_buf_clear_namespace(unified_buf, ns_id, 0, -1)
local change_lines = {}
local buf_line_count = vim.api.nvim_buf_line_count(unified_buf)
local has_deletion_at_start = false
local deleted_lines_at_start = 0
for _, hunk in ipairs(hunks) do
-- Track both old and new line positions separately
local old_line_idx = hunk.old_start - 1 -- 0-indexed, for tracking deletions
local new_line_idx = hunk.new_start - 1 -- 0-indexed, for tracking additions
for _, line in ipairs(hunk.lines) do
if line.type == "add" then
-- Highlight added line (without gutter sign)
if new_line_idx < buf_line_count then
vim.api.nvim_buf_set_extmark(unified_buf, ns_id, new_line_idx, 0, {
line_hl_group = "DiffAdd",
})
table.insert(change_lines, new_line_idx + 1) -- 1-indexed for navigation
end
new_line_idx = new_line_idx + 1
elseif line.type == "remove" then
-- Show removed line as virtual text above the current new line position
-- This shows deletions at the position where they occurred in the old file
local attach_line
if new_line_idx == 0 then
-- Deletions at the very beginning
attach_line = 0
has_deletion_at_start = true
deleted_lines_at_start = deleted_lines_at_start + 1
else
-- Attach deletions to the line where they would appear in the new content
-- Use new_line_idx directly (not new_line_idx - 1) so deletions appear
-- above the line that replaced them or the next context line
attach_line = math.min(new_line_idx, buf_line_count - 1)
end
-- Track deletion position for navigation (use attach_line for navigation)
if attach_line < buf_line_count then
table.insert(change_lines, attach_line + 1) -- 1-indexed for navigation
end
-- Show deleted content as virtual text above with proper vgit-style highlighting
vim.api.nvim_buf_set_extmark(unified_buf, ns_id, attach_line, 0, {
virt_lines = { { { "- " .. line.content, "GitDeletedLine" } } },
virt_lines_above = true,
})
-- Only increment old line index for removed lines
old_line_idx = old_line_idx + 1
elseif line.type == "context" then
-- Context line - increment both counters
old_line_idx = old_line_idx + 1
new_line_idx = new_line_idx + 1
end
end
end
-- Apply topfill workaround if we have deletions at the beginning
if has_deletion_at_start then
-- Create an autocmd group for this buffer (like claudecode.nvim)
local augroup = vim.api.nvim_create_augroup("ClaudeCodeUnifiedDiffTopfill_" .. unified_buf, { clear = true })
-- Set topfill for virtual text above first line
local topfill = deleted_lines_at_start
-- Apply topfill in the next tick to ensure window is ready
vim.schedule(function()
local win = vim.fn.bufwinid(unified_buf)
if win > 0 then
vim.fn.win_execute(win, "lua vim.fn.winrestview({ topfill = " .. topfill .. " })")
-- Set up autocmd to maintain topfill on cursor movement (like claudecode.nvim)
vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, {
group = augroup,
buffer = unified_buf,
callback = function()
local current_win = vim.fn.bufwinid(unified_buf)
if current_win > 0 then
vim.fn.win_execute(current_win, "lua vim.fn.winrestview({ topfill = " .. topfill .. " })")
end
end,
})
end
end)
end
-- Sort and deduplicate change_lines for proper navigation order
local unique_lines = {}
local seen = {}
for _, line_num in ipairs(change_lines) do
if not seen[line_num] then
seen[line_num] = true
table.insert(unique_lines, line_num)
end
end
table.sort(unique_lines)
return unique_lines
end
-- Setup vgit-style highlight groups for proper diff visualization
function UnifiedDisplay:_setup_vgit_highlight_groups()
-- Define proper highlight groups for removed lines (red background like vgit)
vim.api.nvim_set_hl(0, 'GitDeletedLine', {
fg = '#ffffff',
bg = '#5c1e1e', -- Dark red background like vgit
bold = false
})
-- Don't override DiffAdd - let it use default colors
-- Word-level highlights like vgit (in case we add word-level diffing later)
vim.api.nvim_set_hl(0, 'GitWordAdd', {
fg = nil,
bg = '#5f875f', -- Green background
bold = true
})
vim.api.nvim_set_hl(0, 'GitWordDelete', {
fg = nil,
bg = '#875f5f', -- Red background
bold = true
})
end
function UnifiedDisplay:_apply_enhanced_unified_highlighting(unified_buf, unified_diff)
-- Use single namespace like claudecode.nvim
local ns_id = vim.api.nvim_create_namespace("diffusion_unified_diff")
-- Clear existing highlighting
vim.api.nvim_buf_clear_namespace(unified_buf, ns_id, 0, -1)
local change_lines = {}
local buf_line_count = vim.api.nvim_buf_line_count(unified_buf)
-- Group removed lines by attach position for proper virtual text display
local removed_lines_by_position = {}
local added_lines = {}
-- First pass: collect and group changes
for _, lnum_change in ipairs(unified_diff.lnum_changes or {}) do
if lnum_change.type == "add" then
table.insert(added_lines, lnum_change)
elseif lnum_change.type == "remove" then
local attach_pos = lnum_change.lnum
if not removed_lines_by_position[attach_pos] then
removed_lines_by_position[attach_pos] = {}
end
table.insert(removed_lines_by_position[attach_pos], lnum_change)
end
end
-- Second pass: apply added line highlighting
for _, lnum_change in ipairs(added_lines) do
local line_num = lnum_change.lnum
if line_num <= buf_line_count then
local line_idx = line_num - 1 -- Convert to 0-indexed
-- Apply line highlighting first
vim.api.nvim_buf_set_extmark(unified_buf, ns_id, line_idx, 0, {
line_hl_group = "DiffAdd",
})
-- Add word-level highlighting if available
if lnum_change.word_diff then
self:_apply_word_diff_highlighting(unified_buf, ns_id, line_idx, lnum_change.word_diff, "add")
end
table.insert(change_lines, line_num)
end
end
-- Third pass: apply removed line virtual text (grouped by position)
for attach_pos, removed_lines in pairs(removed_lines_by_position) do
local attach_line = math.max(0, math.min(attach_pos - 1, buf_line_count - 1))
-- Create continuous virtual lines for all removed content at this position
local virtual_lines = {}
for _, lnum_change in ipairs(removed_lines) do
local line_content = lnum_change.line_content or ""
if lnum_change.word_diff then
-- Create word-diff highlighted virtual line
local segments = self:_create_word_diff_virtual_text(lnum_change.word_diff, "remove")
table.insert(virtual_lines, segments)
else
-- Create syntax-aware virtual line segments
local segments = self:_create_syntax_aware_virtual_text(line_content, unified_buf)
table.insert(virtual_lines, segments)
end
end
-- Apply all virtual lines at once for continuous display
if #virtual_lines > 0 then
vim.api.nvim_buf_set_extmark(unified_buf, ns_id, attach_line, 0, {
virt_lines = virtual_lines,
virt_lines_above = true,
})
table.insert(change_lines, attach_line + 1) -- 1-indexed for navigation
end
end
-- Sort and deduplicate change_lines for proper navigation order
local unique_lines = {}