Debian Codegraph @

net/sf/saxon/serialize/HTMLIndenter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize;
9
10 import net.sf.saxon.event.ProxyReceiver;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.SaxonOutputKeys;
16 import net.sf.saxon.om.FingerprintedQName;
17 import net.sf.saxon.om.NodeName;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.tiny.CharSlice;
20 import net.sf.saxon.type.SchemaType;
21
22 import java.util.*;
23
24
25 /**
26 * HTMLIndenter: This ProxyEmitter indents HTML elements, by adding whitespace
27 * character data where appropriate.
28 * The character data is never added when within an inline element.
29 * The string used for indentation defaults to three spaces
30 *
31 * @author Michael Kay
32 */
33
34
35 public class HTMLIndenter extends ProxyReceiver {
36
37 // TODO: some of the logic in this class is probably redundant, e.g. the "sameLine" flag. However,
38 // indentation is under-tested in the W3C test suites, so it's safest to avoid unnecessary changes.
39
40 // The specification has complex rules for deciding whether something is an inline element and whether
41 // indentation is suppressed: the rules for matching names depend on whether it's HTML or XHTML, and which
42 // version. But since the rules are of the form: "if the name matches X, then indentation is not allowed,
43 // otherwise indentation is allowed but not required", there is no harm in having spurious matches. So we
44 // simply do a case-blind match on the local part of the name, which catches all cases where indentation
45 // is not allowed, and is very unlikely to upset anyone by not indenting things that we could have indented.
46
47 // We make one exception (see bug 3877): we don't treat "link" as an inline element under any circumstances,
48 // though HTML5 has some complex rules that treat it as a phrasal element under some conditions, based on the
49 // value of the "rel" attribute.
50
51 final private static String[] formattedTags = {"pre", "script", "style", "textarea", "title", "xmp"};
52 // "xmp" is obsolete but still encountered!
53
54 // When elements are classified as inline, indenting whitespace is not added adjacent to the element.
55
56 // See Saxon bug 3839 and W3C bug 30276. We use a list of inline elements that is the union of
57 // the HTML4 and HTML5 lists, on the basis that no harm is done treating an element as inline
58 // even if the spec doesn't require us to do so. This also means we include elements such as
59 // "ins", "del", and "area" that are sometimes inline and sometimes not.
60
61 final private static String[] inlineTags = {
62 "a", "abbr", "acronym", "applet", "area",
63 "audio", "b", "basefont", "bdi", "bdo", "big", "br", "button", "canvas", "cite", "code", "data",
64 "datalist", "del", "dfn", "em", "embed", "font", "i", "iframe", "img", "input", "ins",
65 "kbd", "label", /*"link" -- excluded, see bug 3877,*/ "map",
66 "mark", "math", "meter", "noscript", "object", "output", "picture",
67 "progress", "q", "ruby", "s", "samp", "script", "select", "small", "span",
68 "strike", "strong", "sub", "sup", "svg", "template", "textarea",
69 "time", "tt", "u", "var", "video", "wbr"};
70
71 final private static Set<String> inlineTable = new HashSet<>(70);
72 final private static Set<String> formattedTable = new HashSet<>(10);
73
74 static {
75 Collections.addAll(inlineTable, inlineTags);
76 Collections.addAll(formattedTable, formattedTags);
77 }
78
79 protected char[] indentChars = {'\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
80
81 private final static int IS_INLINE = 1;
82 private final static int IS_FORMATTED = 2;
83 private final static int IS_SUPPRESSED = 4;
84
85 private String method;
86 private int level = 0;
87 private boolean sameLine = false;
88 private boolean inFormattedTag = false;
89 private boolean afterInline = false;
90 //private boolean afterFormatted = true; // to prevent a newline at the start
91
92 private boolean afterEndElement = false;
93 private int[] propertyStack = new int[20];
94 private Set<String> suppressed = null;
95
96 public HTMLIndenter(Receiver next, String method) {
97 super(next);
98 }
99
100 /**
101 * Set the properties for this indenter
102 *
103 * @param props the serialization properties
104 */
105
106 public void setOutputProperties(Properties props) {
107 String s = props.getProperty(SaxonOutputKeys.SUPPRESS_INDENTATION);
108 if (s != null) {
109 suppressed = new HashSet<>(8);
110 StringTokenizer st = new StringTokenizer(s, " \t\r\n");
111 while (st.hasMoreTokens()) {
112 String clarkName = st.nextToken();
113 suppressed.add(FingerprintedQName.fromClarkName(clarkName).getLocalPart().toLowerCase());
114 }
115 }
116 }
117
118 /**
119 * Classify an element name as inline, formatted, or both or neither.
120 * This method is overridden in the XHTML indenter
121 *
122 * @param name the element name
123 * @return a bit-significant integer containing flags IS_INLINE and/or IS_FORMATTED
124 */
125
126 public int classifyTag(NodeName name) {
127 int r = 0;
128 if (inlineTable.contains(name.getLocalPart().toLowerCase())) {
129 r |= IS_INLINE;
130 }
131 if (formattedTable.contains(name.getLocalPart().toLowerCase())) {
132 r |= IS_FORMATTED;
133 }
134 if (suppressed != null && suppressed.contains(name.getLocalPart().toLowerCase())) {
135 r |= IS_SUPPRESSED;
136 }
137 return r;
138 }
139
140 /**
141 * Output element start tag
142 */
143
144 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
145 int withinSuppressed = level == 0 ? 0 : (propertyStack[level - 1] & IS_SUPPRESSED);
146 int tagProps = classifyTag(nameCode) | withinSuppressed;
147 if (level >= propertyStack.length) {
148 propertyStack = Arrays.copyOf(propertyStack, level * 2);
149 }
150 propertyStack[level] = tagProps;
151 boolean inlineTag = (tagProps & IS_INLINE) != 0;
152 if (!inlineTag && !inFormattedTag && !afterInline && /*!afterFormatted &&*/ withinSuppressed == 0 && level != 0) {
153 indent();
154 }
155
156 nextReceiver.startElement(nameCode, typeCode, location, properties);
157
158 inFormattedTag = inFormattedTag || ((tagProps & IS_FORMATTED) != 0);
159 level++;
160 sameLine = true;
161 afterInline = false;
162 //afterFormatted = false;
163 afterEndElement = false;
164 }
165
166 /**
167 * Output element end tag
168 */
169
170 public void endElement() throws XPathException {
171 level--;
172 boolean thisInline = (propertyStack[level] & IS_INLINE) != 0;
173 boolean thisFormatted = (propertyStack[level] & IS_FORMATTED) != 0;
174 boolean thisSuppressed = (propertyStack[level] & IS_SUPPRESSED) != 0;
175 if (afterEndElement && !thisInline && !thisSuppressed && !afterInline &&
176 !sameLine && !inFormattedTag) {
177 indent();
178 afterInline = false;
179 //afterFormatted = false;
180 } else {
181 afterInline = thisInline;
182 //afterFormatted = thisFormatted;
183 }
184 nextReceiver.endElement();
185 inFormattedTag = inFormattedTag && !thisFormatted;
186 sameLine = false;
187 afterEndElement = true;
188 }
189
190 /**
191 * Output character data
192 */
193
194 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
195 if (inFormattedTag ||
196 (properties & ReceiverOptions.USE_NULL_MARKERS) != 0 ||
197 (properties & ReceiverOptions.DISABLE_ESCAPING) != 0) {
198 // don't split the text if in a tag such as <pre>, or if the text contains the result of
199 // expanding a character map or was produced using disable-output-escaping
200 nextReceiver.characters(chars, locationId, properties);
201 } else {
202 // otherwise try to split long lines into multiple lines
203 int lastNL = 0;
204 for (int i = 0; i < chars.length(); i++) {
205 if (chars.charAt(i) == '\n' || (i - lastNL > getLineLength() && chars.charAt(i) == ' ')) {
206 sameLine = false;
207 nextReceiver.characters(chars.subSequence(lastNL, i), locationId, properties);
208 indent();
209 lastNL = i + 1;
210 while (lastNL < chars.length() && chars.charAt(lastNL) == ' ') {
211 lastNL++;
212 }
213 }
214 }
215 if (lastNL < chars.length()) {
216 nextReceiver.characters(chars.subSequence(lastNL, chars.length()), locationId, properties);
217 }
218 }
219 afterInline = false;
220 afterEndElement = false;
221 }
222
223 /**
224 * Output a processing instruction
225 */
226
227 @Override
228 public void processingInstruction(String target, CharSequence data, Location locationId, int properties) throws XPathException {
229 boolean thisInline = (propertyStack[level] & IS_INLINE) != 0;
230 if (afterEndElement && !thisInline) {
231 indent();
232 }
233 nextReceiver.processingInstruction(target, data, locationId, properties);
234 afterEndElement = false;
235 }
236
237 /**
238 * Output a comment
239 */
240
241 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
242 boolean thisInline = (propertyStack[level] & IS_INLINE) != 0;
243 if (afterEndElement && !thisInline) {
244 indent();
245 }
246 nextReceiver.comment(chars, locationId, properties);
247 afterEndElement = false;
248 }
249
250 /**
251 * Get the maximum length of lines, after which long lines will be word-wrapped
252 *
253 * @return the maximum line length
254 */
255
256 protected int getLineLength() {
257 return 80;
258 }
259
260 /**
261 * Output white space to reflect the current indentation level
262 *
263 * @throws net.sf.saxon.trans.XPathException if an error occurs downstream in the pipeline
264 */
265
266 private void indent() throws XPathException {
267 int spaces = level * getIndentation();
268 if (spaces + 1 >= indentChars.length) {
269 int increment = 5 * getIndentation();
270 if (spaces + 1 > indentChars.length + increment) {
271 increment += spaces + 1;
272 }
273 char[] c2 = new char[indentChars.length + increment];
274 System.arraycopy(indentChars, 0, c2, 0, indentChars.length);
275 Arrays.fill(c2, indentChars.length, c2.length, ' ');
276 indentChars = c2;
277 }
278 nextReceiver.characters(new CharSlice(indentChars, 0, spaces + 1), ExplicitLocation.UNKNOWN_LOCATION, 0);
279 sameLine = false;
280 }
281
282 /**
283 * Get the number of spaces to be used for indentation
284 *
285 * @return the number of spaces to be added to the indentation for each level
286 */
287
288 protected int getIndentation() {
289 return 3;
290 }
291
292 }
293