You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@freemarker.apache.org by dd...@apache.org on 2026/08/01 20:51:35 UTC

(freemarker) branch feature/string-formatting-builtins created (now 4ab4d64f)

This is an automated email from the ASF dual-hosted git repository.

ddekany pushed a change to branch feature/string-formatting-builtins
in repository https://gitbox.apache.org/repos/asf/freemarker.git


      at 4ab4d64f [PR-130] Adjustments: - ?dedent() => ?dedent, and ?dedent() is error - ?wrap(width) is now valid (prefix defaults to "") - Reworked Manual sections, especially for ?wrap - Moved string transformation methods from Builtins to _CoreStringUtils - Moved most string transformation testing _CoreStringUtilsTest. Add some more test cases.  - IndentAndWrapBuiltInTest now focues on the FTL interface issues, like number and type of arguments. - Adjusted IndentAndWrapBuiltInTest to  [...]

This branch includes the following new commits:

     new 4ab4d64f [PR-130] Adjustments: - ?dedent() => ?dedent, and ?dedent() is error - ?wrap(width) is now valid (prefix defaults to "") - Reworked Manual sections, especially for ?wrap - Moved string transformation methods from Builtins to _CoreStringUtils - Moved most string transformation testing _CoreStringUtilsTest. Add some more test cases.  - IndentAndWrapBuiltInTest now focues on the FTL interface issues, like number and type of arguments. - Adjusted IndentAndWrapBuiltInTest to  [...]

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(freemarker) 01/01: [PR-130] Adjustments: - ?dedent() => ?dedent, and ?dedent() is error - ?wrap(width) is now valid (prefix defaults to "") - Reworked Manual sections, especially for ?wrap - Moved string transformation methods from Builtins to _CoreStringUtils - Moved most string transformation testing _CoreStringUtilsTest. Add some more test cases. - IndentAndWrapBuiltInTest now focues on the FTL interface issues, like number and type of arguments. - Adjusted IndentAndWrapBuiltInTest to code use FTL JUnit [...]

Posted by dd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ddekany pushed a commit to branch feature/string-formatting-builtins
in repository https://gitbox.apache.org/repos/asf/freemarker.git

commit 4ab4d64f8d02a9c9efa22ae33dc15f185182a0b8
Author: ddekany <dd...@apache.org>
AuthorDate: Mon Jul 27 01:21:48 2026 +0200

    [PR-130] Adjustments:
    - ?dedent() => ?dedent, and ?dedent() is error
    - ?wrap(width) is now valid (prefix defaults to "")
    - Reworked Manual sections, especially for ?wrap
    - Moved string transformation methods from Builtins to _CoreStringUtils
    - Moved most string transformation testing _CoreStringUtilsTest. Add some more test cases.
     - IndentAndWrapBuiltInTest now focues on the FTL interface issues, like number and type of arguments.
    - Adjusted IndentAndWrapBuiltInTest to code use FTL JUnit test conventions in this project
---
 .../freemarker/core/BuiltInsForStringsBasic.java   | 459 ++++++---------------
 .../java/freemarker/core/_CoreStringUtils.java     | 252 +++++++++++
 .../freemarker/core/IndentAndWrapBuiltInTest.java  | 267 +++---------
 .../java/freemarker/core/_CoreStringUtilsTest.java | 391 ++++++++++++++++++
 freemarker-manual/src/main/docgen/en_US/book.xml   | 224 ++++++----
 .../main/java/freemarker/test/TemplateTest.java    |   5 +
 6 files changed, 978 insertions(+), 620 deletions(-)

