Search code examples
stringeclipsejava-17java-21java-text-blocks

Can Eclipse be configured to convert a String to a text block if you hit enter while typing the string?


There are two things I'd like to figure out:

  1. If I am typing a String literal and hit enter, it should be converted to a text block.
  2. The same way you can highlight a block of text and hit CTRL+SHIFT+C to convert it to a multiline comment, there should be a key sequence for converting a highlighted block of concatenated String into a text block.

For example, highlight this:

String sql =
  "SELECT S.STOCK_ID, S.NAME, C.COLOR, S.PROD_DESCRIP, S.PRICE, S.PROD_FAM_ID " +
  "FROM STOCK S " +
  "INNER JOIN FAMILY F " +
  "ON S.STOCK_ID = ? AND F.PART_NUM = 'FINISH' AND F.FAMILY_ID = S.PROD_FAM_ID AND S.IS_ACTIVE = 1 " +
  "LEFT OUTER JOIN COLOR C ON C.COLOR_ID = S.COLOR " +
  "ORDER BY S.PRODNO,S.NAME";

And then CTRL+SHIFT+something to get:

String sql = """
  SELECT S.STOCK_ID, S.NAME, C.COLOR, S.PROD_DESCRIP, S.PRICE, S.PROD_FAM_ID  
  FROM STOCK S 
  INNER JOIN FAMILY F 
  ON S.STOCK_ID = ? AND F.PART_NUM = 'FINISH' AND F.FAMILY_ID = S.PROD_FAM_ID AND S.IS_ACTIVE = 1 
  LEFT OUTER JOIN COLOR C ON C.COLOR_ID = S.COLOR 
  ORDER BY S.PRODNO,S.NAME
  """;

Solution

  • A text block can be created by just using the Ctrl + Shift + ' shortcut; then start typing inside.

    Note: text block support was added as Java 14 feature preview in Eclipse 2020-06

    It seems there's no direct shortcut to convert to a text block (yet). It could be done in 2 steps:

    1. Select the text not including the ending semicolon. Hit Ctrl + Shift + '
      or select Source > Add text block
      Result:
    private static final String sql =
         """
         "SELECT S.STOCK_ID, S.NAME, C.COLOR, S.PROD_DESCRIP, S.PRICE, S.PROD_FAM_ID " +
         "FROM STOCK S " +
         "INNER JOIN FAMILY F " +
         "ON S.STOCK_ID = ? AND F.PART_NUM = 'FINISH' AND F.FAMILY_ID = S.PROD_FAM_ID AND S.IS_ACTIVE = 1 " +
         "LEFT OUTER JOIN COLOR C ON C.COLOR_ID = S.COLOR " +
         "ORDER BY S.PRODNO,S.NAME"
         """;
    
    1. Select the text again not including the triple quotes. Hit Ctrl + F, check Regular Expressions and use
      ^(\s*)"([^"]+)"(\s*[;+]?) as the find expression and
      $1$2 as the replace expression.
      Hit Replace all

      Result

    private static final String sql =
          """
          SELECT S.STOCK_ID, S.NAME, C.COLOR, S.PROD_DESCRIP, S.PRICE, S.PROD_FAM_ID 
          FROM STOCK S 
          INNER JOIN FAMILY F 
          ON S.STOCK_ID = ? AND F.PART_NUM = 'FINISH' AND F.FAMILY_ID = S.PROD_FAM_ID AND S.IS_ACTIVE = 1 
          LEFT OUTER JOIN COLOR C ON C.COLOR_ID = S.COLOR 
          ORDER BY S.PRODNO,S.NAME""";
    

    The Find/Replace dialog may remained opened to perform more refactorings.

    Find/Replace dialog with regular expressions