@@ -382,6 +382,21 @@ function Chat:follow()
382382 vim .api .nvim_win_set_cursor (self .winnr , { last_line + 1 , last_column })
383383end
384384
385+ --- Prepare the chat window for writing.
386+ function Chat :start ()
387+ self :validate ()
388+
389+ if self :focused () then
390+ utils .return_to_normal_mode ()
391+ end
392+
393+ if self .spinner then
394+ self .spinner :start ()
395+ end
396+
397+ vim .bo [self .bufnr ].modifiable = false
398+ end
399+
385400--- Finish writing to the chat window.
386401function Chat :finish ()
387402 if not self .spinner then
@@ -414,9 +429,7 @@ function Chat:add_message(message, replace)
414429 self :append (message .content )
415430 elseif replace and current_message then
416431 -- Replace the content of the current message
417- self :append (' ' )
418432 self :render ()
419-
420433 current_message .content = message .content
421434 local section = current_message .section
422435
@@ -430,9 +443,8 @@ function Chat:add_message(message, replace)
430443 vim .split (message .content , ' \n ' )
431444 )
432445 vim .bo [self .bufnr ].modifiable = false
446+ self :append (' ' )
433447 end
434-
435- self :append (' ' )
436448 else
437449 -- Append to the current message
438450 current_message .content = current_message .content .. message .content
476488--- @param str string
477489function Chat :append (str )
478490 self :validate ()
479- vim .bo [self .bufnr ].modifiable = true
480-
481- if self :focused () then
482- utils .return_to_normal_mode ()
483- end
484-
485- if self .spinner then
486- self .spinner :start ()
487- end
488491
489492 -- Decide if we should follow cursor after appending text.
490493 local should_follow_cursor = self .config .auto_follow_cursor
@@ -496,13 +499,14 @@ function Chat:append(str)
496499 end
497500
498501 local last_line , last_column , _ = self :last ()
502+
503+ vim .bo [self .bufnr ].modifiable = true
499504 vim .api .nvim_buf_set_text (self .bufnr , last_line , last_column , last_line , last_column , vim .split (str , ' \n ' ))
505+ vim .bo [self .bufnr ].modifiable = false
500506
501507 if should_follow_cursor then
502508 self :follow ()
503509 end
504-
505- vim .bo [self .bufnr ].modifiable = false
506510end
507511
508512--- Clear the chat window.
548552--- Render the chat window.
549553--- @protected
550554function Chat :render ()
555+ self :validate ()
551556 vim .api .nvim_buf_clear_namespace (self .bufnr , self .header_ns , 0 , - 1 )
552557 local lines = vim .api .nvim_buf_get_lines (self .bufnr , 0 , - 1 , false )
553558
0 commit comments