Debian Codegraph @

net/sf/saxon/serialize/XMLIndenter.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.Event;
11 import net.sf.saxon.event.ProxyReceiver;
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.NamespaceConstant;
16 import net.sf.saxon.lib.SaxonOutputKeys;
17 import net.sf.saxon.om.FingerprintedQName;
18 import net.sf.saxon.om.NamespaceBinding;
19 import net.sf.saxon.om.NamespaceBindingSet;
20 import net.sf.saxon.om.NodeName;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.tree.tiny.CharSlice;
23 import net.sf.saxon.tree.util.AttributeCollectionImpl;
24 import net.sf.saxon.type.*;
25 import net.sf.saxon.value.Whitespace;
26
27 import javax.xml.transform.OutputKeys;
28 import java.util.*;
29
30 /**
31 * XMLIndenter: This ProxyReceiver indents elements, by adding character data where appropriate.
32 * The character data is always added as "ignorable white space", that is, it is never added
33 * adjacent to existing character data.
34 *
35 * @author Michael Kay
36 */
37
38
39 public class XMLIndenter extends ProxyReceiver {
40
41 private int level = 0;
42
43 protected char[] indentChars = {'\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
44 private boolean sameline = false;
45 private boolean afterStartTag = false;
46 private boolean afterEndTag = true;
47 private Event.Text pendingWhitespace = null;
48 private int line = 0; // line and column measure the number of lines and columns
49 private int column = 0; // .. in whitespace text nodes between tags
50 private int suppressedAtLevel = -1;
51 private Set<NodeName> suppressedElements = null;
52 private XMLEmitter emitter;
53 private AttributeCollectionImpl bufferedAttributes;
54 private List<NamespaceBindingSet> bufferedNamespaces = new ArrayList<NamespaceBindingSet>(8);
55
56
57 /**
58 * Create an XML Indenter
59 *
60 * @param next the next receiver in the pipeline, always an XMLEmitter
61 */
62
63 public XMLIndenter(XMLEmitter next) {
64 super(next);
65 emitter = next;
66 bufferedAttributes = new AttributeCollectionImpl(getConfiguration());
67 }
68
69 /**
70 * Set the properties for this indenter
71 *
72 * @param props the serialization properties
73 */
74
75 public void setOutputProperties(Properties props) {
76
77 String omit = props.getProperty(OutputKeys.OMIT_XML_DECLARATION);
78 afterEndTag = omit == null || !"yes".equals(Whitespace.trim(omit)) ||
79 props.getProperty(OutputKeys.DOCTYPE_SYSTEM) != null;
80 String s = props.getProperty(SaxonOutputKeys.SUPPRESS_INDENTATION);
81 if (s == null) {
82 s = props.getProperty("{http://saxon.sf.net/}suppress-indentation");
83 // for compatibility: since 9.3 also available in default namespace
84 }
85 if (s != null) {
86 suppressedElements = new HashSet<NodeName>(8);
87 StringTokenizer st = new StringTokenizer(s, " \t\r\n");
88 while (st.hasMoreTokens()) {
89 String clarkName = st.nextToken();
90 suppressedElements.add(FingerprintedQName.fromClarkName(clarkName));
91 }
92 }
93
94 }
95
96 /**
97 * Start of document
98 */
99
100 public void open() throws XPathException {
101 nextReceiver.open();
102 }
103
104 /**
105 * Output element start tag
106 */
107
108 public void startElement(NodeName nameCode, SchemaType type, Location location, int properties) throws XPathException {
109 if (afterStartTag || afterEndTag) {
110 if (isDoubleSpaced(nameCode)) {
111 nextReceiver.characters("\n", location, 0);
112 line = 0;
113 column = 0;
114 }
115 indent();
116 } else {
117 flushPendingWhitespace();
118 }
119 nextReceiver.startElement(nameCode, type, location, properties);
120 level++;
121 sameline = true;
122 afterStartTag = true;
123 afterEndTag = false;
124 line = 0;
125 if (suppressedElements != null && suppressedAtLevel == -1 && suppressedElements.contains(nameCode)) {
126 suppressedAtLevel = level;
127 }
128 if (type != AnyType.getInstance() && type != Untyped.getInstance() && suppressedAtLevel < 0
129 && type.isComplexType() && ((ComplexType) type).isMixedContent()) {
130 // suppress indentation for elements with mixed content. (Note this also suppresses
131 // indentation for all descendants of such elements. We could be smarter than this.)
132 suppressedAtLevel = level;
133 }
134 bufferedAttributes.clear();
135 bufferedNamespaces.clear();
136 }
137
138 @Override
139 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
140 bufferedNamespaces.add(namespaceBindings);
141 }
142
143 /**
144 * Output an attribute
145 */
146
147 public void attribute(NodeName attName, SimpleType typeCode, CharSequence value, Location locationId, int properties)
148 throws XPathException {
149 if (value.equals("preserve") &&
150 attName.hasURI(NamespaceConstant.XML) &&
151 attName.getLocalPart().equals("space") &&
152 suppressedAtLevel < 0) {
153 // Note, we are suppressing indentation within an xml:space="preserve" region even if a descendant
154 // specifies xml:space="default"
155 suppressedAtLevel = level;
156 }
157 bufferedAttributes.addAttribute(attName, typeCode, value.toString(), locationId, properties);
158 //nextReceiver.attribute(nameCode, typeCode, value, locationId, properties);
159 }
160
161 public void startContent() throws XPathException {
162 int len = 0;
163 int count = 0;
164 int indent = -1;
165 AttributeCollectionImpl ba = bufferedAttributes;
166 if (suppressedAtLevel < 0) {
167 for (NamespaceBindingSet nbs : bufferedNamespaces) {
168 for (NamespaceBinding binding : nbs) {
169 String prefix = binding.getPrefix();
170 if (prefix.isEmpty()) {
171 len += 9 + binding.getURI().length();
172 } else {
173 len += prefix.length() + 10 + binding.getURI().length();
174 }
175 }
176 }
177 for (int i = 0; i < ba.getLength(); i++) {
178 String prefix = ba.getPrefix(i);
179 len += ba.getLocalName(i).length()
180 + ba.getValue(i).length()
181 + 4 + (prefix.isEmpty() ? 4 : prefix.length() + 5);
182 }
183 if (len > getLineLength()) {
184 indent = (level - 1) * getIndentation() + emitter.elementStack.peek().length() + 3;
185 }
186 }
187 for (NamespaceBindingSet nbs : bufferedNamespaces) {
188 for (NamespaceBinding binding : nbs) {
189 nextReceiver.namespace(binding, 0);
190 if (indent > 0 && count++ == 0) {
191 emitter.setIndentForNextAttribute(indent);
192 }
193 }
194 }
195 for (int i = 0; i < ba.getLength(); i++) {
196 nextReceiver.attribute(ba.getNodeName(i), ba.getTypeAnnotation(i),
197 ba.getValue(i), ba.getLocation(i), ba.getProperties(i));
198 if (indent > 0 && count++ == 0) {
199 emitter.setIndentForNextAttribute(indent);
200 }
201 }
202 nextReceiver.startContent();
203
204 }
205
206 /**
207 * Output element end tag
208 */
209
210 public void endElement() throws XPathException {
211 level--;
212 if (afterEndTag && !sameline) {
213 indent();
214 } else {
215 flushPendingWhitespace();
216 }
217 nextReceiver.endElement();
218 sameline = false;
219 afterEndTag = true;
220 afterStartTag = false;
221 line = 0;
222 if (level == (suppressedAtLevel - 1)) {
223 suppressedAtLevel = -1;
224 // remove the suppression of indentation
225 }
226 }
227
228 /**
229 * Output a processing instruction
230 */
231
232 public void processingInstruction(String target, CharSequence data, Location locationId, int properties) throws XPathException {
233 if (afterEndTag) {
234 indent();
235 } else {
236 flushPendingWhitespace();
237 }
238 nextReceiver.processingInstruction(target, data, locationId, properties);
239 //afterStartTag = false;
240 //afterEndTag = false;
241 }
242
243 /**
244 * Output character data
245 */
246
247 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
248 if (suppressedAtLevel < 0 && Whitespace.isWhite(chars)) {
249 pendingWhitespace = new Event.Text(chars, locationId, properties);
250 } else {
251 flushPendingWhitespace();
252 for (int i = 0; i < chars.length(); i++) {
253 char c = chars.charAt(i);
254 if (c == '\n') {
255 sameline = false;
256 line++;
257 column = 0;
258 }
259 column++;
260 }
261 nextReceiver.characters(chars, locationId, properties);
262 afterStartTag = false;
263 afterEndTag = false;
264 }
265 }
266
267 /**
268 * Output a comment
269 */
270
271 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
272 if (afterEndTag) {
273 indent();
274 } else {
275 flushPendingWhitespace();
276 }
277 nextReceiver.comment(chars, locationId, properties);
278 //afterStartTag = false;
279 //afterEndTag = false;
280 }
281
282 /**
283 * Ask whether this Receiver (or the downstream pipeline) makes any use of the type annotations
284 * supplied on element and attribute events
285 *
286 * @return true if the Receiver makes any use of this information. If false, the caller
287 * may supply untyped nodes instead of supplying the type annotation
288 */
289
290 public boolean usesTypeAnnotations() {
291 return true;
292 }
293
294 /**
295 * Output white space to reflect the current indentation level
296 *
297 * @throws XPathException if a downstream error occurs doing the output
298 */
299
300 private void indent() throws XPathException {
301 if (suppressedAtLevel >= 0) {
302 // indentation has been suppressed (e.g. by xmlspace="preserve")
303 flushPendingWhitespace();
304 return;
305 }
306 pendingWhitespace = null; // if we're adding new whitespace, we're allowed to discard existing whitespace
307 int spaces = level * getIndentation();
308 if (line > 0) {
309 spaces -= column;
310 if (spaces <= 0) {
311 return; // there's already enough white space, don't add more
312 }
313 }
314 if (spaces + 2 >= indentChars.length) {
315 int increment = 5 * getIndentation();
316 if (spaces + 2 > indentChars.length + increment) {
317 increment += spaces + 2;
318 }
319 char[] c2 = new char[indentChars.length + increment];
320 System.arraycopy(indentChars, 0, c2, 0, indentChars.length);
321 Arrays.fill(c2, indentChars.length, c2.length, ' ');
322 indentChars = c2;
323 }
324 // output the initial newline character only if line==0
325 int start = line == 0 ? 0 : 1;
326 //super.characters(indentChars.subSequence(start, start+spaces+1), 0, ReceiverOptions.NO_SPECIAL_CHARS);
327 nextReceiver.characters(new CharSlice(indentChars, start, spaces + 1), ExplicitLocation.UNKNOWN_LOCATION, ReceiverOptions.NO_SPECIAL_CHARS);
328 sameline = false;
329 }
330
331 private void flushPendingWhitespace() throws XPathException {
332 if (pendingWhitespace != null) {
333 pendingWhitespace.replay(nextReceiver);
334 pendingWhitespace = null;
335 }
336 }
337
338 @Override
339 public void endDocument() throws XPathException {
340 if (afterEndTag) {
341 nextReceiver.characters("\n", ExplicitLocation.UNKNOWN_LOCATION, 0); // if permitted, output a trailing newline, for tidier console output
342 }
343 super.endDocument();
344 }
345
346 /**
347 * Get the number of spaces to be used for indentation
348 *
349 * @return the number of spaces to be added to the indentation for each level
350 */
351
352 protected int getIndentation() {
353 return 3;
354 }
355
356 /**
357 * Ask whether a particular element is to be double-spaced
358 *
359 * @param name the element name
360 * @return true if double-spacing is in effect for this element
361 */
362
363 protected boolean isDoubleSpaced(NodeName name) {
364 return false;
365 }
366
367 /**
368 * Get the suggested maximum length of a line
369 *
370 * @return the suggested maximum line length (used for wrapping attributes)
371 */
372
373 protected int getLineLength() {
374 return 80;
375 }
376 }
377