X-Git-Url: http://git.nikiroo.be/?a=blobdiff_plain;f=src%2Fbe%2Fnikiroo%2Futils%2Fmain%2Fjustify.java;fp=src%2Fbe%2Fnikiroo%2Futils%2Fmain%2Fjustify.java;h=cf589059a5ebf398cea085fcfc06913067e32d73;hb=9e50696ec75e70b4eb592a9a1b6fceacf169977f;hp=0000000000000000000000000000000000000000;hpb=ce060f5a4fcbea33cbecf2e8696fde7db183bff0;p=nikiroo-utils.git diff --git a/src/be/nikiroo/utils/main/justify.java b/src/be/nikiroo/utils/main/justify.java new file mode 100644 index 0000000..cf58905 --- /dev/null +++ b/src/be/nikiroo/utils/main/justify.java @@ -0,0 +1,95 @@ +package be.nikiroo.utils.main; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +import be.nikiroo.utils.StringUtils; +import be.nikiroo.utils.StringUtils.Alignment; + +/** + * Text justification (left, right, center, justify). + * + * @author niki + */ +public class justify { + /** + * Syntax: $0 ([left|right|center|justify]) (max width) + *

+ *

+ * + * @param args + */ + public static void main(String[] args) { + int width = -1; + StringUtils.Alignment align = Alignment.LEFT; + + if (args.length >= 1) { + align = Alignment.valueOf(args[0].toUpperCase()); + } + if (args.length >= 2) { + width = Integer.parseInt(args[1]); + } + + // TODO: move to utils? + List lines = new ArrayList(); + Scanner scan = new Scanner(System.in); + scan.useDelimiter("[\r\n]"); + try { + StringBuilder previous = null; + StringBuilder tmp = new StringBuilder(); + while (scan.hasNext()) { + String current = scan.next(); + tmp.setLength(0); + for (String word : current.split(" ")) { + if (word.isEmpty()) { + continue; + } + + if (tmp.length() > 0) { + tmp.append(' '); + } + tmp.append(word.trim()); + } + current = tmp.toString(); + + if (previous == null) { + previous = new StringBuilder(); + } else { + if (current.isEmpty() || isFullLine(previous)) { + lines.add(previous.toString()); + previous.setLength(0); + } else { + previous.append(' '); + } + } + + previous.append(current); + } + + if (previous != null) { + lines.add(previous.toString()); + } + } finally { + scan.close(); + } + + // TODO: supports bullet lines "- xxx" and sub levels + for (String line : lines) { + for (String subline : StringUtils.justifyText(line, width, align)) { + System.out.println(subline); + } + } + } + + static private boolean isFullLine(StringBuilder line) { + return line.length() == 0 // + || line.charAt(line.length() - 1) == '.' + || line.charAt(line.length() - 1) == '"' + || line.charAt(line.length() - 1) == '»'; + } +}