How can I apply AI-generated changes only to specific code lines I've selected?

How can I apply AI-generated changes only to specific code lines I’ve selected?

Hi @PiDanShouRouZhouXD ,

You can highlight the code and then press Ctrl + K.

https://docs.cursor.com/cmdk/overview#inline-edits

Is that the functionality you are looking for?

I have already generated some code in the chat (using Ctrl+L), but since I initially selected a large portion of code, applying changes globally would likely cause errors (and it’s also slow). Therefore, I need to apply the AI-generated code blocks only to specific parts of my code.

Hi @PiDanShouRouZhouXD ,

Usually, when you click Apply in Ctrl + L, you will see the highlighted rows moving down through the file in your Editor as it scans for where to add the changes (and it will say ‘Generating’ in the chat pane).

You will then see a Green and Red diff where the suggested changes are in the Editor.

You can approve or reject those changes one at a time, by clicking on the Green or Red button near the change, rather than clicking ‘Accept’ in the Chat pane (which would make all of the suggested changes).

So if you are just wanting to make some of the suggested changes, but not all of them, that is the only way I know of via the Ctrl + L chat interface.

If I am misunderstanding something, or you are seeking different functionality, feel free to write back with more details and perhaps someone else can assist.

The use case I find where this would be useful is when editing a large file and waiting for Apply to get to the spot where the change needs to be made takes a long time and often breaks. (Don’t tell me to have smaller files I know I know)

Have you tried this?
Get your suggested change from the chat.
Select the code block that you want changed and use Ctrl + K
Add your chat with @chat

It will then apply the change from the chat to the selected section only.

I’m tempted to give the unhelpful suggestion that your files are too long, but I know that can’t always be helped! :grin:

1 Like

Thank you for your helpful suggestion!

1 Like