I have written a command to "Reflow comments" in my Stata do files. The command is as follows:

#!/usr/bin/env bash

sed -E -e 's_^\s*//(.*)_\1_' |   # strip leading // and whitespace from each line
fmt |                            # reflow comment text
sed -E -e 's_^(.*)_//\1_'        # prefix each line with //

Input is set to "Selected Text" or "Scope", and output is set to "Replace selected text".

If I invoke the command with the cursor in the middle of the following comment:

// this is a profoundly silly comment that I'm writing just to test out how to reflow comments
// something strange happens when I select the text rather than simply execute it within the comment scope
// i wonder what's going on
// maybe i'll write to the mailing list

I get the desired output:

// this is a profoundly silly comment that I'm writing just to test out how to
// reflow comments something strange happens when I select the text rather
// than simply execute it within the comment scope i wonder what's going on
// maybe i'll write to the mailing list

However, if I instead select the entire block of text, I get the following mangled result:

// this is a profoundly silly comment that I'm writing just to test out how to
reflow comments // something strange happens when I select the text rather than
simply execute it within the comment scope // i wonder what's going on // maybe
i'll write to the mailing list

Can anyone explain what causes the differing behavior?

Thanks!

Michael Manti
statboy3000@gmail.com