How can I merge paragraphs in a code block?

You’d have to, after changing the paragraphs to code blocks, replace the boundaries between the affected ones (the range from the end of one code block to the start of the next one, covering the closing and opening tokens for the code blocks) with a newline (or two?).