robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2---<pre>help 3---:DiffTool {left} {right} *:DiffTool* 4---Compares two directories or files side-by-side. 5---Supports directory diffing, rename detection, and highlights changes 6---in quickfix list. Replaces the built-in `nvim -d` diff mode with this interface. 7---</pre> 8--- 9--- The plugin is not loaded by default; use `:packadd` to activate it: 10--- ``` 11--- :packadd nvim.difftool 12--- ``` 13--- 14--- Example `git difftool -d` integration using `nvim -d` replacement: 15--- 16--- ```ini 17--- [difftool "nvim_difftool"] 18--- cmd = nvim -c \"packadd nvim.difftool\" -d \"$LOCAL\" \"$REMOTE\" 19--- [diff] 20--- tool = nvim_difftool 21--- ``` 22 23local highlight_groups ={ 24A ='DiffAdd' , 25D ='DiffDelete' , 26M ='DiffText' , 27R ='DiffChange' , 28} 29 30local layout ={ 31group =nil , --- @type integer? 32left_win =nil , --- @type integer? 33right_win =nil , --- @type integer? 34} 35 36local util =require ( 'vim._core.util' ) 37 38--- Clean up the layout state, autocmds and quickfix list 39--- @param with_qf boolean whether the layout included a quickfix window 40local function cleanup_layout ( with_qf ) 41if layout . group then 42vim . api . nvim_del_augroup_by_id ( layout . group ) 43layout . group =nil 44end 45layout . left_win =nil 46layout . right_win =nil 47 48if with_qf then 49vim . fn . setqflist ( {} ) 50vim . cmd . cclose () 51end 52end 53 54--- Set up a consistent layout with two diff windows 55--- @param with_qf boolean whether to open the quickfix window 56local function setup_layout ( with_qf ) 57local left_valid =layout . left_win and vim . api . nvim_win_is_valid ( layout . left_win ) 58local right_valid =layout . right_win and vim . api . nvim_win_is_valid ( layout . right_win ) 59 60if left_valid and right_valid then 61return false 62end 63 64vim . cmd . only ( { mods ={ silent =true } } ) 65layout . left_win =vim . api . nvim_get_current_win () 66vim . cmd ( 'rightbelow vsplit' ) 67layout . right_win =vim . api . nvim_get_current_win () 68 69if with_qf then 70vim . cmd ( 'botright copen' ) 71end 72vim . api . nvim_set_current_win ( layout . right_win ) 73 74-- When one of the windows is closed, clean up the layout 75vim . api . nvim_create_autocmd ( 'WinClosed' , { 76group =layout . group , 77pattern =tostring ( layout . left_win ), 78callback =function () 79cleanup_layout ( with_qf ) 80end , 81} ) 82vim . api . nvim_create_autocmd ( 'WinClosed' , { 83group =layout . group , 84pattern =tostring ( layout . right_win ), 85callback =function () 86cleanup_layout ( with_qf ) 87end , 88} ) 89end 90 91--- Diff two files 92--- @param left_file string 93--- @param right_file string 94--- @param with_qf boolean? whether to open the quickfix window 95local function diff_files ( left_file , right_file , with_qf ) 96setup_layout ( with_qf or false ) 97 98util . edit_in ( assert ( layout . left_win ), left_file ) 99util . edit_in ( assert ( layout . right_win ), right_file ) 100 101vim . cmd ( 'diffoff!' ) 102vim . api . nvim_win_call ( assert ( layout . left_win ), vim . cmd . diffthis ) 103vim . api . nvim_win_call ( assert ( layout . right_win ), vim . cmd . diffthis ) 104end 105 106--- Diff two directories using external `diff` command 107--- @param left_dir string 108--- @param right_dir string 109--- @param opt difftool.opt 110--- @return table[] list of quickfix entries 111local function diff_dirs_diffr ( left_dir , right_dir , opt ) 112local args ={ 'diff' , '-qrN' } 113for _ , pattern in ipairs ( opt . ignore ) do 114table . insert ( args , '-x' ) 115table . insert ( args , pattern ) 116end 117table . insert ( args , left_dir ) 118table . insert ( args , right_dir ) 119 120-- Force English locale so that we can rely on the output format 121local result =vim . system ( args , { text =true , env ={ LC_ALL ='C' } } ): wait () 122local lines =vim . split ( result . stdout or '' , '\n' , { trimempty =true } ) 123local qf_entries ={} 124 125for _ , line in ipairs ( lines ) do 126local modified_left , modified_right =line : match ( "^Files '?(.-)'? and '?(.-)'? differ$" ) 127if modified_left and modified_right then 128local left_exists =vim . fn . filereadable ( modified_left ) == 1 129local right_exists =vim . fn . filereadable ( modified_right ) == 1 130local status ='?' 131if left_exists and right_exists then 132status ='M' 133elseif left_exists then 134status ='D' 135elseif right_exists then 136status ='A' 137end 138local left =vim . fn . resolve ( vim . fs . abspath ( modified_left )) 139local right =vim . fn . resolve ( vim . fs . abspath ( modified_right )) 140table . insert ( qf_entries , { 141filename =right , 142text =status , 143user_data ={ 144diff =true , 145rel =vim . fs . relpath ( left_dir , modified_left ), 146left =left , 147right =right , 148} , 149} ) 150end 151end 152 153return qf_entries 154end 155 156--- Diff two directories using built-in Lua implementation 157--- @param left_dir string 158--- @param right_dir string 159--- @param opt difftool.opt 160--- @return table[] list of quickfix entries 161local function diff_dirs_builtin ( left_dir , right_dir , opt ) 162--- @param rel_path string? 163--- @param ignore string[] 164--- @return boolean 165local function is_ignored ( rel_path , ignore ) 166if not rel_path then 167return false 168end 169for _ , pat in ipairs ( ignore ) do 170if vim . fn . match ( rel_path , pat ) >= 0 then 171return true 172end 173end 174return false 175end 176 177--- @param file1 string 178--- @param file2 string 179--- @param chunk_size integer 180--- @param chunk_cache table<string, any> 181--- @return number similarity ratio (0 to 1) 182local function calculate_similarity ( file1 , file2 , chunk_size , chunk_cache ) 183-- Get or read chunk for file1 184local chunk1 =chunk_cache [ file1 ] 185if not chunk1 then 186chunk1 =util . read_chunk ( file1 , chunk_size ) 187chunk_cache [ file1 ] =chunk1 188end 189 190-- Get or read chunk for file2 191local chunk2 =chunk_cache [ file2 ] 192if not chunk2 then 193chunk2 =util . read_chunk ( file2 , chunk_size ) 194chunk_cache [ file2 ] =chunk2 195end 196 197if not chunk1 or not chunk2 then 198return 0 199end 200if chunk1 == chunk2 then 201return 1 202end 203local matches =0 204local len =math . min ( # chunk1 , # chunk2 ) 205for i =1 , len do 206if chunk1 : sub ( i , i ) == chunk2 : sub ( i , i ) then 207matches =matches + 1 208end 209end 210return matches / len 211end 212 213-- Create a map of all relative paths 214 215--- @type table<string, {left: string?, right: string?}> 216local all_paths ={} 217--- @type table<string, string> 218local left_only ={} 219--- @type table<string, string> 220local right_only ={} 221 222--- @param dir_path string 223--- @param is_left boolean 224local function process_files_in_directory ( dir_path , is_left ) 225local files =vim . fs . find ( function ( name , path ) 226local rel_path =vim . fs . relpath ( dir_path , vim . fs . joinpath ( path , name )) 227return not is_ignored ( rel_path , opt . ignore ) 228end , { limit =math . huge , path =dir_path , follow =false } ) 229 230for _ , full_path in ipairs ( files ) do 231local rel_path =vim . fs . relpath ( dir_path , full_path ) 232if rel_path then 233full_path =vim . fn . resolve ( full_path ) 234 235if vim . fn . isdirectory ( full_path ) == 0 then 236all_paths [ rel_path ] =all_paths [ rel_path ] or { left =nil , right =nil } 237 238if is_left then 239all_paths [ rel_path ]. left =full_path 240if not all_paths [ rel_path ]. right then 241left_only [ rel_path ] =full_path 242end 243else 244all_paths [ rel_path ]. right =full_path 245if not all_paths [ rel_path ]. left then 246right_only [ rel_path ] =full_path 247end 248end 249end 250end 251end 252end 253 254-- Process both directories 255process_files_in_directory ( left_dir , true ) 256process_files_in_directory ( right_dir , false ) 257 258--- @type table<string, string> 259local renamed ={} 260--- @type table<string, string> 261local chunk_cache ={} 262 263-- Detect possible renames 264if opt . rename . detect then 265for left_rel , left_path in pairs ( left_only ) do 266---@type {similarity: number, path: string?, rel: string?} 267local best_match ={ similarity =opt . rename . similarity , path =nil } 268 269for right_rel , right_path in pairs ( right_only ) do 270local similarity = 271calculate_similarity ( left_path , right_path , opt . rename . chunk_size , chunk_cache ) 272 273if similarity > best_match . similarity then 274best_match ={ 275similarity =similarity , 276path =right_path , 277rel =right_rel , 278} 279end 280end 281 282if best_match . path and best_match . rel then 283renamed [ left_rel ] =best_match . rel 284all_paths [ left_rel ]. right =best_match . path 285all_paths [ best_match . rel ] =nil 286left_only [ left_rel ] =nil 287right_only [ best_match . rel ] =nil 288end 289end 290end 291 292local qf_entries ={} 293 294-- Convert to quickfix entries 295for rel_path , files in pairs ( all_paths ) do 296local status =nil 297if files . left and files . right then 298--- @type number 299local similarity 300if opt . rename . detect then 301similarity = 302calculate_similarity ( files . left , files . right , opt . rename . chunk_size , chunk_cache ) 303else 304similarity =vim . fn . getfsize ( files . left ) == vim . fn . getfsize ( files . right ) and 1 or 0 305end 306if similarity < 1 then 307status =renamed [ rel_path ] and 'R' or 'M' 308end 309elseif files . left then 310status ='D' 311files . right =right_dir .. rel_path 312elseif files . right then 313status ='A' 314files . left =left_dir .. rel_path 315end 316 317if status then 318table . insert ( qf_entries , { 319filename =files . right , 320text =status , 321user_data ={ 322diff =true , 323rel =rel_path , 324left =files . left , 325right =files . right , 326} , 327} ) 328end 329end 330 331return qf_entries 332end 333 334--- Diff two directories 335--- @param left_dir string 336--- @param right_dir string 337--- @param opt difftool.opt 338local function diff_dirs ( left_dir , right_dir , opt ) 339local method =opt . method 340if method == 'auto' then 341if not opt . rename . detect and vim . fn . executable ( 'diff' ) == 1 then 342method ='diffr' 343else 344method ='builtin' 345end 346end 347 348--- @type table[] 349local qf_entries 350if method == 'diffr' then 351qf_entries =diff_dirs_diffr ( left_dir , right_dir , opt ) 352elseif method == 'builtin' then 353qf_entries =diff_dirs_builtin ( left_dir , right_dir , opt ) 354else 355vim . notify ( 'Unknown diff method: ' .. method , vim . log . levels . ERROR ) 356return 357end 358 359-- Early exit if no differences found 360if # qf_entries == 0 then 361vim . notify ( 'No differences found' , vim . log . levels . INFO ) 362return 363end 364 365-- Sort entries by filename for consistency 366table . sort ( qf_entries , function ( a , b ) 367return a . user_data . rel < b . user_data . rel 368end ) 369 370vim . fn . setqflist ( {} , 'r' , { 371nr ='$' , 372title ='DiffTool' , 373items =qf_entries , 374---@param info {id: integer, start_idx: integer, end_idx: integer} 375quickfixtextfunc =function ( info ) 376local items =assert ( vim . fn . getqflist ( { id =info . id , items =1 } ). items ) 377local out ={} 378for item =info . start_idx , info . end_idx do 379local entry =assert ( items [ item ]) 380table . insert ( out , entry . text .. ' ' .. entry . user_data . rel ) 381end 382return out 383end , 384} ) 385 386setup_layout ( true ) 387vim . cmd . cfirst () 388end 389 390local M ={} 391 392--- @class difftool.opt 393--- @inlinedoc 394--- 395--- Diff method to use 396--- (default: `auto`) 397--- @field method 'auto'|'builtin'|'diffr' 398--- 399--- List of file patterns to ignore (for example: `'.git', '*.log'`) 400--- (default: `{}`) 401--- @field ignore string[] 402--- 403--- Rename detection options (supported only by `builtin` method) 404--- @field rename table Controls rename detection 405--- 406--- - {rename.detect} (`boolean`, default: `false`) Whether to detect renames 407--- - {rename.similarity} (`number`, default: `0.5`) Minimum similarity for rename detection (0 to 1) 408--- - {rename.chunk_size} (`number`, default: `4096`) Maximum chunk size to read from files for similarity calculation 409 410--- Diff two files or directories 411--- @param left string 412--- @param right string 413--- @param opt? difftool.opt 414function M . open ( left , right , opt ) 415if not left or not right then 416vim . notify ( 'Both arguments are required' , vim . log . levels . ERROR ) 417return 418end 419 420local config =vim . tbl_deep_extend ( 'force' , { 421method ='auto' , 422ignore ={} , 423rename ={ 424detect =false , 425similarity =0.5 , 426chunk_size =4096 , 427} , 428} , opt or {} ) 429 430layout . group =vim . api . nvim_create_augroup ( 'nvim.difftool.events' , { clear =true } ) 431local hl_id =vim . api . nvim_create_namespace ( 'nvim.difftool.hl' ) 432 433--- @param bufnr? integer 434local function get_diff_entry ( bufnr ) 435local qf_info =vim . fn . getqflist ( { idx =0 , items =1 , size =1 } ) 436if qf_info . size == 0 then 437return false 438end 439 440local entry =assert ( qf_info . items )[ assert ( qf_info . idx )] 441if 442not entry 443or not entry . user_data 444or not entry . user_data . diff 445or ( bufnr and entry . bufnr ~= bufnr ) 446then 447return nil 448end 449 450return entry 451end 452 453vim . api . nvim_create_autocmd ( 'BufWinEnter' , { 454group =layout . group , 455pattern ='quickfix' , 456callback =function ( ev ) 457if not get_diff_entry () then 458return 459end 460 461vim . api . nvim_buf_clear_namespace ( ev . buf , hl_id , 0 , - 1 ) 462local lines =vim . api . nvim_buf_get_lines ( ev . buf , 0 , - 1 , false ) 463 464-- Map status codes to highlight groups 465for i , line in ipairs ( lines ) do 466local status =line : match ( '^(%a) ' ) 467local hl_group =highlight_groups [ status ] 468if hl_group then 469vim . hl . range ( ev . buf , hl_id , hl_group , { i - 1 , 0 } , { i - 1 , 1 } ) 470end 471end 472end , 473} ) 474 475vim . api . nvim_create_autocmd ( 'BufWinEnter' , { 476group =layout . group , 477pattern ='*' , 478callback =function ( ev ) 479local entry =get_diff_entry ( ev . buf ) 480if not entry then 481return 482end 483 484vim . w . lazyredraw =true 485vim . schedule ( function () 486diff_files ( entry . user_data . left , entry . user_data . right ) 487vim . w . lazyredraw =false 488end ) 489end , 490} ) 491 492left =vim . fs . normalize ( left ) 493right =vim . fs . normalize ( right ) 494 495if vim . fn . isdirectory ( left ) == 1 and vim . fn . isdirectory ( right ) == 1 then 496diff_dirs ( left , right , config ) 497elseif vim . fn . filereadable ( left ) == 1 and vim . fn . filereadable ( right ) == 1 then 498diff_files ( left , right ) 499else 500vim . notify ( 'Both arguments must be files or directories' , vim . log . levels . ERROR ) 501end 502end 503 504return M