Library contents

Groovy String.indent

Adjust each line’s indentation and normalize line endings to LF.

A simple example

String.indent

  1. Start with "A" on one line
  2. Do this Indent by two spaces
  3. Result Two spaces, A, newline
Java adds the requested spaces at the front and terminates the line with a newline.

Syntax

Groovy syntax
public String indent(int n)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Indent a printed checklist

A plain-text printer needs to set a checklist apart from its surrounding notice. Add a consistent left margin to each item and inspect how the operation handles line boundaries.

Result··tea|··rice|
Lesson.groovy
println "tea\nrice".indent(2).replace(" ", "·").replace("\n","|")
Output
··tea|··rice|

Two spaces precede every printed item.

Advertisements

Outdent an imported line

A copied checklist or timetable contains meaningful indentation. Adjust the requested leading margin and preserve the subordinate levels so the printed layout still communicates its structure.

Result·Lab|
Lesson.groovy
println "  Lab".indent(-1).replace(" ", "·").replace("\n","|")
Output
·Lab|

Only one leading space is removed.

Indent a packing slip

A stage manager nests two supply items under the main packing heading. Add two spaces to the start of each line before printing it. Brackets around the first line make its indentation visible.

GivenCable / Lamp · indent +2
Worked result[ Cable]

What to watch for

A nonempty result ends with a newline. A negative adjustment removes up to the requested amount of leading whitespace.

Documentation for String.indent