javaintellij-ideaformattingembedded-languagejava-text-blocks

Can IntelliJ treat a Java text block as syntax such as SQL or XML to assist editing/formatting?


Java 15 brings us the new JEP 378: Text Blocks feature. This eases working with multi-line strings.

Can IntelliJ be made to parse the text within that block as some kind of syntax? Is there a way for me to tell IntelliJ that a text block is SQL source code or XML data?

If so, can IntelliJ use its code-editing superpowers to assist with colorizing, editing, and formatting the code nested inside my Java via that text block?


Solution

  • You can use Language Injection feature.

    You can specify the intended language embedded as a text block by including either a Java comment or a Java annotation. See IntelliJ documentation: Language injections.

    Comment

    eg:

    // language=JSON
    """
    {
       "field1": "text,
       "field2": 123.43,
       "field3": true
    }
    """
    

    Should be interpreted by Idea as JSON and highlight errors:

    screenshot from idea to present the feature

    See the IntelliJ documentation, Use language injection comments.

    Annotation

    Alternatively, you can use the org.intellij.lang.annotations.Language annotation if you add JetBrains Annotations as a dependency on your project.

    @Language("JSON")
    String json = 
        """
        {
           "field1": "text,
           "field2": 123.43,
           "field3": true
        }
        """ ;
    

    Find the Maven coordinates in a repository like this.

    <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations -->
    <dependency>
        <groupId>org.jetbrains</groupId>
        <artifactId>annotations</artifactId>
        <version>24.1.0</version>
    </dependency>