Email trimming improvement (no trimming in code blocks)

Just so we’re on the same page, let me reformulate your problem so that we are talking about the same thing :wink:

You want the ability to correctly handle Fenced code blocks in email replies, especially if they include the # symbol, which is often used as a (signature) delimiter and thus trimmed.

So if you were to send the following email reply

Here's my patch

```
# This is some comment
####

answer = 42
```

Does it look good?

It should be “clever” enough to recognize that the lines between the ``` is actual code and thus should be “ignored” from the regular processing.

If that’s the case, I would recommend a different solution / approach. It might be better to hoist all the code blocks in the preprocess! function and inject them back afterwards.

Fenced code blocks are somewhat hard to parse correctly using a regex but for a good enough solution, this should work

def hoist_code_blocks(text)
  blocks = {}
  pattern = /^```\w*$\n.*?^```$/m
  
  text.gsub(pattern) do |block|
    token = SecureRandom.hex
    blocks[token] = block
    token
  end

  [text, blocks]
end

This method will replace all the code blocks with a random value and keep track of the mapping between the random value and the content of the block in the blocks hash.

You can call it like this

text = "some text\n```ruby\ndef foo\nend\n```\nmore text"
new_text, blocks = hoist_code_blocks(text)

And then you can “restore” the code blocks with the following code

blocks.each { |token, block| new_text.gsub!(token, block) }