Commit | Line | Data |
---|---|---|
9e50696e NR |
1 | package be.nikiroo.utils.main; |
2 | ||
3 | import java.util.ArrayList; | |
4 | import java.util.List; | |
5 | import java.util.Scanner; | |
6 | ||
7 | import be.nikiroo.utils.StringUtils; | |
8 | import be.nikiroo.utils.StringUtils.Alignment; | |
9 | ||
10 | /** | |
11 | * Text justification (left, right, center, justify). | |
12 | * | |
13 | * @author niki | |
14 | */ | |
15 | public class justify { | |
16 | /** | |
17 | * Syntax: $0 ([left|right|center|justify]) (max width) | |
18 | * <p> | |
19 | * <ul> | |
20 | * <li>mode: left, right, center or full justification (defaults to left)</li> | |
21 | * <li>max width: the maximum width of a line, or "" for "no maximum" | |
22 | * (defaults to "no maximum")</li> | |
23 | * </ul> | |
24 | * | |
25 | * @param args | |
26 | */ | |
27 | public static void main(String[] args) { | |
28 | int width = -1; | |
29 | StringUtils.Alignment align = Alignment.LEFT; | |
30 | ||
31 | if (args.length >= 1) { | |
32 | align = Alignment.valueOf(args[0].toUpperCase()); | |
33 | } | |
34 | if (args.length >= 2) { | |
35 | width = Integer.parseInt(args[1]); | |
36 | } | |
37 | ||
38 | // TODO: move to utils? | |
39 | List<String> lines = new ArrayList<String>(); | |
40 | Scanner scan = new Scanner(System.in); | |
41 | scan.useDelimiter("[\r\n]"); | |
42 | try { | |
43 | StringBuilder previous = null; | |
44 | StringBuilder tmp = new StringBuilder(); | |
45 | while (scan.hasNext()) { | |
46 | String current = scan.next(); | |
47 | tmp.setLength(0); | |
48 | for (String word : current.split(" ")) { | |
49 | if (word.isEmpty()) { | |
50 | continue; | |
51 | } | |
52 | ||
53 | if (tmp.length() > 0) { | |
54 | tmp.append(' '); | |
55 | } | |
56 | tmp.append(word.trim()); | |
57 | } | |
58 | current = tmp.toString(); | |
59 | ||
60 | if (previous == null) { | |
61 | previous = new StringBuilder(); | |
62 | } else { | |
63 | if (current.isEmpty() || isFullLine(previous)) { | |
64 | lines.add(previous.toString()); | |
65 | previous.setLength(0); | |
66 | } else { | |
67 | previous.append(' '); | |
68 | } | |
69 | } | |
70 | ||
71 | previous.append(current); | |
72 | } | |
73 | ||
74 | if (previous != null) { | |
75 | lines.add(previous.toString()); | |
76 | } | |
77 | } finally { | |
78 | scan.close(); | |
79 | } | |
80 | ||
81 | // TODO: supports bullet lines "- xxx" and sub levels | |
82 | for (String line : lines) { | |
83 | for (String subline : StringUtils.justifyText(line, width, align)) { | |
84 | System.out.println(subline); | |
85 | } | |
86 | } | |
87 | } | |
88 | ||
89 | static private boolean isFullLine(StringBuilder line) { | |
90 | return line.length() == 0 // | |
91 | || line.charAt(line.length() - 1) == '.' | |
92 | || line.charAt(line.length() - 1) == '"' | |
93 | || line.charAt(line.length() - 1) == 'ยป'; | |
94 | } | |
95 | } |