Community
Participate
Working Groups
Created attachment 270086 [details] s Sometimes I have to store an escaped JSON-String directly in the java code (especially for testing reasons). Therefore I paste a formatted String with newlines and indentation my code like this: String foo= "{\n" + " \"type\" : \"individual\",\n" + " \"firstName\" : \"" + firstName + "\",\n" + " \"lastName\" : \"" + lastName + "\",\n" + " \"createAccount\" : true,\n" + " \"email\" : \"" + emailAddress + "\",\n" + " \"password\" : \"" + password+ "\"\n" + "}"; When I run the code formatter, the result is nearly unreadable: String foo = "{\n" + " \"type\" : \"individual\",\n" + " \"firstName\" : \"" + firstName + "\",\n" + " \"lastName\" : \"" + lastName + "\",\n" + " \"createAccount\" : true,\n" + " \"email\" : \"" + emailAddress + "\",\n" + " \"password\" : \"" + password + "\"\n" + "}"; It would be nice, if the formatter would have an understanding of the meaning of the string. I know, this would be pretty challenging - an alternative would be to not be so strict with the given maximum line length and respect the programmer's choice of manual formatting. The @formatter:on/off comments are - in my opinion - a poor alternative, because then there is really no help at all from the formatter.
Moving to Core. Frankly, I don't see "an understanding of the meaning of the string" as a responsibility of a Java formatter. The content of a string could conform to any language on this planet, I don't see reason to treat JSON specifically. The best I could (in wild dreams) imagine JDT to offer is an extension point into which 3rd party formatters for designated areas are plugged, marked, e.g., by @formatter:json ... @formatter:java. For now @formatter:on is the means to tell the formatter that you are leaving standard Java territory, which is exactly what you want.
Mateusz, any comments?
Another feature useful for dealing with problems like this is "Never join already wrapped lines". Personally I like it the most, it's great with Ctrl+Alt+J hotkey when I modify a multi-line instruction and want to quickly join it into a single line before reformatting. Another idea is to use line comments at the end of each line, it'll prevent lines from joining - but that's a lot of manual work. The idea of parsing the contents of strings seems like way too much work for a little benefit. In IntelliJ it's integrated with syntax highlighting, so it makes a bit more sense. But even with good formatting the readability is pretty poor with all the escaping. A much simpler approach that would probably solve the problem entirely is an option to always wrap on concatenation of string literals when the left side ends with a newline character. That's in bug 418327 so I'll close this one as duplicate. I also found another idea for the same problem - to automatically add @formatter:off tags when pasting a multi-line string literal - bug 425473. *** This bug has been marked as a duplicate of bug 418327 ***