@@ -478,34 +478,60 @@ M.update_current_buffer = function(prev_path)
478478 return false
479479 end
480480
481+ local buffers = vim .api .nvim_list_bufs ()
482+ local listed_buffers = vim .tbl_filter (function (bufn )
483+ return vim .api .nvim_buf_is_valid (bufn ) and vim .api .nvim_buf_get_option (bufn , ' buflisted' )
484+ end , buffers )
485+
486+ local changed = false
487+ local current_buf_name = vim .api .nvim_buf_get_name (vim .api .nvim_get_current_buf ())
488+ local new_current_buf = 0
489+
481490 local cwd = vim .loop .cwd ()
482- local current_buf_name = vim .api .nvim_buf_get_name (0 )
483- if not current_buf_name or current_buf_name == " " then
484- return false
485- end
491+ for _ , existing_buffer in ipairs (listed_buffers ) do
492+ local buf_name = vim .api .nvim_buf_get_name (existing_buffer )
493+ if not buf_name or buf_name == " " then
494+ goto continue
495+ end
486496
487- local name = Path :new (current_buf_name ):absolute ()
488- local start , fin = string.find (name , cwd .. Path .path .sep , 1 , true )
489- if start ~= nil then
490- return true
491- end
497+ local name = Path :new (buf_name ):absolute ()
498+ local start , fin = string.find (name , cwd .. Path .path .sep , 1 , true )
499+ if start ~= nil then
500+ changed = true
501+ goto continue
502+ end
492503
493- start , fin = string.find (name , prev_path , 1 , true )
494- if start == nil then
495- return false
496- end
504+ -- de-list buffer if it's related to the old worktree
505+ vim .api .nvim_buf_set_option (existing_buffer , ' buflisted' , false )
497506
498- local local_name = name :sub (fin + 2 )
507+ start , fin = string.find (name , prev_path , 1 , true )
508+ if start == nil then
509+ goto continue
510+ end
499511
500- local final_path = Path : new ({ cwd , local_name }): absolute ( )
512+ local local_name = name : sub ( fin + 2 )
501513
502- if not Path :new (final_path ):exists () then
503- return false
514+ local final_path = Path :new ({ cwd , local_name }):absolute ()
515+
516+ if not Path :new (final_path ):exists () then
517+ goto continue
518+ end
519+
520+ local new_buffer = vim .fn .bufnr (final_path , true )
521+ vim .api .nvim_buf_set_option (new_buffer , ' buflisted' , true )
522+ vim .api .nvim_set_current_buf (new_buffer )
523+
524+ if current_buf_name == buf_name then
525+ new_current_buf = new_buffer
526+ end
527+
528+ changed = true
529+
530+ :: continue::
504531 end
532+ vim .api .nvim_set_current_buf (new_current_buf )
505533
506- local bufnr = vim .fn .bufnr (final_path , true )
507- vim .api .nvim_set_current_buf (bufnr )
508- return true
534+ return changed
509535end
510536
511537M .on_tree_change = function (cb )
0 commit comments