Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a concatenated VB.NET string literal to a multi-line string

Note: This question is not about VB.NET per se, it's about a particular feature of the Visual Studio 2015 Basic editor.

I have some legacy code that looks like this:

Dim someText =
    " a " &
    " AND b " &
    " AND cd " &
    " AND efg " &
    " AND h "

Since Roslyn has introduced multi-line string literals in VB, I want to convert it to this:

Dim someText =
    " a 
      AND b 
      AND cd 
      AND efg 
      AND h "

(I know that the two are not exactly equivalent, since the second one contains additional line breaks and spaces. That's fine. Let's assume that the content is something like SQL or HTML where additional whitespace does not matter.)

Now my approach would be as follows: First I block-select the starting quotes (except for the first one) and replace them with a space:

Dim someText =
   " a " &
     AND b " &
     AND cd " &
     AND efg " &
     AND h "

Then I click into the a line to fix the trailing quotes, and poof the following happens:

Dim someText =
    " a " &
      And b " &
      AND cd " &
      AND efg " &
      AND h "

The capitalization of the first "And" got messed up.

I understand why this happens. I even filed a bug report to fix a similar issue. Unfortunately, the fix (which apparently made it into VS 2015 Update 2) only helps if the total number of quotes is odd, which is not the case here.

Has anyone found a workaround to reformat large blocks of concatenated strings into multi-line string literals without Visual Studio messing up the string contents? I know that I can turn of pretty-formatting globally (Tools/Options/Text Editor/Basic/Advanced), but is there a better solution?

like image 882
Heinzi Avatar asked Mar 13 '23 14:03

Heinzi


1 Answers

You can use Find and Replace for this. Turn on Regular expressions:

enter image description here

and use this expression:

" &\r\n\s*"

This will match the quote and ampersand at the end of one line, followed by the newline and any whitespace and the quote at the start of the next line:

enter image description here

The replacement is then:

\r\n

To replace the matched text with a new line.

If you want to preserve the whitespace at the start of each line, use a capturing group (the parentheses) to capture it in the find expression:

" &\r\n(\s*)"

and put it back in in the replacement, using $1:

\r\n$1

enter image description here

like image 84
James Thorpe Avatar answered May 03 '23 06:05

James Thorpe