diff --git a/freemarker-core/src/main/java/freemarker/core/BuiltInsForStringsBasic.java b/freemarker-core/src/main/java/freemarker/core/BuiltInsForStringsBasic.java
index f064e07f..d1c8fce2 100644
--- a/freemarker-core/src/main/java/freemarker/core/BuiltInsForStringsBasic.java
+++ b/freemarker-core/src/main/java/freemarker/core/BuiltInsForStringsBasic.java
@@ -46,7 +46,7 @@ class BuiltInsForStringsBasic {
         TemplateModel calculateResult(String s, Environment env) {
             int i = 0;
             int ln = s.length();
-            while (i < ln  &&  Character.isWhitespace(s.charAt(i))) {
+            while (i < ln && Character.isWhitespace(s.charAt(i))) {
                 i++;
             }
             if (i < ln) {
@@ -73,15 +73,15 @@ class BuiltInsForStringsBasic {
     }
 
     static class containsBI extends BuiltIn {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
-            
+
             private final String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -89,7 +89,7 @@ class BuiltInsForStringsBasic {
                         ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
             }
         }
-    
+
         @Override
         TemplateModel _eval(Environment env) throws TemplateException {
             return new BIMethod(target.evalAndCoerceToStringOrUnsupportedMarkup(env,
@@ -98,14 +98,14 @@ class BuiltInsForStringsBasic {
     }
 
     static class ends_withBI extends BuiltInForString {
-    
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -113,7 +113,7 @@ class BuiltInsForStringsBasic {
                         TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -121,14 +121,14 @@ class BuiltInsForStringsBasic {
     }
 
     static class ensure_ends_withBI extends BuiltInForString {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -136,7 +136,7 @@ class BuiltInsForStringsBasic {
                 return new SimpleScalar(s.endsWith(suffix) ? s : s + suffix);
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -144,28 +144,28 @@ class BuiltInsForStringsBasic {
     }
 
     static class ensure_starts_withBI extends BuiltInForString {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1, 3);
-                
+
                 final String checkedPrefix = getStringMethodArg(args, 0);
-                
+
                 final boolean startsWithPrefix;
-                final String addedPrefix; 
+                final String addedPrefix;
                 if (args.size() > 1) {
                     addedPrefix = getStringMethodArg(args, 1);
                     long flags = args.size() > 2
                             ? RegexpHelper.parseFlagString(getStringMethodArg(args, 2))
                             : RegexpHelper.RE_FLAG_REGEXP;
-                  
+
                     if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
                         RegexpHelper.checkOnlyHasNonRegexpFlags(key, flags, true);
                         if ((flags & RegexpHelper.RE_FLAG_CASE_INSENSITIVE) == 0) {
@@ -177,7 +177,7 @@ class BuiltInsForStringsBasic {
                         Pattern pattern = RegexpHelper.getPattern(checkedPrefix, (int) flags);
                         final Matcher matcher = pattern.matcher(s);
                         startsWithPrefix = matcher.lookingAt();
-                    } 
+                    }
                 } else {
                     startsWithPrefix = s.startsWith(checkedPrefix);
                     addedPrefix = checkedPrefix;
@@ -185,7 +185,7 @@ class BuiltInsForStringsBasic {
                 return new SimpleScalar(startsWithPrefix ? s : addedPrefix + s);
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -193,15 +193,15 @@ class BuiltInsForStringsBasic {
     }
 
     static class index_ofBI extends BuiltIn {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
-            
+
             private final String s;
-            
+
             private BIMethod(String s) {
                 this.s = s;
             }
-            
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 int argCnt = args.size();
@@ -215,13 +215,13 @@ class BuiltInsForStringsBasic {
                 }
             }
         }
-        
+
         private final boolean findLast;
-    
+
         index_ofBI(boolean findLast) {
             this.findLast = findLast;
         }
-        
+
         @Override
         TemplateModel _eval(Environment env) throws TemplateException {
             return new BIMethod(target.evalAndCoerceToStringOrUnsupportedMarkup(env,
@@ -243,7 +243,7 @@ class BuiltInsForStringsBasic {
                 checkMethodArgCount(argCnt, 1, 2);
                 String separatorString = getStringMethodArg(args, 0);
                 long flags = argCnt > 1 ? RegexpHelper.parseFlagString(getStringMethodArg(args, 1)) : 0;
-                
+
                 int startIndex;
                 if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
                     RegexpHelper.checkOnlyHasNonRegexpFlags(key, flags, true);
@@ -263,18 +263,18 @@ class BuiltInsForStringsBasic {
                     } else {
                         startIndex = -1;
                     }
-                } 
+                }
                 return startIndex == -1 ? TemplateScalarModel.EMPTY_STRING : new SimpleScalar(s.substring(startIndex));
             }
         }
-        
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateModelException {
             return new KeepAfterMethod(s);
         }
-        
+
     }
-    
+
     static class keep_after_lastBI extends BuiltInForString {
         class KeepAfterMethod implements TemplateMethodModelEx {
             private String s;
@@ -289,7 +289,7 @@ class BuiltInsForStringsBasic {
                 checkMethodArgCount(argCnt, 1, 2);
                 String separatorString = getStringMethodArg(args, 0);
                 long flags = argCnt > 1 ? RegexpHelper.parseFlagString(getStringMethodArg(args, 1)) : 0;
-                
+
                 int startIndex;
                 if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
                     RegexpHelper.checkOnlyHasNonRegexpFlags(key, flags, true);
@@ -316,18 +316,18 @@ class BuiltInsForStringsBasic {
                             startIndex = -1;
                         }
                     }
-                } 
+                }
                 return startIndex == -1 ? TemplateScalarModel.EMPTY_STRING : new SimpleScalar(s.substring(startIndex));
             }
         }
-        
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateModelException {
             return new KeepAfterMethod(s);
         }
-        
+
     }
-    
+
     static class keep_beforeBI extends BuiltInForString {
         class KeepUntilMethod implements TemplateMethodModelEx {
             private String s;
@@ -342,7 +342,7 @@ class BuiltInsForStringsBasic {
                 checkMethodArgCount(argCnt, 1, 2);
                 String separatorString = getStringMethodArg(args, 0);
                 long flags = argCnt > 1 ? RegexpHelper.parseFlagString(getStringMethodArg(args, 1)) : 0;
-                
+
                 int stopIndex;
                 if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
                     RegexpHelper.checkOnlyHasNonRegexpFlags(key, flags, true);
@@ -359,18 +359,18 @@ class BuiltInsForStringsBasic {
                     } else {
                         stopIndex = -1;
                     }
-                } 
+                }
                 return stopIndex == -1 ? new SimpleScalar(s) : new SimpleScalar(s.substring(0, stopIndex));
             }
         }
-        
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateModelException {
             return new KeepUntilMethod(s);
         }
-        
+
     }
-    
+
     // TODO
     static class keep_before_lastBI extends BuiltInForString {
         class KeepUntilMethod implements TemplateMethodModelEx {
@@ -386,7 +386,7 @@ class BuiltInsForStringsBasic {
                 checkMethodArgCount(argCnt, 1, 2);
                 String separatorString = getStringMethodArg(args, 0);
                 long flags = argCnt > 1 ? RegexpHelper.parseFlagString(getStringMethodArg(args, 1)) : 0;
-                
+
                 int stopIndex;
                 if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
                     RegexpHelper.checkOnlyHasNonRegexpFlags(key, flags, true);
@@ -410,26 +410,26 @@ class BuiltInsForStringsBasic {
                             stopIndex = -1;
                         }
                     }
-                } 
+                }
                 return stopIndex == -1 ? new SimpleScalar(s) : new SimpleScalar(s.substring(0, stopIndex));
             }
         }
-        
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateModelException {
             return new KeepUntilMethod(s);
         }
-        
+
     }
-    
+
     static class lengthBI extends BuiltInForString {
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new SimpleNumber(s.length());
         }
-        
-    }    
+
+    }
 
     static class lower_caseBI extends BuiltInForString {
         @Override
@@ -446,22 +446,22 @@ class BuiltInsForStringsBasic {
     }
 
     static class padBI extends BuiltInForString {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
-            
+
             private final String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
-                int argCnt  = args.size();
+                int argCnt = args.size();
                 checkMethodArgCount(argCnt, 1, 2);
-    
+
                 int width = getNumberMethodArg(args, 0).intValue();
-    
+
                 if (argCnt > 1) {
                     String filling = getStringMethodArg(args, 1);
                     try {
@@ -483,13 +483,13 @@ class BuiltInsForStringsBasic {
                 }
             }
         }
-    
+
         private final boolean leftPadder;
-    
+
         padBI(boolean leftPadder) {
             this.leftPadder = leftPadder;
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -512,23 +512,7 @@ class BuiltInsForStringsBasic {
                 checkMethodArgCount(argCnt, 1, 1);
 
                 String prefix = getStringMethodArg(args, 0);
-
-                if (s.isEmpty()) {
-                    return new SimpleScalar(s);
-                }
-
-                StringBuilder sb = new StringBuilder(s.length() + prefix.length() * 10);
-                int len = s.length();
-                boolean atLineStart = true;
-                for (int i = 0; i < len; i++) {
-                    char c = s.charAt(i);
-                    if (atLineStart && c != '\n' && c != '\r') {
-                        sb.append(prefix);
-                    }
-                    sb.append(c);
-                    atLineStart = (c == '\n' || (c == '\r' && (i + 1 >= len || s.charAt(i + 1) != '\n')));
-                }
-                return new SimpleScalar(sb.toString());
+                return new SimpleScalar(_CoreStringUtils.indent(s, prefix));
             }
         }
 
@@ -540,165 +524,31 @@ class BuiltInsForStringsBasic {
 
     static class dedentBI extends BuiltInForString {
 
-        private class BIMethod implements TemplateMethodModelEx {
+        private class BIMethod implements TemplateScalarModel, TemplateMethodModelEx {
 
-            private final String s;
+            private final String targetAsString;
+            private String cachedResult;
 
-            private BIMethod(String s) {
-                this.s = s;
+            private BIMethod(String targetAsString) {
+                this.targetAsString = targetAsString;
             }
 
             @Override
             public Object exec(List args) throws TemplateModelException {
                 int argCnt = args.size();
-                checkMethodArgCount(argCnt, 0, 1);
-
-                if (argCnt == 0) {
-                    // No-argument form: strip the longest common leading whitespace
-                    // (spaces and tabs) across all non-empty lines, like Python's
-                    // textwrap.dedent. Empty lines are ignored when computing the
-                    // common prefix.
-                    return new SimpleScalar(dedentCommonLeadingWhitespace(s));
-                }
+                checkMethodArgCount(argCnt, 1);
 
-                // Explicit-prefix form: remove the given prefix from each line that
-                // starts with it; leave other lines unchanged.
                 String prefix = getStringMethodArg(args, 0);
-
-                if (s.isEmpty() || prefix.isEmpty()) {
-                    return new SimpleScalar(s);
-                }
-
-                int prefixLen = prefix.length();
-                StringBuilder sb = new StringBuilder(s.length());
-                int len = s.length();
-                boolean atLineStart = true;
-                int matchPos = 0;
-                boolean stripping = true;
-
-                for (int i = 0; i < len; i++) {
-                    char c = s.charAt(i);
-                    if (atLineStart && stripping) {
-                        if (matchPos < prefixLen && c == prefix.charAt(matchPos)) {
-                            matchPos++;
-                            if (matchPos == prefixLen) {
-                                stripping = false;
-                            }
-                            continue; // consume prefix char
-                        } else {
-                            // Prefix didn't match — emit what we skipped
-                            sb.append(prefix, 0, matchPos);
-                            stripping = false;
-                        }
-                    }
-                    sb.append(c);
-                    if (c == '\n') {
-                        atLineStart = true;
-                        matchPos = 0;
-                        stripping = true;
-                    } else if (c == '\r') {
-                        atLineStart = true;
-                        matchPos = 0;
-                        stripping = true;
-                    } else {
-                        atLineStart = false;
-                    }
-                }
-                // Handle trailing partial match (line without newline)
-                if (stripping && matchPos > 0 && matchPos < prefixLen) {
-                    sb.append(prefix, 0, matchPos);
-                }
-                return new SimpleScalar(sb.toString());
+                return new SimpleScalar(_CoreStringUtils.dedent(targetAsString, prefix));
             }
-        }
 
-        /**
-         * Strip the longest leading-whitespace string (spaces and tabs only) that
-         * is a common prefix of every non-empty line. Empty lines are ignored when
-         * computing the prefix but remain empty in the output. Mirrors Python's
-         * textwrap.dedent semantics. Note: a leading tab and a leading space do
-         * not collapse — they're distinct characters with no common prefix.
-         */
-        private static String dedentCommonLeadingWhitespace(String s) {
-            if (s.isEmpty()) return s;
-            int len = s.length();
-
-            // First pass: walk lines, find the leading-whitespace run of each,
-            // and compute the common prefix among non-empty lines.
-            String commonPrefix = null;
-            int lineStart = 0;
-            for (int i = 0; i <= len; i++) {
-                boolean atEnd = (i == len);
-                char c = atEnd ? '\n' : s.charAt(i);
-                if (atEnd || c == '\n' || c == '\r') {
-                    int contentStart = lineStart;
-                    while (contentStart < i) {
-                        char cc = s.charAt(contentStart);
-                        if (cc != ' ' && cc != '\t') break;
-                        contentStart++;
-                    }
-                    boolean nonEmpty = contentStart < i;
-                    if (nonEmpty) {
-                        if (commonPrefix == null) {
-                            commonPrefix = s.substring(lineStart, contentStart);
-                        } else {
-                            int maxLen = Math.min(commonPrefix.length(), contentStart - lineStart);
-                            int matched = 0;
-                            while (matched < maxLen
-                                    && commonPrefix.charAt(matched) == s.charAt(lineStart + matched)) {
-                                matched++;
-                            }
-                            if (matched < commonPrefix.length()) {
-                                commonPrefix = commonPrefix.substring(0, matched);
-                            }
-                            if (commonPrefix.isEmpty()) break; // can't shrink further; finish quickly
-                        }
-                    }
-                    if (!atEnd) {
-                        // Step past \r\n if applicable
-                        if (c == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') i++;
-                        lineStart = i + 1;
-                    }
-                }
-            }
-
-            if (commonPrefix == null || commonPrefix.isEmpty()) {
-                return s;
-            }
-
-            // Second pass: emit each line with the common prefix stripped (from
-            // non-empty lines only).
-            int prefixLen = commonPrefix.length();
-            StringBuilder sb = new StringBuilder(len);
-            lineStart = 0;
-            for (int i = 0; i <= len; i++) {
-                boolean atEnd = (i == len);
-                if (atEnd || s.charAt(i) == '\n' || s.charAt(i) == '\r') {
-                    int contentStart = lineStart;
-                    while (contentStart < i) {
-                        char cc = s.charAt(contentStart);
-                        if (cc != ' ' && cc != '\t') break;
-                        contentStart++;
-                    }
-                    boolean nonEmpty = contentStart < i;
-                    if (nonEmpty) {
-                        // Non-empty line: by construction it has the common prefix.
-                        sb.append(s, lineStart + prefixLen, i);
-                    } else {
-                        // Whitespace-only or empty line — keep as is.
-                        sb.append(s, lineStart, i);
-                    }
-                    if (!atEnd) {
-                        sb.append(s.charAt(i));
-                        if (s.charAt(i) == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') {
-                            i++;
-                            sb.append('\n');
-                        }
-                        lineStart = i + 1;
-                    }
+            @Override
+            public String getAsString() {
+                if (cachedResult == null) {
+                    cachedResult = _CoreStringUtils.dedent(targetAsString);
                 }
+                return cachedResult;
             }
-            return sb.toString();
         }
 
         @Override
@@ -711,16 +561,16 @@ class BuiltInsForStringsBasic {
 
         private class BIMethod implements TemplateMethodModelEx {
 
-            private final String s;
+            private final String targetAsString;
 
-            private BIMethod(String s) {
-                this.s = s;
+            private BIMethod(String targetAsString) {
+                this.targetAsString = targetAsString;
             }
 
             @Override
             public Object exec(List args) throws TemplateModelException {
                 int argCnt = args.size();
-                checkMethodArgCount(argCnt, 2, 3);
+                checkMethodArgCount(argCnt, 1, 3);
 
                 int width = getNumberMethodArg(args, 0).intValue();
                 if (width < 1) {
@@ -728,42 +578,22 @@ class BuiltInsForStringsBasic {
                             "?", key, "(...) argument #1 (width) must be at least 1.");
                 }
 
-                String firstPrefix = getStringMethodArg(args, 1);
-                String restPrefix = argCnt > 2 ? getStringMethodArg(args, 2) : firstPrefix;
-
-                String[] words = s.split("\\s+");
-                if (words.length == 0 || (words.length == 1 && words[0].isEmpty())) {
-                    return new SimpleScalar(firstPrefix + "\n");
-                }
-
-                StringBuilder sb = new StringBuilder();
-                String currentPrefix = firstPrefix;
-                int lineLen = currentPrefix.length();
-                sb.append(currentPrefix);
-                boolean firstWord = true;
-
-                for (String word : words) {
-                    if (word.isEmpty()) continue;
-                    if (firstWord) {
-                        sb.append(word);
-                        lineLen += word.length();
-                        firstWord = false;
+                String result;
+                if (argCnt == 1) {
+                    result = _CoreStringUtils.wrap(targetAsString, width);
+                } else if (argCnt >= 2) {
+                    String firstPrefix = getStringMethodArg(args, 1);
+                    if (argCnt == 2) {
+                        result = _CoreStringUtils.wrap(targetAsString, width, firstPrefix);
                     } else {
-                        if (lineLen + 1 + word.length() > width) {
-                            sb.append('\n');
-                            currentPrefix = restPrefix;
-                            sb.append(currentPrefix);
-                            sb.append(word);
-                            lineLen = currentPrefix.length() + word.length();
-                        } else {
-                            sb.append(' ');
-                            sb.append(word);
-                            lineLen += 1 + word.length();
-                        }
+                        String restPrefix = getStringMethodArg(args, 2);
+                        result = _CoreStringUtils.wrap(targetAsString, width, firstPrefix, restPrefix);
                     }
+                } else {
+                    throw new BugException("Unexpected argCnt");
                 }
-                sb.append('\n');
-                return new SimpleScalar(sb.toString());
+
+                return new SimpleScalar(result);
             }
         }
 
@@ -788,51 +618,25 @@ class BuiltInsForStringsBasic {
                 int argCnt = args.size();
                 checkMethodArgCount(argCnt, 1, 2);
 
-                int column = getNumberMethodArg(args, 0).intValue();
-                if (column < 0) {
+                int width = getNumberMethodArg(args, 0).intValue();
+                if (width < 0) {
                     throw new _TemplateModelException(
                             "?", key, "(...) argument #1 must be non-negative.");
                 }
 
-                char fillChar = ' ';
+                String result;
                 if (argCnt > 1) {
                     String filling = getStringMethodArg(args, 1);
                     if (filling.length() != 1) {
                         throw new _TemplateModelException(
                                 "?", key, "(...) argument #2 must be a single character string.");
                     }
-                    fillChar = filling.charAt(0);
-                }
-
-                if (s.isEmpty()) {
-                    return new SimpleScalar(s);
+                    result = _CoreStringUtils.rightPadLines(s, width, filling.charAt(0));
+                } else {
+                    result = _CoreStringUtils.rightPadLines(s, width);
                 }
 
-                StringBuilder sb = new StringBuilder(s.length() + column);
-                int lineStart = 0;
-                int len = s.length();
-                for (int i = 0; i <= len; i++) {
-                    if (i == len || s.charAt(i) == '\n' || s.charAt(i) == '\r') {
-                        int lineLen = i - lineStart;
-                        sb.append(s, lineStart, i);
-                        // Pad to column (skip empty lines)
-                        if (lineLen > 0) {
-                            for (int p = lineLen; p < column; p++) {
-                                sb.append(fillChar);
-                            }
-                        }
-                        // Append the line ending
-                        if (i < len) {
-                            sb.append(s.charAt(i));
-                            if (s.charAt(i) == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') {
-                                i++;
-                                sb.append('\n');
-                            }
-                        }
-                        lineStart = i + 1;
-                    }
-                }
-                return new SimpleScalar(sb.toString());
+                return new SimpleScalar(result);
             }
         }
 
@@ -843,14 +647,14 @@ class BuiltInsForStringsBasic {
     }
 
     static class remove_beginningBI extends BuiltInForString {
-        
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -858,7 +662,7 @@ class BuiltInsForStringsBasic {
                 return new SimpleScalar(s.startsWith(prefix) ? s.substring(prefix.length()) : s);
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -866,14 +670,14 @@ class BuiltInsForStringsBasic {
     }
 
     static class remove_endingBI extends BuiltInForString {
-    
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -881,13 +685,13 @@ class BuiltInsForStringsBasic {
                 return new SimpleScalar(s.endsWith(suffix) ? s.substring(0, s.length() - suffix.length()) : s);
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
         }
     }
-    
+
     static class split_BI extends BuiltInForString {
         class SplitMethod implements TemplateMethodModel {
             private String s;
@@ -910,27 +714,27 @@ class BuiltInsForStringsBasic {
                 } else {
                     Pattern pattern = RegexpHelper.getPattern(splitString, (int) flags);
                     result = pattern.split(s);
-                } 
+                }
                 return ObjectWrapper.DEFAULT_WRAPPER.wrap(result);
             }
         }
-        
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateModelException {
             return new SplitMethod(s);
         }
-        
+
     }
-    
+
     static class starts_withBI extends BuiltInForString {
-    
+
         private class BIMethod implements TemplateMethodModelEx {
             private String s;
-    
+
             private BIMethod(String s) {
                 this.s = s;
             }
-    
+
             @Override
             public Object exec(List args) throws TemplateModelException {
                 checkMethodArgCount(args, 1);
@@ -938,7 +742,7 @@ class BuiltInsForStringsBasic {
                         TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
             }
         }
-    
+
         @Override
         TemplateModel calculateResult(String s, Environment env) throws TemplateException {
             return new BIMethod(s);
@@ -946,26 +750,26 @@ class BuiltInsForStringsBasic {
     }
 
     static class substringBI extends BuiltInForString {
-        
+
         @Override
         TemplateModel calculateResult(final String s, final Environment env) throws TemplateException {
             return new TemplateMethodModelEx() {
-                
+
                 @Override
                 public Object exec(java.util.List args) throws TemplateModelException {
                     int argCount = args.size();
                     checkMethodArgCount(argCount, 1, 2);
-    
+
                     int beginIdx = getNumberMethodArg(args, 0).intValue();
-    
+
                     final int len = s.length();
-    
+
                     if (beginIdx < 0) {
                         throw newIndexLessThan0Exception(0, beginIdx);
                     } else if (beginIdx > len) {
                         throw newIndexGreaterThanLengthException(0, beginIdx, len);
                     }
-    
+
                     if (argCount > 1) {
                         int endIdx = getNumberMethodArg(args, 1).intValue();
                         if (endIdx < 0) {
@@ -984,7 +788,7 @@ class BuiltInsForStringsBasic {
                         return new SimpleScalar(s.substring(beginIdx));
                     }
                 }
-    
+
                 private TemplateModelException newIndexGreaterThanLengthException(
                         int argIdx, int idx, final int len) throws TemplateModelException {
                     return _MessageUtil.newMethodArgInvalidValueException(
@@ -993,14 +797,14 @@ class BuiltInsForStringsBasic {
                             Integer.valueOf(len),
                             ", but it was ", Integer.valueOf(idx), ".");
                 }
-    
+
                 private TemplateModelException newIndexLessThan0Exception(
                         int argIdx, int idx) throws TemplateModelException {
                     return _MessageUtil.newMethodArgInvalidValueException(
                             "?" + key, argIdx,
                             "The index must be at least 0, but was ", Integer.valueOf(idx), ".");
                 }
-                
+
             };
         }
     }
@@ -1030,7 +834,7 @@ class BuiltInsForStringsBasic {
                     Integer terminatorLength;
                     if (argCount > 1) {
                         terminator = (TemplateModel) args.get(1);
-                        if (!(terminator instanceof  TemplateScalarModel)) {
+                        if (!(terminator instanceof TemplateScalarModel)) {
                             if (allowMarkupTerminator()) {
                                 if (!(terminator instanceof TemplateMarkupOutputModel)) {
                                     throw _MessageUtil.newMethodArgMustBeStringOrMarkupOutputException(
@@ -1165,7 +969,7 @@ class BuiltInsForStringsBasic {
         TemplateModel calculateResult(String s, Environment env) {
             int i = 0;
             int ln = s.length();
-            while (i < ln  &&  Character.isWhitespace(s.charAt(i))) {
+            while (i < ln && Character.isWhitespace(s.charAt(i))) {
                 i++;
             }
             if (i < ln) {
@@ -1197,13 +1001,14 @@ class BuiltInsForStringsBasic {
             SimpleSequence result = new SimpleSequence(_ObjectWrappers.SAFE_OBJECT_WRAPPER);
             StringTokenizer st = new StringTokenizer(s);
             while (st.hasMoreTokens()) {
-               result.add(st.nextToken());
+                result.add(st.nextToken());
             }
             return result;
         }
     }
 
     // Can't be instantiated
-    private BuiltInsForStringsBasic() { }
-    
+    private BuiltInsForStringsBasic() {
+    }
+
 }
diff --git a/freemarker-core/src/main/java/freemarker/core/_CoreStringUtils.java b/freemarker-core/src/main/java/freemarker/core/_CoreStringUtils.java
index ce9fb9d1..989b2a37 100644
--- a/freemarker-core/src/main/java/freemarker/core/_CoreStringUtils.java
+++ b/freemarker-core/src/main/java/freemarker/core/_CoreStringUtils.java
@@ -22,6 +22,7 @@ package freemarker.core;
 import java.util.Collection;
 
 import freemarker.template.Configuration;
+import freemarker.template.utility.NullArgumentException;
 import freemarker.template.utility.StringUtil;
 
 /**
@@ -154,4 +155,255 @@ public final class _CoreStringUtils {
         }
         return sb.toString();
     }
+
+    public static String indent(String s, String prefix) {
+        if (s == null || s.isEmpty() || prefix.isEmpty()) {
+            return s;
+        }
+
+        StringBuilder sb = new StringBuilder(s.length() + prefix.length() * 10);
+        int len = s.length();
+        boolean atLineStart = true;
+        for (int i = 0; i < len; i++) {
+            char c = s.charAt(i);
+            if (atLineStart && c != '\n' && c != '\r') {
+                sb.append(prefix);
+            }
+            sb.append(c);
+            atLineStart = (c == '\n' || (c == '\r' && (i + 1 >= len || s.charAt(i + 1) != '\n')));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Remove the given prefix from each line that starts with it; leave other lines unchanged.
+     */
+    public static String dedent(String s, String prefix) {
+        if (s == null || s.isEmpty() || prefix.isEmpty()) {
+            return s;
+        }
+
+        int prefixLen = prefix.length();
+        StringBuilder sb = new StringBuilder(s.length());
+        int len = s.length();
+        boolean atLineStart = true;
+        int matchPos = 0;
+        boolean stripping = true;
+
+        for (int i = 0; i < len; i++) {
+            char c = s.charAt(i);
+            if (atLineStart && stripping) {
+                if (matchPos < prefixLen && c == prefix.charAt(matchPos)) {
+                    matchPos++;
+                    if (matchPos == prefixLen) {
+                        stripping = false;
+                    }
+                    continue; // consume prefix char
+                } else {
+                    // Prefix didn't match — emit what we skipped
+                    sb.append(prefix, 0, matchPos);
+                    stripping = false;
+                }
+            }
+            sb.append(c);
+            if (c == '\n') {
+                atLineStart = true;
+                matchPos = 0;
+                stripping = true;
+            } else if (c == '\r') {
+                atLineStart = true;
+                matchPos = 0;
+                stripping = true;
+            } else {
+                atLineStart = false;
+            }
+        }
+        // Handle trailing partial match (line without newline)
+        if (stripping && matchPos > 0 && matchPos < prefixLen) {
+            sb.append(prefix, 0, matchPos);
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Strip the longest leading-whitespace string (spaces and tabs only) that
+     * is a common prefix of every non-empty line. Empty lines are ignored when
+     * computing the prefix but remain empty in the output. Mirrors Python's
+     * textwrap.dedent semantics. Note: a leading tab and a leading space do
+     * not collapse — they're distinct characters with no common prefix.
+     */
+    public static String dedent(String s) {
+        if (s.isEmpty()) {
+            return s;
+        }
+        int len = s.length();
+
+        // First pass: walk lines, find the leading-whitespace run of each,
+        // and compute the common prefix among non-empty lines.
+        String commonPrefix = null;
+        int lineStart = 0;
+        for (int i = 0; i <= len; i++) {
+            boolean atEnd = (i == len);
+            char c = atEnd ? '\n' : s.charAt(i);
+            if (atEnd || c == '\n' || c == '\r') {
+                int contentStart = lineStart;
+                while (contentStart < i) {
+                    char cc = s.charAt(contentStart);
+                    if (cc != ' ' && cc != '\t') break;
+                    contentStart++;
+                }
+                boolean nonEmpty = contentStart < i;
+                if (nonEmpty) {
+                    if (commonPrefix == null) {
+                        commonPrefix = s.substring(lineStart, contentStart);
+                    } else {
+                        int maxLen = Math.min(commonPrefix.length(), contentStart - lineStart);
+                        int matched = 0;
+                        while (matched < maxLen
+                                && commonPrefix.charAt(matched) == s.charAt(lineStart + matched)) {
+                            matched++;
+                        }
+                        if (matched < commonPrefix.length()) {
+                            commonPrefix = commonPrefix.substring(0, matched);
+                        }
+                        if (commonPrefix.isEmpty()) break; // can't shrink further; finish quickly
+                    }
+                }
+                if (!atEnd) {
+                    // Step past \r\n if applicable
+                    if (c == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') i++;
+                    lineStart = i + 1;
+                }
+            }
+        }
+
+        if (commonPrefix == null || commonPrefix.isEmpty()) {
+            return s;
+        }
+
+        // Second pass: emit each line with the common prefix stripped (from
+        // non-empty lines only).
+        int prefixLen = commonPrefix.length();
+        StringBuilder sb = new StringBuilder(len);
+        lineStart = 0;
+        for (int i = 0; i <= len; i++) {
+            boolean atEnd = (i == len);
+            if (atEnd || s.charAt(i) == '\n' || s.charAt(i) == '\r') {
+                int contentStart = lineStart;
+                while (contentStart < i) {
+                    char cc = s.charAt(contentStart);
+                    if (cc != ' ' && cc != '\t') break;
+                    contentStart++;
+                }
+                boolean nonEmpty = contentStart < i;
+                if (nonEmpty) {
+                    // Non-empty line: by construction it has the common prefix.
+                    sb.append(s, lineStart + prefixLen, i);
+                } else {
+                    // Whitespace-only or empty line — keep as is.
+                    sb.append(s, lineStart, i);
+                }
+                if (!atEnd) {
+                    sb.append(s.charAt(i));
+                    if (s.charAt(i) == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') {
+                        i++;
+                        sb.append('\n');
+                    }
+                    lineStart = i + 1;
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+    public static String wrap(String s, int width) {
+        return wrap(s, width, "");
+    }
+
+    public static String wrap(String s, int width, String firstPrefix) {
+        return wrap(s, width, firstPrefix, firstPrefix);
+    }
+
+    public static String wrap(String s, int width, String firstPrefix, String restPrefix) {
+        NullArgumentException.check(firstPrefix, "firstPrefix");
+        NullArgumentException.check(restPrefix, "restPrefix");
+        if (width <= 0) {
+            throw new IllegalArgumentException("width must be at least 1");
+        }
+
+        String[] words = s.split("\\s+");
+        if (words.length == 0 || (words.length == 1 && words[0].isEmpty())) {
+            return firstPrefix + "\n";
+        }
+
+        StringBuilder sb = new StringBuilder();
+        String currentPrefix = firstPrefix;
+        int lineLen = currentPrefix.length();
+        sb.append(currentPrefix);
+        boolean firstWord = true;
+
+        for (String word : words) {
+            if (word.isEmpty()) continue;
+            if (firstWord) {
+                sb.append(word);
+                lineLen += word.length();
+                firstWord = false;
+            } else {
+                if (lineLen + 1 + word.length() > width) {
+                    sb.append('\n');
+                    currentPrefix = restPrefix;
+                    sb.append(currentPrefix);
+                    sb.append(word);
+                    lineLen = currentPrefix.length() + word.length();
+                } else {
+                    sb.append(' ');
+                    sb.append(word);
+                    lineLen += 1 + word.length();
+                }
+            }
+        }
+        sb.append('\n');
+        return sb.toString();
+    }
+
+    public static String rightPadLines(String s, int width) {
+        return rightPadLines(s, width, ' ');
+    }
+
+    public static String rightPadLines(String s, int width, char fillChar) {
+        if (s.isEmpty()) {
+            return s;
+        }
+
+        if (width < 0) {
+            throw new IllegalArgumentException("width must be non-negative");
+        }
+
+        StringBuilder sb = new StringBuilder(s.length() + width);
+        int lineStart = 0;
+        int len = s.length();
+        for (int i = 0; i <= len; i++) {
+            if (i == len || s.charAt(i) == '\n' || s.charAt(i) == '\r') {
+                int lineLen = i - lineStart;
+                sb.append(s, lineStart, i);
+                // Pad to column (skip empty lines)
+                if (lineLen > 0) {
+                    for (int p = lineLen; p < width; p++) {
+                        sb.append(fillChar);
+                    }
+                }
+                // Append the line ending
+                if (i < len) {
+                    sb.append(s.charAt(i));
+                    if (s.charAt(i) == '\r' && i + 1 < len && s.charAt(i + 1) == '\n') {
+                        i++;
+                        sb.append('\n');
+                    }
+                }
+                lineStart = i + 1;
+            }
+        }
+        return sb.toString();
+    }
+
 }
diff --git a/freemarker-core/src/test/java/freemarker/core/IndentAndWrapBuiltInTest.java b/freemarker-core/src/test/java/freemarker/core/IndentAndWrapBuiltInTest.java
index 6ef8d4ab..2d91ee05 100644
--- a/freemarker-core/src/test/java/freemarker/core/IndentAndWrapBuiltInTest.java
+++ b/freemarker-core/src/test/java/freemarker/core/IndentAndWrapBuiltInTest.java
@@ -20,279 +20,120 @@ package freemarker.core;
 
 import static org.junit.Assert.*;
 
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.HashMap;
-import java.util.Map;
+import java.io.IOException;
 
 import org.junit.Test;
 
 import freemarker.template.Configuration;
-import freemarker.template.Template;
 import freemarker.template.TemplateException;
+import freemarker.test.TemplateTest;
 
-public class IndentAndWrapBuiltInTest {
-
-    private String eval(String expr) throws Exception {
-        return eval(expr, new HashMap<String, Object>());
-    }
-
-    private String eval(String expr, Map<String, Object> model) throws Exception {
-        String templateContent = "${" + expr + "}";
-        Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
-        Template t = new Template("test.ftl", new StringReader(templateContent), cfg);
-        StringWriter sw = new StringWriter();
-        t.process(model, sw);
-        return sw.toString();
-    }
-
-    // ---- ?indent tests ----
-
-    @Test
-    public void testIndentSingleLine() throws Exception {
-        assertEquals("    hello", eval("'hello'?indent('    ')"));
-    }
-
-    @Test
-    public void testIndentMultiLine() throws Exception {
-        assertEquals("  line1\n  line2\n  line3",
-                eval("'line1\\nline2\\nline3'?indent('  ')"));
-    }
-
-    @Test
-    public void testIndentWithPrefix() throws Exception {
-        assertEquals(" * line1\n * line2",
-                eval("'line1\\nline2'?indent(' * ')"));
-    }
-
-    @Test
-    public void testIndentEmptyString() throws Exception {
-        assertEquals("", eval("''?indent('  ')"));
-    }
-
-    @Test
-    public void testIndentPreservesBlankLines() throws Exception {
-        assertEquals("  a\n\n  b",
-                eval("'a\\n\\nb'?indent('  ')"));
-    }
-
-    @Test
-    public void testIndentTrailingNewline() throws Exception {
-        assertEquals("  a\n  b\n",
-                eval("'a\\nb\\n'?indent('  ')"));
-    }
-
-    // ---- ?wrap tests ----
-
-    @Test
-    public void testWrapBasic() throws Exception {
-        assertEquals(" * @brief Hello world.\n",
-                eval("'Hello world.'?wrap(40, ' * @brief ')"));
-    }
-
-    @Test
-    public void testWrapLongText() throws Exception {
-        String text = "This is a long description that should be wrapped at the specified width";
-        Map<String, Object> model = new HashMap<>();
-        model.put("text", text);
-        String result = eval("text?wrap(40, ' * ', ' * ')", model);
-        // Every line should end with \n and be <= 40 chars (excluding \n)
-        String[] lines = result.split("\n", -1);
-        // Last element is empty after trailing \n
-        for (int i = 0; i < lines.length - 1; i++) {
-            assertTrue("Line " + i + " too long: [" + lines[i] + "] (" + lines[i].length() + " chars)",
-                    lines[i].length() <= 40);
-        }
-        assertTrue(result.startsWith(" * This"));
-    }
-
-    @Test
-    public void testWrapWithDifferentPrefixes() throws Exception {
-        String text = "This is a description that needs wrapping to fit within bounds";
-        Map<String, Object> model = new HashMap<>();
-        model.put("text", text);
-        String result = eval("text?wrap(40, ' * @brief ', ' *          ')", model);
-        assertTrue(result.startsWith(" * @brief "));
-        // Second line should start with rest prefix
-        String[] lines = result.split("\n");
-        if (lines.length > 1) {
-            assertTrue("Second line should start with rest prefix",
-                    lines[1].startsWith(" *          "));
-        }
-    }
-
-    @Test
-    public void testWrapSamePrefix() throws Exception {
-        // Two-arg form: same prefix for all lines
-        assertEquals("// hello world\n",
-                eval("'hello world'?wrap(40, '// ')"));
-    }
-
-    @Test
-    public void testWrapSingleLongWord() throws Exception {
-        // A single word longer than width — can't break, just emit it
-        String result = eval("'superlongword'?wrap(5, '')");
-        assertEquals("superlongword\n", result);
-    }
-
-    @Test(expected = TemplateException.class)
-    public void testWrapZeroWidthThrows() throws Exception {
-        eval("'hello'?wrap(0, '')");
-    }
-
-    // ---- ?dedent tests ----
-
-    @Test
-    public void testDedentBasic() throws Exception {
-        assertEquals("int x;\nint y;\n",
-                eval("'    int x;\\n    int y;\\n'?dedent('    ')"));
-    }
-
-    @Test
-    public void testDedentNoMatch() throws Exception {
-        // Line doesn't start with prefix — left unchanged
-        // "  short" has only 2 spaces, doesn't match 4-space prefix → unchanged
-        // "    full" has 4 spaces, matches prefix → stripped
-        assertEquals("  short\nfull\n",
-                eval("'  short\\n    full\\n'?dedent('    ')"));
-    }
-
-    @Test
-    public void testDedentMixed() throws Exception {
-        // Some lines match, some don't
-        assertEquals("a\n  b\nc\n",
-                eval("'  a\\n    b\\n  c\\n'?dedent('  ')"));
-    }
+/**
+ * Checks indent/dedend/wrap built-ns; for the thorough testing of the text transformations see the
+ * {@link _CoreStringUtilsTest}!
+ */
+public class IndentAndWrapBuiltInTest extends TemplateTest {
 
-    @Test
-    public void testDedentEmptyString() throws Exception {
-        assertEquals("", eval("''?dedent('  ')"));
+    @Override
+    protected Configuration createConfiguration() throws Exception {
+        return new Configuration(Configuration.VERSION_2_3_35);
     }
 
     @Test
-    public void testDedentEmptyPrefix() throws Exception {
-        assertEquals("  hello", eval("'  hello'?dedent('')"));
+    public void testIndentBasic() throws Exception {
+        assertExpOutput("'line1\\nline2'?indent(' * ')", " * line1\n * line2");
     }
 
     @Test
-    public void testDedentNoTrailingNewline() throws Exception {
-        assertEquals("hello",
-                eval("'    hello'?dedent('    ')"));
+    public void testIndentBadNumberOfArgs() {
+        assertErrorContains("${''?indent()}",  "?indent", "expects 1 argument");
+        assertErrorContains("${''?indent(1, 2)}",  "?indent", "expects 1 argument");
     }
 
     @Test
-    public void testDedentSymmetryWithIndent() throws Exception {
-        // indent then dedent should round-trip
-        Map<String, Object> model = new HashMap<>();
-        model.put("text", "line1\nline2\nline3");
-        assertEquals("line1\nline2\nline3",
-                eval("text?indent('  ')?dedent('  ')", model));
+    public void testWrap1Arg() throws Exception {
+        assertExpOutput("'Hello world'?wrap(4)", "Hello\nworld\n");
+        assertExpOutput("'Hello world'?wrap(40)", "Hello world\n");
     }
 
-    // ---- ?dedent (no-args, Python textwrap.dedent-style) tests ----
-
     @Test
-    public void testDedentNoArgsUniformIndent() throws Exception {
-        assertEquals("a\nb\nc",
-                eval("'    a\\n    b\\n    c'?dedent()"));
+    public void testWrap2Arg() throws Exception {
+        assertExpOutput("'Hello world'?wrap(4, '* ')", "* Hello\n* world\n");
     }
 
     @Test
-    public void testDedentNoArgsMixedIndent() throws Exception {
-        // The longest common leading whitespace across non-empty lines is 2 spaces.
-        assertEquals("a\n  b\n    c",
-                eval("'  a\\n    b\\n      c'?dedent()"));
+    public void testWrap3Args() throws Exception {
+        assertExpOutput("'Hello world'?wrap(4, '* ', '  ')", "* Hello\n  world\n");
     }
 
     @Test
-    public void testDedentNoArgsRespectsEmptyLines() throws Exception {
-        // Empty/whitespace-only lines are ignored when computing the common prefix
-        // and pass through unchanged.
-        assertEquals("a\n\nb",
-                eval("'    a\\n\\n    b'?dedent()"));
+    public void testWrapNoArgTypeCoercion() throws Exception {
+        assertErrorContains("${''?wrap(4, 1)}", "string as argument #2");
     }
 
     @Test
-    public void testDedentNoArgsNoCommonPrefix() throws Exception {
-        // If lines have no common leading whitespace, nothing is stripped.
-        assertEquals("a\n    b",
-                eval("'a\\n    b'?dedent()"));
+    public void testWrapBadNumberOfArgs() {
+        assertErrorContains("${''?wrap()}",  "?wrap", "expects 1 to 3 arguments");
+        assertErrorContains("${''?wrap(4, '*', '**', '***')}",  "?wrap", "expects 1 to 3 arguments");
     }
 
     @Test
-    public void testDedentNoArgsTabAndSpaceDistinct() throws Exception {
-        // A leading tab and a leading space have no common prefix.
-        // (Same behaviour as Python textwrap.dedent.)
-        assertEquals("\ta\n    b",
-                eval("'\\ta\\n    b'?dedent()"));
+    public void testWrapArg1AtLeast1() throws TemplateException, IOException {
+        assertErrorContains("${''?wrap(0, '* ')}", "width", "at least 1");
+        assertErrorContains("${''?wrap(-1, '* ')}", "width", "at least 1");
     }
 
     @Test
-    public void testDedentNoArgsTabsOnly() throws Exception {
-        assertEquals("a\nb",
-                eval("'\\t\\ta\\n\\t\\tb'?dedent()"));
+    public void testWrapBadArgTypeError() {
+        assertErrorContains("${''?wrap('4', '*')}",  "number as argument #1");
     }
 
     @Test
-    public void testDedentNoArgsEmptyString() throws Exception {
-        assertEquals("", eval("''?dedent()"));
+    public void testDedent1Arg() throws Exception {
+        assertExpOutput("'    int x;\\n    int y;\\n'?dedent('    ')", "int x;\nint y;\n");
+        assertExpOutput("'  hello'?dedent('')", "  hello");
     }
 
     @Test
-    public void testDedentNoArgsAlreadyDedented() throws Exception {
-        // No common leading whitespace => no change.
-        assertEquals("a\nb\nc",
-                eval("'a\\nb\\nc'?dedent()"));
+    public void testDedent0Arg() throws Exception {
+        assertExpOutput("'  a\\n   b\\n  c'?dedent", "a\n b\nc");
     }
 
-    // ---- ?right_pad_lines tests ----
-
     @Test
-    public void testRightPadLinesBasic() throws Exception {
-        assertEquals("a         \nbb        \nccc       \n",
-                eval("'a\\nbb\\nccc\\n'?right_pad_lines(10)"));
+    public void testDedentBadNumberOfArgs() {
+        assertErrorContains("${''?dedent()}",  "?dedent", "expects 1 argument");
+        assertErrorContains("${''?dedent('  ', 2)}",  "?dedent", "expects 1 argument");
     }
 
     @Test
-    public void testRightPadLinesWithFillChar() throws Exception {
-        assertEquals("a.........\nbb........\n",
-                eval("'a\\nbb\\n'?right_pad_lines(10, '.')"));
+    public void testDedentNoArgTypeCoercion() throws Exception {
+        assertErrorContains("${''?dedent(1)}", "string as argument #1");
     }
 
     @Test
-    public void testRightPadLinesLinePastColumn() throws Exception {
-        // "long line" (9 chars) past column 5 — no padding
-        // "ab" (2 chars) shorter than column 5 — padded
-        assertEquals("long line\nab   \n",
-                eval("'long line\\nab\\n'?right_pad_lines(5)"));
+    public void testRightPad1Arg() throws Exception {
+        assertExpOutput("'a\nbb\nccc'?right_pad_lines(5)", "a    \nbb   \nccc  ");
     }
 
     @Test
-    public void testRightPadLinesNoTrailingNewline() throws Exception {
-        assertEquals("a         ",
-                eval("'a'?right_pad_lines(10)"));
+    public void testRightPad2Arg() throws Exception {
+        assertExpOutput("'a\nbb\nccc'?right_pad_lines(5, '.')", "a....\nbb...\nccc..");
     }
 
     @Test
-    public void testRightPadLinesEmpty() throws Exception {
-        assertEquals("", eval("''?right_pad_lines(10)"));
+    public void testRightPadLinesCamelCase() throws Exception {
+        assertExpOutput("'a\nbb\nccc'?rightPadLines(5, '.')", "a....\nbb...\nccc..");
     }
 
     @Test
-    public void testRightPadLinesCamelCase() throws Exception {
-        assertEquals("a    \nbb   \n",
-                eval("'a\\nbb\\n'?rightPadLines(5)"));
+    public void testRightPadLinesBadNumberOfArgs() {
+        assertErrorContains("${''?right_pad_lines()}",  "?right_pad_lines", "expects 1 or 2 arguments");
+        assertErrorContains("${''?rightPadLines(1, '.', 3)}",  "?rightPadLines", "expects 1 or 2 arguments");
     }
 
     @Test
-    public void testRightPadLinesCodeAlignment() throws Exception {
-        // Practical use: align code for trailing comments
-        Map<String, Object> model = new HashMap<>();
-        model.put("code", "int x;\nString name;\nboolean active;\n");
-        String result = eval("code?right_pad_lines(20)", model);
-        String[] lines = result.split("\n", -1);
-        assertEquals("int x;              ", lines[0]);
-        assertEquals("String name;        ", lines[1]);
-        assertEquals("boolean active;     ", lines[2]);
+    public void testRightPadLinesNoArgTypeCoercion() throws Exception {
+        assertErrorContains("${''?right_pad_lines('1', '.')}", "number as argument #1");
+        assertErrorContains("${''?right_pad_lines(1, 2)}", "string as argument #2");
     }
 }
diff --git a/freemarker-core/src/test/java/freemarker/core/_CoreStringUtilsTest.java b/freemarker-core/src/test/java/freemarker/core/_CoreStringUtilsTest.java
new file mode 100644
index 00000000..c9db7df2
--- /dev/null
+++ b/freemarker-core/src/test/java/freemarker/core/_CoreStringUtilsTest.java
@@ -0,0 +1,391 @@
+package freemarker.core;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import freemarker.template.utility.StringUtil;
+import freemarker.test.hamcerst.Matchers;
+
+public class _CoreStringUtilsTest {
+
+    // ---- indent tests ----
+
+    @Test
+    public void testIndentSingleLine() {
+        assertEquals(
+                "    hello",
+                _CoreStringUtils.indent("hello", "    "));
+    }
+
+    @Test
+    public void testIndentMultiLine() {
+        assertEquals(
+                "  line1\n  line2\n  line3",
+                _CoreStringUtils.indent("line1\nline2\nline3", "  "));
+    }
+
+    @Test
+    public void testIndentWithPrefix() {
+        assertEquals(
+                " * line1\n * line2",
+                _CoreStringUtils.indent("line1\nline2", " * "));
+    }
+
+    @Test
+    public void testIndentEmptyString() {
+        assertEquals(
+                "",
+                _CoreStringUtils.indent("", "  "));
+    }
+
+    @Test
+    public void testIndentPreservesBlankLines() {
+        assertEquals(
+                "  a\n\n  b",
+                _CoreStringUtils.indent("a\n\nb", "  "));
+    }
+
+    @Test
+    public void testIndentTrailingNewline() {
+        assertEquals(
+                "  a\n  b\n",
+                _CoreStringUtils.indent("a\nb\n", "  "));
+    }
+
+    // ---- wrap tests ----
+
+    @Test
+    public void testWrapBasic() {
+        assertEquals(
+                " * @brief Hello world.\n",
+                _CoreStringUtils.wrap("Hello world.", 40, " * @brief "));
+    }
+
+    @Test
+    public void testWrapLongTextNoPrefix() {
+        testWrapLongText(null, null);
+    }
+
+    @Test
+    public void testWrapLongTextFirstPrefixOnly() {
+        testWrapLongText(" * ", null);
+    }
+
+    @Test
+    public void testWrapLongTextWithDifferentPrefixes() {
+        testWrapLongText(" * @brief ", " *          ");
+    }
+
+    private void testWrapLongText(String firstPrefix, String restPrefix) {
+        for (int width = 30; width <= 100; width += 10) {
+            testWrapLongText(width, firstPrefix, restPrefix);
+        }
+    }
+
+    private void testWrapLongText(int width, String firstPrefix, String restPrefix) {
+        String text = "This is a description that needs wrapping to fit within bounds. Also it's a very long text.";
+
+        String result =
+                firstPrefix == null ? _CoreStringUtils.wrap(text, width)
+                        : restPrefix == null ? _CoreStringUtils.wrap(text, width, firstPrefix)
+                                : _CoreStringUtils.wrap(text, width, firstPrefix, restPrefix);
+
+        String effFirstPrefix = firstPrefix != null ? firstPrefix : "";
+        String effRestPrefix = restPrefix != null ? restPrefix : effFirstPrefix;
+
+        assertTrue(result.startsWith(effFirstPrefix));
+
+        // Second line should start with rest prefix
+        String[] lines = result.split("\n", -1);
+        for (int i = 1; i < lines.length - 1; i++) {
+            String line = lines[i];
+            if (line.length() > width) {
+                fail("Line " + i + " is too long: " + StringUtil.jQuote(line));
+            }
+            if (!line.startsWith(effRestPrefix)) {
+                fail("Line " + i + " doesn't start as expected: " + StringUtil.jQuote(line));
+            }
+        }
+
+        assertEquals("", lines[lines.length - 1]);
+        assertTrue(result.endsWith("\n"));
+    }
+
+    @Test
+    public void testWrapSamePrefix() {
+        assertEquals(
+                "// hello world\n",
+                _CoreStringUtils.wrap("hello world", 40, "// "));
+    }
+
+    @Test
+    public void testWrapSingleLongWord() {
+        // A single word longer than width — can't break, just emit it
+        assertEquals(
+                "superlongword\n",
+                _CoreStringUtils.wrap("superlongword", 4, ""));
+        // Not even after the prefix
+        assertEquals(
+                "  *  superlongword\n",
+                _CoreStringUtils.wrap("superlongword", 4, "  *  "));
+    }
+
+    @Test
+    public void testWrapCollapsesWhitespaces() {
+        assertEquals(
+                "a b c d e\n",
+                _CoreStringUtils.wrap("  a  \n b \n c\t\td   e  ", 40, ""));
+    }
+
+    @Test
+    public void testWrapWithNbsp() {
+        // No NBSP:
+        assertEquals(
+                "word1\nword2\nword3\nword4\n",
+                _CoreStringUtils.wrap("word1 word2 word3 word4", 4));
+        // With NBSP:
+        assertEquals(
+                "word1\u00A0word2\u00A0word3\u00A0word4\n",
+                _CoreStringUtils.wrap("word1\u00A0word2\u00A0word3\u00A0word4", 4));
+        assertEquals(
+                "word1\u00A0word2\nword3\u00A0word4\n",
+                _CoreStringUtils.wrap("word1\u00A0word2 word3\u00A0word4", 4));
+        assertEquals(
+                "word1\u00A0\nword2\n\u00A0word3\n",
+                _CoreStringUtils.wrap("word1\u00A0 word2 \u00A0word3", 4));
+        assertEquals(
+                "\u00A0 a \u00A0\u00A0 b \u00A0\n",
+                _CoreStringUtils.wrap(" \u00A0  a  \u00A0\u00A0 b \u00A0  ", 40, ""));
+    }
+
+    @Test
+    public void testWrapWithInputLeadingTrailingEmptyLinesDoesntMatter() {
+        assertEquals(
+                "word1\nword2\n",
+                _CoreStringUtils.wrap("word1 word2", 4));
+        assertEquals(
+                "word1\nword2\n",
+                _CoreStringUtils.wrap("word1 word2\n", 4));
+        assertEquals(
+                "word1\nword2\n",
+                _CoreStringUtils.wrap("\n\nword1 word2\n\n", 4));
+    }
+
+    @Test
+    public void testWrapZeroWidthThrows() {
+        try {
+            _CoreStringUtils.wrap("hello", 0);
+            fail();
+        } catch (IllegalArgumentException e) {
+            assertThat(
+                    e.getMessage(),
+                    Matchers.containsStringIgnoringCase("must be at least 1"));
+        }
+    }
+
+    // ---- dedent tests ----
+
+    @Test
+    public void testDedentBasic() {
+        assertEquals(
+                "int x;\nint y;\n",
+                _CoreStringUtils.dedent("    int x;\n    int y;\n", "    ")
+        );
+    }
+
+    @Test
+    public void testDedentNoMatch() {
+        // Line doesn't start with prefix — left unchanged
+        // "  short" has only 2 spaces, doesn't match 4-space prefix → unchanged
+        // "    full" has 4 spaces, matches prefix → stripped
+        assertEquals(
+                "  short\nfull\n",
+                _CoreStringUtils.dedent("  short\n    full\n", "    ")
+        );
+    }
+
+    @Test
+    public void testDedentMixed() {
+        // Some lines match, some don't
+        assertEquals(
+                "a\n  b\nc\n",
+                _CoreStringUtils.dedent("  a\n    b\n  c\n", "  ")
+        );
+    }
+
+    @Test
+    public void testDedentEmptyString() {
+        assertEquals(
+                "",
+                _CoreStringUtils.dedent("", "  ")
+        );
+    }
+
+    @Test
+    public void testDedentEmptyPrefix() {
+        assertEquals(
+                "  hello",
+                _CoreStringUtils.dedent("  hello", "")
+        );
+    }
+
+    @Test
+    public void testDedentNoTrailingNewline() {
+        assertEquals(
+                "hello",
+                _CoreStringUtils.dedent("    hello", "    ")
+        );
+    }
+
+    @Test
+    public void testDedentSymmetryWithIndent() {
+        // indent then dedent should round-trip
+        String text = "line1\n line2\nline3";
+        String prefix = "  ";
+        assertEquals(
+                text,
+                _CoreStringUtils.dedent(_CoreStringUtils.indent(text, prefix), prefix)
+        );
+    }
+
+    // ---- dedent no-args (Python textwrap.dedent-style) tests ----
+
+    @Test
+    public void testDedentNoArgsUniformIndent() {
+        assertEquals(
+                "a\nb\nc",
+                _CoreStringUtils.dedent("    a\n    b\n    c")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsMixedIndent() {
+        // The longest common leading whitespace across non-empty lines is 2 spaces.
+        assertEquals(
+                "a\n  b\n    c",
+                _CoreStringUtils.dedent("  a\n    b\n      c")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsRespectsEmptyLines() {
+        // Empty/whitespace-only lines are ignored when computing the common prefix
+        // and pass through unchanged.
+        assertEquals(
+                "a\n\nb",
+                _CoreStringUtils.dedent("    a\n\n    b")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsNoCommonPrefix() {
+        // If lines have no common leading whitespace, nothing is stripped.
+        assertEquals(
+                "a\n    b",
+                _CoreStringUtils.dedent("a\n    b")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsTabAndSpaceDistinct() {
+        // A leading tab and a leading space have no common prefix.
+        // (Same behaviour as Python textwrap.dedent.)
+        assertEquals(
+                "\ta\n    b",
+                _CoreStringUtils.dedent("\ta\n    b")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsTabsOnly() {
+        assertEquals(
+                "a\nb",
+                _CoreStringUtils.dedent("\t\ta\n\t\tb")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsEmptyString() {
+        assertEquals(
+                "",
+                _CoreStringUtils.dedent("")
+        );
+    }
+
+    @Test
+    public void testDedentNoArgsAlreadyDedented() {
+        // No common leading whitespace => no change.
+        assertEquals(
+                "a\nb\nc",
+                _CoreStringUtils.dedent("a\nb\nc")
+        );
+    }
+
+    // ---- rightPadLines tests ----
+
+    @Test
+    public void testRightPadLinesBasic() {
+        assertEquals(
+                "a         \nbb        \nccc       \n",
+                _CoreStringUtils.rightPadLines("a\nbb\nccc\n", 10)
+        );
+    }
+
+    @Test
+    public void testRightPadLinesWithFillChar() {
+        assertEquals(
+                "a.........\nbb........\n",
+                _CoreStringUtils.rightPadLines("a\nbb\n", 10, '.')
+        );
+    }
+
+    @Test
+    public void testRightPadLinesLinePastColumn() {
+        // "long line" (9 chars) past column 5 — no padding
+        // "ab" (2 chars) shorter than column 5 — padded
+        assertEquals(
+                "long line\nab   \n",
+                _CoreStringUtils.rightPadLines("long line\nab\n", 5)
+        );
+    }
+
+    @Test
+    public void testRightPadLinesNoTrailingNewline() {
+        assertEquals(
+                "a         ",
+                _CoreStringUtils.rightPadLines("a", 10)
+        );
+    }
+
+    @Test
+    public void testRightPadLinesEmpty() {
+        assertEquals(
+                "",
+                _CoreStringUtils.rightPadLines("", 10)
+        );
+    }
+
+    @Test
+    public void testRightPadLinesCamelCase() {
+        assertEquals(
+                "a    \nbb   \n",
+                _CoreStringUtils.rightPadLines("a\nbb\n", 5)
+        );
+    }
+
+    @Test
+    public void testRightPadLinesCodeAlignment() {
+        // Practical use: align code for trailing comments
+        String code = "int x;\nString name;\nboolean active;\n";
+        String result = _CoreStringUtils.rightPadLines(code, 20);
+        String[] lines = result.split("\n", -1);
+        assertEquals("int x;              ", lines[0]);
+        assertEquals("String name;        ", lines[1]);
+        assertEquals("boolean active;     ", lines[2]);
+        assertEquals("", lines[3]);
+    }
+
+}
diff --git a/freemarker-manual/src/main/docgen/en_US/book.xml b/freemarker-manual/src/main/docgen/en_US/book.xml
index 2e78de80..8ac13aa1 100644
--- a/freemarker-manual/src/main/docgen/en_US/book.xml
+++ b/freemarker-manual/src/main/docgen/en_US/book.xml
@@ -11298,8 +11298,8 @@ TemplateHashModel fileStatics =
 
           <para>And you will get a template hash model that exposes all static
           methods and static fields (both final and non-final) of the
-          <literal>java.io.File</literal> class as hash keys. Suppose that
-          you put the previous model in your root model:</para>
+          <literal>java.io.File</literal> class as hash keys. Suppose that you
+          put the previous model in your root model:</para>
 
           <programlisting role="unspecified">root.put("File", fileStatics);</programlisting>
 
@@ -14071,17 +14071,17 @@ Green Mouse</programlisting>
             <para>This built-in is available since FreeMarker 2.3.35.</para>
           </note>
 
-          <para>Removes a leading-whitespace prefix from each line of the
-          string. The built-in has two forms: a no-argument form that strips
-          common leading whitespace automatically, and an explicit-prefix form
-          for exact control. This is the inverse of the <link
+          <para>Removes a leading prefix from each line of the string. The
+          built-in has two forms: a no-argument form that strips common
+          leading whitespace automatically, and an explicit-prefix form for
+          exact control. This is the inverse of the <link
           linkend="ref_builtin_indent"><literal>indent</literal></link>
-          built-in. Line breaks can be <literal>LF</literal>,
-          <literal>CR</literal>, or <literal>CRLF</literal>, and are kept as
-          is.</para>
+          built-in. Line-breaks can be <literal>LF</literal> (Linux), or
+          <literal>CRLF</literal> (DOS/Windows), even <literal>CR</literal>
+          (old Mac), and are kept as is.</para>
 
           <para>The <emphasis>no-argument form</emphasis>
-          (<literal>?dedent()</literal>) finds the longest leading whitespace
+          (<literal>?dedent</literal>) finds the longest leading whitespace
           (spaces and tabs only) that is a common prefix of every non-empty
           line, and removes it. This is robust to imperfect input: lines with
           different leading-whitespace amounts work as expected, and
@@ -14091,14 +14091,15 @@ Green Mouse</programlisting>
 
           <para>For example:</para>
 
-          <programlisting role="template">&lt;#assign code = "  int x;\n    int y;\n  int z;" /&gt;
-[${code?dedent()}]</programlisting>
+          <programlisting role="template">&lt;#assign code = "  if (x) {\n    foo();\n  }" /&gt;
+[${code?dedent}]</programlisting>
 
-          <para>will output this (the common prefix is 2 spaces):</para>
+          <para>will output this (the common prefix was 2 spaces, which was
+          removed):</para>
 
-          <programlisting role="output">[int x;
-  int y;
-int z;]</programlisting>
+          <programlisting role="output">if (x) {
+  foo();
+}</programlisting>
 
           <para>A leading tab and a leading space are treated as distinct
           characters (they have no common prefix), matching Python's
@@ -14106,29 +14107,38 @@ int z;]</programlisting>
 
           <para>The <emphasis>explicit-prefix form</emphasis>
           (<literal>?dedent(prefix)</literal>) removes the given prefix from
-          each line that starts with it. Lines that don't start with the prefix
-          are left unchanged. Use this when you want exact control rather than
-          automatic common-prefix detection. For example:</para>
+          each line that starts with it. Lines that don't start with the
+          prefix are left unchanged. Use this when you want exact control
+          rather than automatic common-prefix detection. For example:</para>
 
-          <programlisting role="template">&lt;#assign code = "    int x;\n    int y;" /&gt;
-[${code?dedent("    ")}]</programlisting>
+          <programlisting role="template">&lt;#assign code = "  if (x) {\n    foo();\n  }" /&gt;
+${code?dedent(" ")}</programlisting>
 
-          <para>will output this:</para>
+          <para>will output this (removed just 1 space of indentation, so the
+          1st line still has 1 space of indentation, and the 2nd has 3 spaces
+          of indentation):</para>
 
-          <programlisting role="output">[int x;
-int y;]</programlisting>
+          <programlisting role="output"> if (x) {
+   foo();
+ }</programlisting>
 
           <para>Lines that don't start with the prefix are unaffected, so with
           a 4-space prefix:</para>
 
-          <programlisting role="template">&lt;#assign text = "  short\n      long" /&gt;
-${text?dedent("    ")}</programlisting>
+          <programlisting role="template">&lt;#assign code = "  if (x) {\n    foo();\n  }" /&gt;
+${code?dedent("    ")}</programlisting>
+
+          <para>will output this (the second line had at least 4 space
+          indentation, so 4 were removed, the other lines only had 2 spaces,
+          so they were left alone):</para>
 
-          <para>will output this (the first line had only 2 leading spaces, so
-          it's unchanged; the second had at least 4, so 4 were removed):</para>
+          <programlisting role="output">  if (x) {
+foo();
+  }</programlisting>
 
-          <programlisting role="output">  short
-  long</programlisting>
+          <para>See also the <link
+          linkend="ref_builtin_indent"><literal>indent</literal>
+          built-in</link>, which is its inverse.</para>
         </section>
 
         <section xml:id="ref_builtin_empty_to_null">
@@ -14445,19 +14455,20 @@ R&amp;amp;D</programlisting>
           each line. The parameter is most often some spaces or tabs used for
           indentation, but can be any string. Lines that are empty (i.e., the
           line break immediately follows the previous line break, or the line
-          is the empty last line) are not prefixed. Line breaks can be
-          <literal>LF</literal>, <literal>CR</literal>, or
-          <literal>CRLF</literal>, and are kept as is.</para>
+          is the empty last line) are not prefixed. Line-breaks can be
+          <literal>LF</literal> (Linux), or <literal>CRLF</literal>
+          (DOS/Windows), even <literal>CR</literal> (old Mac), and are kept as
+          is.</para>
 
           <para>For example, this:</para>
 
           <programlisting role="template">&lt;#assign code = "int x;\nint y;" /&gt;
-[${code?indent("    ")}]</programlisting>
+${code?indent("    ")}</programlisting>
 
           <para>will output this:</para>
 
-          <programlisting role="output">[    int x;
-    int y;]</programlisting>
+          <programlisting role="output">    int x;
+    int y;</programlisting>
 
           <para>Another example, using a non-whitespace prefix:</para>
 
@@ -14469,9 +14480,9 @@ ${text?indent(" * ")}</programlisting>
           <programlisting role="output"> * First line.
  * Second line.</programlisting>
 
-          <para>See also: the <link
-          linkend="ref_builtin_dedent"><literal>dedent</literal></link>
-          built-in, which is its inverse.</para>
+          <para>See also the <link
+          linkend="ref_builtin_dedent"><literal>dedent</literal>
+          built-in</link>, which is its inverse.</para>
         </section>
 
         <section xml:id="ref_builtin_index_of">
@@ -15164,25 +15175,28 @@ ${s?no_esc}</programlisting>
           already at least that long are left unchanged. Unlike <link
           linkend="ref_builtin_right_pad"><literal>right_pad</literal></link>,
           which operates on the string as a whole, this operates on each line
-          separately, which is useful for aligning multi-line text. Empty lines
-          are not padded. Line breaks can be <literal>LF</literal>,
-          <literal>CR</literal>, or <literal>CRLF</literal>, and are kept as
-          is.</para>
+          separately, which is useful for aligning multi-line text. Empty
+          lines are not padded. Line-breaks can be <literal>LF</literal>
+          (Linux), or <literal>CRLF</literal> (DOS/Windows), even
+          <literal>CR</literal> (old Mac), and are kept as is.</para>
 
           <para>For example, this:</para>
 
           <programlisting role="template">&lt;#assign code = "int x;\nString name;\nboolean active;" /&gt;
 ${code?right_pad_lines(20)}done</programlisting>
 
-          <para>will output this (each line padded to width 20):</para>
+          <para>will output this (each line padded to width 20, the <phrase
+          role="markedInvisibleText">[BR]</phrase> is only shown below to
+          illustrate the line-break):</para>
 
-          <programlisting role="output">int x;
-String name;
+          <programlisting role="output">int x;              <phrase
+              role="markedInvisibleText">[BR]</phrase>
+String name;        <phrase role="markedInvisibleText">[BR]</phrase>
 boolean active;     done</programlisting>
 
-          <para>If used with 2 parameters, the 2nd parameter specifies the fill
-          character to use instead of space. It must be a string exactly 1
-          character long. For example:</para>
+          <para>If used with 2 parameters, the 2nd parameter specifies the
+          fill character to use instead of space. It must be a string exactly
+          1 character long. For example:</para>
 
           <programlisting role="template">${"a\nbb"?right_pad_lines(5, ".")}</programlisting>
 
@@ -16170,48 +16184,83 @@ ${x?url}</programlisting>
             <para>This built-in is available since FreeMarker 2.3.35.</para>
           </note>
 
-          <para>Word-wraps the string so that no line is longer than the column
-          (width) given as the 1st parameter, breaking only between words
-          (runs of <link linkend="gloss.whiteSpace">white-space</link> in the
-          input are treated as word boundaries and collapsed to a single
-          space). The 2nd parameter is a prefix prepended to the first output
-          line; the optional 3rd parameter is a prefix prepended to all
-          subsequent lines (if omitted, the 2nd parameter is used for all
-          lines). The result always ends with a line break.</para>
+          <para>Word-wraps the string so that if possible, no line is longer
+          than the width given as the 1st parameter. It breaks line at <link
+          linkend="gloss.whiteSpace">white-space</link> only. A section
+          without white-space that's longer than the width is emitted on its
+          own line without being broken.</para>
 
-          <para>This is useful for generating wrapped comments, such as
-          documentation blocks. For example:</para>
+          <para><link linkend="gloss.whiteSpace">White-space</link>
+          treatment:</para>
 
-          <programlisting role="template">&lt;#assign text = "This is a long description that should be wrapped" /&gt;
-${text?wrap(40, " * @brief ", " *         ")}</programlisting>
+          <itemizedlist>
+            <listitem>
+              <para>Each continuous sequence of white-space characters in the
+              input is in effect collapsed to a single space, or removed if
+              they are before a word-wrapping line-break</para>
+            </listitem>
 
-          <para>will output this:</para>
+            <listitem>
+              <para>The result always ends with a single line-break</para>
+            </listitem>
 
-          <programlisting role="output"> * @brief This is a long description
- *         that should be wrapped</programlisting>
+            <listitem>
+              <para>All leading and trailing whitespace of the input
+              (including line-breaks!) is removed in effect</para>
+            </listitem>
+
+            <listitem>
+              <para>Non-breaking space (U+00A0) is <emphasis>not</emphasis>
+              treated as white-space by this built-in. <phrase
+              role="forProgrammers">(We treat the Java regular expression
+              <literal>\s</literal> as white-space, which does
+              <emphasis>not</emphasis> include the non-breaking
+              space.)</phrase></para>
+            </listitem>
+          </itemizedlist>
 
-          <para>With a single prefix used for all lines:</para>
+          <para>Example:</para>
 
-          <programlisting role="template">${"A comment that needs to be wrapped at a reasonable width"?wrap(40, "// ")}</programlisting>
+          <programlisting role="template">${"Some long text that need to be wrapper at reasonable width"?wrap(25)}</programlisting>
 
           <para>will output this:</para>
 
-          <programlisting role="output">// A comment that needs to be wrapped at
-// a reasonable width</programlisting>
+          <programlisting role="output">Some long text that need
+to be wrapper at
+reasonable width
+</programlisting>
 
-          <para>The 1st parameter (width) must be at least 1. A single word
-          longer than the width is emitted on its own line without being
-          broken.</para>
+          <para>The width parameter is truncated to integer, and must be at
+          least 1.</para>
 
-          <note>
-            <para>Widths are counted in Java <literal>char</literal>s (UTF-16
-            code units), not visual display columns. A tab counts as one
-            character. Words are split on Java's <literal>\s+</literal>
-            character class, which does <emphasis>not</emphasis> include
-            U+00A0 (the non-breaking space) — so a non-breaking space stays
-            inside a word and is never used as a break point. This is the
-            intended behaviour of non-breaking spaces.</para>
-          </note>
+          <section>
+            <title>Adding line suffixed</title>
+
+            <para>An optional 2nd parameter is a prefix prepended to the first
+            output line. The optional 3rd parameter is a prefix prepended to
+            all subsequent lines. If the 3rd parameter is omitted, the 2nd
+            parameter is used for all lines.</para>
+
+            <para>This is useful for generating wrapped comments, such as
+            documentation blocks. For example:</para>
+
+            <programlisting role="template">&lt;#assign text = "This is a long description that should be wrapped" /&gt;
+${text?wrap(40, " * @brief ", " *         ")}</programlisting>
+
+            <para>will output this:</para>
+
+            <programlisting role="output"> * @brief This is a long description
+ *         that should be wrapped</programlisting>
+
+            <para>With a single prefix used for all lines:</para>
+
+            <programlisting role="template">${"A comment that needs to be wrapped at a reasonable width"?wrap(40, "// ")}</programlisting>
+
+            <para>will output this:</para>
+
+            <programlisting role="output">// A comment that needs to be wrapped at
+// a reasonable width</programlisting>
+          </section>
         </section>
 
         <section xml:id="ref_builtin_xhtml">
@@ -30849,6 +30898,21 @@ TemplateModel x = env.getVariable("x");  // get variable x</programlisting>
 
         <para>Release date: [TODO]</para>
 
+        <section>
+          <title>Changes on the FTL side</title>
+
+          <itemizedlist>
+            <listitem>
+              <para>New built-ins, mostly useful for source code (or
+              configuration file) generation: <link
+              linkend="ref_builtin_dedent">dedent</link>, <link
+              linkend="ref_builtin_indent">indent</link>, <link
+              linkend="ref_builtin_right_pad_lines">right_pad_lines</link>,
+              <link linkend="ref_builtin_wrap">wrap</link></para>
+            </listitem>
+          </itemizedlist>
+        </section>
+
         <section>
           <title>Changes on the Java side</title>
 
diff --git a/freemarker-test-utils/src/main/java/freemarker/test/TemplateTest.java b/freemarker-test-utils/src/main/java/freemarker/test/TemplateTest.java
index c67117ff..73845351 100644
--- a/freemarker-test-utils/src/main/java/freemarker/test/TemplateTest.java
+++ b/freemarker-test-utils/src/main/java/freemarker/test/TemplateTest.java
@@ -99,6 +99,11 @@ public abstract class TemplateTest {
         assertOutput(createTemplate(ftl), expectedOut, false);
     }
 
+    // !!T exchange params
+    protected void assertExpOutput(String ftlExpression, String expectedOut) throws IOException, TemplateException {
+        assertOutput("${" + ftlExpression + "}", expectedOut);
+    }
+
     private Template createTemplate(String ftl) throws IOException {
         Template t = new Template(null, ftl, getConfiguration());
         return t;