1

In stringtemplate-4, how to generate a multi-line comment? For example, the template is like this (the comment's start and end are in some other template):

test(DESCRIPTION) ::= <<
*
* <DESCRIPTION>
*
>>

And DESCRIPTION is a long string, and may also contain line-feeds in it, like:

"This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line."

So we want the output string like:

*
* This is a small description of the program,
* with a line-width of 50 chars max, so the
* line is split.
* Final line.
*
R71
  • 4,283
  • 7
  • 32
  • 60

1 Answers1

1

It looks like you're wanting to do a couple of things here- put the description on a line which starts with an asterisk, but if there's a linefeed or the length is greater than 50, put that on a separate line.

First off, I'd split the description up in the view model prior to passing it to the template, based on line feeds and the length.

I'd then make a small change to the template to separate each item in the array with a newline and an asterisk.

Here's the group file test.stg:

group test;

description(lines) ::= <<
*
* <lines; separator="\n* ">
* 
>>

I'm not sure which language you're using in the view model, but here's some Java:

public static void main(String[] args) {
    STGroup templates = new STGroupFile("test.stg");
    String description = "This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line.";
    // we add two characters at the start of each line "* " so lines can now
    // be only 48 chars in length
    description = addLinebreaks(description, 48);
    String lines[] = description.split("\\r?\\n");
    ST descTemplate = templates.getInstanceOf("description");
    for (String line : lines)
    { 
        descTemplate.add("lines", line);
    }
    System.out.println(descTemplate.render());
}


// used to add line breaks if the length is greater than 50
// From this SO question: http://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java
public static String addLinebreaks(String input, int maxLineLength) {
    StringTokenizer tok = new StringTokenizer(input, " ");
    StringBuilder output = new StringBuilder(input.length());
    int lineLen = 0;
    while (tok.hasMoreTokens()) {
        String word = tok.nextToken()+" ";

        if (lineLen + word.length() > maxLineLength) {
            output.append("\n");
            lineLen = 0;
        }

        output.append(word);
        lineLen += word.length();
    }
    return output.toString();
}

The output I got was:

*
* This is a small description of the program, 
* with a line-width of 50 chars max, so the line 
* is split.
* Final line. 
*

which looks slightly different to your example, but does meet the 50 char limit. I guess you can play around with it until it matches your requirements.

Andy Stabler
  • 1,309
  • 1
  • 15
  • 19