View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html.serializer;
16  
17  import static org.htmlunit.css.CssStyleSheet.BLOCK;
18  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
19  
20  import java.util.IdentityHashMap;
21  import java.util.Iterator;
22  import java.util.List;
23  import java.util.Map;
24  
25  import org.htmlunit.Page;
26  import org.htmlunit.SgmlPage;
27  import org.htmlunit.WebWindow;
28  import org.htmlunit.html.DomComment;
29  import org.htmlunit.html.DomElement;
30  import org.htmlunit.html.DomNode;
31  import org.htmlunit.html.DomText;
32  import org.htmlunit.html.HtmlBody;
33  import org.htmlunit.html.HtmlBreak;
34  import org.htmlunit.html.HtmlCheckBoxInput;
35  import org.htmlunit.html.HtmlDetails;
36  import org.htmlunit.html.HtmlElement;
37  import org.htmlunit.html.HtmlElement.DisplayStyle;
38  import org.htmlunit.html.HtmlHiddenInput;
39  import org.htmlunit.html.HtmlInlineFrame;
40  import org.htmlunit.html.HtmlInput;
41  import org.htmlunit.html.HtmlListItem;
42  import org.htmlunit.html.HtmlNoFrames;
43  import org.htmlunit.html.HtmlNoScript;
44  import org.htmlunit.html.HtmlNumberInput;
45  import org.htmlunit.html.HtmlOption;
46  import org.htmlunit.html.HtmlOrderedList;
47  import org.htmlunit.html.HtmlPreformattedText;
48  import org.htmlunit.html.HtmlRadioButtonInput;
49  import org.htmlunit.html.HtmlResetInput;
50  import org.htmlunit.html.HtmlScript;
51  import org.htmlunit.html.HtmlSelect;
52  import org.htmlunit.html.HtmlStyle;
53  import org.htmlunit.html.HtmlSubmitInput;
54  import org.htmlunit.html.HtmlSummary;
55  import org.htmlunit.html.HtmlTable;
56  import org.htmlunit.html.HtmlTableCell;
57  import org.htmlunit.html.HtmlTableFooter;
58  import org.htmlunit.html.HtmlTableHeader;
59  import org.htmlunit.html.HtmlTableRow;
60  import org.htmlunit.html.HtmlTextArea;
61  import org.htmlunit.html.HtmlTitle;
62  import org.htmlunit.html.HtmlUnorderedList;
63  import org.htmlunit.html.TableRowGroup;
64  import org.htmlunit.html.serializer.HtmlSerializerNormalizedText.HtmlSerializerTextBuilder.Mode;
65  
66  /**
67   * Utility to handle conversion from HTML code to string.
68   * This implements HtmlUnit's way of normalization.
69   * <p>Note: The conversion done by selenium WebElement#getText()
70   * is different (see {@link HtmlSerializerVisibleText}).</p>
71   *
72   * @author Marc Guillemot
73   * @author Ahmed Ashour
74   * @author Ronald Brill
75   * @author Rob Kodey
76   */
77  public class HtmlSerializerNormalizedText {
78  
79      private boolean ignoreMaskedElements_ = true;
80  
81      /**
82       * Cache of the visibility of the nodes processed by the current run;
83       * the dom is not changed while serializing.
84       */
85      private final Map<DomNode, Boolean> visibilityCache_ = new IdentityHashMap<>();
86  
87      /**
88       * Converts an HTML node to text.
89       * @param node a node
90       * @return the text representation according to the setting of this serializer
91       */
92      public String asText(final DomNode node) {
93          visibilityCache_.clear();
94          final HtmlSerializerTextBuilder builder = new HtmlSerializerTextBuilder();
95          appendNode(builder, node);
96          return builder.getText();
97      }
98  
99      /**
100      * Iterates over all children and calls appendNode() for every child.
101      *
102      * @param builder the StringBuilder to add to
103      * @param node the node to process
104      */
105     protected void appendChildren(final HtmlSerializerTextBuilder builder, final DomNode node) {
106         for (final DomNode child : node.getChildren()) {
107             appendNode(builder, child);
108         }
109     }
110 
111     /**
112      * The core distribution method; calls the different appendXXX
113      * methods depending on the type of the given node.
114      *
115      * @param builder the StringBuilder to add to
116      * @param node the node to process
117      */
118     protected void appendNode(final HtmlSerializerTextBuilder builder, final DomNode node) {
119         if (node instanceof DomText text1) {
120             appendText(builder, text1);
121         }
122         else if (node instanceof DomComment) {
123             // nothing to do
124         }
125         else if (node instanceof HtmlBreak break1) {
126             appendBreak(builder, break1);
127         }
128         else if (node instanceof HtmlHiddenInput) {
129             // nothing to do
130         }
131         else if (node instanceof HtmlScript) {
132             // nothing to do
133         }
134         else if (node instanceof HtmlStyle) {
135             // nothing to do
136         }
137         else if (node instanceof HtmlNoFrames) {
138             // nothing to do
139         }
140         else if (node instanceof HtmlTextArea area) {
141             appendTextArea(builder, area);
142         }
143         else if (node instanceof HtmlTitle title) {
144             appendTitle(builder, title);
145         }
146         else if (node instanceof HtmlTableRow row) {
147             appendTableRow(builder, row);
148         }
149         else if (node instanceof HtmlSelect select) {
150             appendSelect(builder, select);
151         }
152         else if (node instanceof HtmlSubmitInput input5) {
153             appendSubmitInput(builder, input5);
154         }
155         else if (node instanceof HtmlResetInput input4) {
156             appendResetInput(builder, input4);
157         }
158         else if (node instanceof HtmlCheckBoxInput input3) {
159             appendCheckBoxInput(builder, input3);
160         }
161         else if (node instanceof HtmlRadioButtonInput input2) {
162             appendRadioButtonInput(builder, input2);
163         }
164         else if (node instanceof HtmlNumberInput input1) {
165             appendNumberInput(builder, input1);
166         }
167         else if (node instanceof HtmlInput input) {
168             appendInput(builder, input);
169         }
170         else if (node instanceof HtmlTable table) {
171             appendTable(builder, table);
172         }
173         else if (node instanceof HtmlOrderedList list1) {
174             appendOrderedList(builder, list1);
175         }
176         else if (node instanceof HtmlUnorderedList list) {
177             appendUnorderedList(builder, list);
178         }
179         else if (node instanceof HtmlPreformattedText text) {
180             appendPreformattedText(builder, text);
181         }
182         else if (node instanceof HtmlInlineFrame frame) {
183             appendInlineFrame(builder, frame);
184         }
185         else if (node instanceof HtmlDetails details) {
186             appendDetails(builder, details);
187         }
188         else if (node instanceof HtmlNoScript && node.getPage().getWebClient().isJavaScriptEnabled()) {
189             // nothing to do
190         }
191         else {
192             appendDomNode(builder, node);
193         }
194     }
195 
196     /**
197      * Process all other {@link DomNode}s; block elements are surrounded by a block separator.
198      *
199      * @param builder the StringBuilder to add to
200      * @param domNode the target to process
201      */
202     protected void appendDomNode(final HtmlSerializerTextBuilder builder, final DomNode domNode) {
203         boolean block = false;
204         if (!(domNode instanceof HtmlBody)) {
205             final SgmlPage page = domNode.getPage();
206             final WebWindow window = page.getEnclosingWindow();
207             if (window.getWebClient().getOptions().isCssEnabled()) {
208                 if (domNode instanceof DomElement element) {
209                     final String display = window.getComputedStyle(element, null).getDisplay();
210                     block = BLOCK.equals(display);
211                 }
212             }
213             else if (domNode instanceof HtmlElement element) {
214                 block = DisplayStyle.BLOCK == element.getDefaultStyleDisplay();
215             }
216         }
217 
218         if (block) {
219             builder.appendBlockSeparator();
220         }
221         appendChildren(builder, domNode);
222         if (block) {
223             builder.appendBlockSeparator();
224         }
225     }
226 
227     /**
228      * Process {@link HtmlSubmitInput}.
229      *
230      * @param builder the StringBuilder to add to
231      * @param htmlSubmitInput the target to process
232      */
233     protected void appendSubmitInput(final HtmlSerializerTextBuilder builder, final HtmlSubmitInput htmlSubmitInput) {
234         String text = htmlSubmitInput.getValueAttribute();
235         if (ATTRIBUTE_NOT_DEFINED == text) {
236             text = HtmlSubmitInput.DEFAULT_VALUE;
237         }
238 
239         builder.append(text, Mode.NORMALIZE);
240     }
241 
242     /**
243      * Process {@link HtmlInput}.
244      *
245      * @param builder the StringBuilder to add to
246      * @param htmlInput the target to process
247      */
248     protected void appendInput(final HtmlSerializerTextBuilder builder, final HtmlInput htmlInput) {
249         builder.append(" ", Mode.NORMALIZE);
250         builder.append(htmlInput.getRawValue(), Mode.NORMALIZE);
251         builder.append(" ", Mode.NORMALIZE);
252     }
253 
254     /**
255      * Process {@link HtmlNumberInput}.
256      *
257      * @param builder the StringBuilder to add to
258      * @param htmlNumberInput the target to process
259      */
260     protected void appendNumberInput(final HtmlSerializerTextBuilder builder, final HtmlNumberInput htmlNumberInput) {
261         builder.append(" ", Mode.NORMALIZE);
262 
263         String val = htmlNumberInput.getRawValue();
264         final int lastPos = val.length() - 1;
265         if (lastPos >= 0 && val.charAt(lastPos) == '.') {
266             val = val.substring(0, lastPos);
267         }
268         builder.append(val, Mode.NORMALIZE);
269 
270         builder.append(" ", Mode.NORMALIZE);
271     }
272 
273     /**
274      * Process {@link HtmlResetInput}.
275      *
276      * @param builder the StringBuilder to add to
277      * @param htmlResetInput the target to process
278      */
279     protected void appendResetInput(final HtmlSerializerTextBuilder builder, final HtmlResetInput htmlResetInput) {
280         String text = htmlResetInput.getValueAttribute();
281         if (ATTRIBUTE_NOT_DEFINED == text) {
282             text = HtmlResetInput.DEFAULT_VALUE;
283         }
284 
285         builder.append(text, Mode.NORMALIZE);
286     }
287 
288     /**
289      * Process {@link HtmlUnorderedList}.
290      *
291      * @param builder the StringBuilder to add to
292      * @param htmlUnorderedList the target to process
293      */
294     protected void appendUnorderedList(final HtmlSerializerTextBuilder builder,
295                                           final HtmlUnorderedList htmlUnorderedList) {
296         builder.appendBlockSeparator();
297         boolean first = true;
298         for (final DomNode item : htmlUnorderedList.getChildren()) {
299             if (!first) {
300                 builder.appendBlockSeparator();
301             }
302             first = false;
303             appendNode(builder, item);
304         }
305         builder.appendBlockSeparator();
306     }
307 
308     /**
309      * Process {@link HtmlDetails}.
310      *
311      * @param builder the StringBuilder to add to
312      * @param htmlDetails the target to process
313      */
314     protected void appendDetails(final HtmlSerializerTextBuilder builder,
315                     final HtmlDetails htmlDetails) {
316         if (htmlDetails.isOpen()) {
317             appendChildren(builder, htmlDetails);
318             return;
319         }
320 
321         for (final DomNode child : htmlDetails.getChildren()) {
322             if (child instanceof HtmlSummary) {
323                 // only the first summary is the summary of the details
324                 // but for the moment i like to have it like this for backward compatibility
325                 appendNode(builder, child);
326             }
327         }
328     }
329 
330     /**
331      * Process {@link HtmlTitle}.
332      *
333      * @param builder the StringBuilder to add to
334      * @param htmlTitle the target to process
335      */
336     protected void appendTitle(final HtmlSerializerTextBuilder builder, final HtmlTitle htmlTitle) {
337         // optimized version
338         // for the title there is no need to check the visibility
339         // of the containing dom text;
340         // this optimization defers the load of the style sheets
341         final DomNode child = htmlTitle.getFirstChild();
342         if (child instanceof DomText text) {
343             builder.append(text.getData(), Mode.NORMALIZE);
344             builder.appendBlockSeparator();
345         }
346     }
347 
348     /**
349      * Process {@link HtmlTableRow}.
350      *
351      * @param builder the StringBuilder to add to
352      * @param htmlTableRow the target to process
353      */
354     protected void appendTableRow(final HtmlSerializerTextBuilder builder, final HtmlTableRow htmlTableRow) {
355         boolean first = true;
356         for (final HtmlTableCell cell : htmlTableRow.getCells()) {
357             if (first) {
358                 first = false;
359             }
360             else {
361                 builder.appendTab();
362             }
363             appendChildren(builder, cell);
364         }
365     }
366 
367     /**
368      * Process {@link HtmlTextArea}.
369      *
370      * @param builder the StringBuilder to add to
371      * @param htmlTextArea the target to process
372      */
373     protected void appendTextArea(final HtmlSerializerTextBuilder builder, final HtmlTextArea htmlTextArea) {
374         if (isVisible(htmlTextArea)) {
375             builder.append(htmlTextArea.getText(), Mode.PRESERVE_BLANK_NEWLINE);
376         }
377     }
378 
379     /**
380      * Process {@link HtmlTable}.
381      *
382      * @param builder the StringBuilder to add to
383      * @param htmlTable the target to process
384      */
385     protected void appendTable(final HtmlSerializerTextBuilder builder, final HtmlTable htmlTable) {
386         builder.appendBlockSeparator();
387         final String caption = htmlTable.getCaptionText();
388         if (caption != null) {
389             builder.append(caption, Mode.NORMALIZE);
390             builder.appendBlockSeparator();
391         }
392 
393         boolean first = true;
394 
395         // first thead has to be displayed first and first tfoot has to be displayed last
396         final HtmlTableHeader tableHeader = htmlTable.getHeader();
397         if (tableHeader != null) {
398             first = appendTableRows(builder, tableHeader.getRows(), true, null, null);
399         }
400         final HtmlTableFooter tableFooter = htmlTable.getFooter();
401 
402         final List<HtmlTableRow> tableRows = htmlTable.getRows();
403         first = appendTableRows(builder, tableRows, first, tableHeader, tableFooter);
404 
405         if (tableFooter != null) {
406             first = appendTableRows(builder, tableFooter.getRows(), first, null, null);
407         }
408         else if (tableRows.isEmpty()) {
409             final DomNode firstChild = htmlTable.getFirstChild();
410             if (firstChild != null) {
411                 appendNode(builder, firstChild);
412             }
413         }
414 
415         builder.appendBlockSeparator();
416     }
417 
418     /**
419      * Process the given {@link HtmlTableRow}s; rows are separated by a block separator.
420      *
421      * @param builder the StringBuilder to add to
422      * @param rows the rows
423      * @param first if true this is the first one
424      * @param skipParent1 skip row if the parent is this
425      * @param skipParent2 skip row if the parent is this
426      * @return true if no row was written so far (the new value of first)
427      */
428     protected boolean appendTableRows(final HtmlSerializerTextBuilder builder,
429             final List<HtmlTableRow> rows, final boolean first, final TableRowGroup skipParent1,
430             final TableRowGroup skipParent2) {
431         boolean isFirst = first;
432         for (final HtmlTableRow row : rows) {
433             if (row.getParentNode() == skipParent1 || row.getParentNode() == skipParent2) {
434                 continue;
435             }
436             if (!isFirst) {
437                 builder.appendBlockSeparator();
438             }
439             isFirst = false;
440             appendTableRow(builder, row);
441         }
442         return isFirst;
443     }
444 
445     /**
446      * Process {@link HtmlSelect}.
447      *
448      * @param builder the StringBuilder to add to
449      * @param htmlSelect the target to process
450      */
451     protected void appendSelect(final HtmlSerializerTextBuilder builder, final HtmlSelect htmlSelect) {
452         final List<HtmlOption> options = htmlSelect.getSelectedOptions();
453 
454         for (final Iterator<HtmlOption> i = options.iterator(); i.hasNext();) {
455             final HtmlOption currentOption = i.next();
456             appendChildren(builder, currentOption);
457             if (i.hasNext()) {
458                 builder.appendBlockSeparator();
459             }
460         }
461     }
462 
463     /**
464      * Process {@link HtmlOrderedList} taking care to numerate it.
465      *
466      * @param builder the StringBuilder to add to
467      * @param htmlOrderedList the OL element
468      */
469     protected void appendOrderedList(final HtmlSerializerTextBuilder builder, final HtmlOrderedList htmlOrderedList) {
470         builder.appendBlockSeparator();
471         boolean first = true;
472         int i = 1;
473 
474         final String start = htmlOrderedList.getStartAttribute();
475         if (ATTRIBUTE_NOT_DEFINED != start) {
476             try {
477                 i = (int) Math.round(Double.parseDouble(start));
478             }
479             catch (final Exception e) {
480                 // ignore start with 1
481             }
482         }
483 
484         for (final DomNode item : htmlOrderedList.getChildren()) {
485             if (!first) {
486                 builder.appendBlockSeparator();
487             }
488             first = false;
489             if (item instanceof HtmlListItem) {
490                 builder.append(Integer.toString(i++), Mode.NORMALIZE);
491                 builder.append(". ", Mode.NORMALIZE);
492                 appendChildren(builder, item);
493             }
494             else {
495                 appendNode(builder, item);
496             }
497         }
498         builder.appendBlockSeparator();
499     }
500 
501     /**
502      * Process {@link HtmlPreformattedText}.
503      *
504      * @param builder the StringBuilder to add to
505      * @param htmlPreformattedText the target to process
506      */
507     protected void appendPreformattedText(final HtmlSerializerTextBuilder builder,
508             final HtmlPreformattedText htmlPreformattedText) {
509         if (isVisible(htmlPreformattedText)) {
510             builder.appendBlockSeparator();
511             builder.append(htmlPreformattedText.getTextContent(), Mode.PRESERVE_BLANK_TAB_NEWLINE);
512             builder.appendBlockSeparator();
513         }
514     }
515 
516     /**
517      * Process {@link HtmlInlineFrame}.
518      *
519      * @param builder the StringBuilder to add to
520      * @param htmlInlineFrame the target to process
521      */
522     protected void appendInlineFrame(final HtmlSerializerTextBuilder builder,
523             final HtmlInlineFrame htmlInlineFrame) {
524         if (isVisible(htmlInlineFrame)) {
525             builder.appendBlockSeparator();
526             final Page page = htmlInlineFrame.getEnclosedPage();
527             if (page instanceof SgmlPage sgmlPage) {
528                 builder.append(sgmlPage.asNormalizedText(), Mode.NORMALIZE);
529             }
530             builder.appendBlockSeparator();
531         }
532     }
533 
534     /**
535      * Process {@link DomText}.
536      *
537      * @param builder the StringBuilder to add to
538      * @param domText the target to process
539      */
540     protected void appendText(final HtmlSerializerTextBuilder builder, final DomText domText) {
541         final DomNode parent = domText.getParentNode();
542         if (parent == null || parent instanceof HtmlTitle || isVisible(parent)) {
543             builder.append(domText.getData(), Mode.NORMALIZE);
544         }
545     }
546 
547     /**
548      * Process {@link HtmlBreak}.
549      *
550      * @param builder the StringBuilder to add to
551      * @param htmlBreak the target to process
552      */
553     protected void appendBreak(final HtmlSerializerTextBuilder builder, final HtmlBreak htmlBreak) {
554         builder.appendNewLine();
555     }
556 
557     /**
558      * Process {@link HtmlCheckBoxInput}.
559      *
560      * @param builder the StringBuilder to add to
561      * @param htmlCheckBoxInput the target to process
562      */
563     protected void appendCheckBoxInput(final HtmlSerializerTextBuilder builder,
564                                             final HtmlCheckBoxInput htmlCheckBoxInput) {
565         appendCheckedState(builder, htmlCheckBoxInput.isChecked());
566     }
567 
568     /**
569      * Process {@link HtmlRadioButtonInput}.
570      *
571      * @param builder the StringBuilder to add to
572      * @param htmlRadioButtonInput the target to process
573      */
574     protected void appendRadioButtonInput(final HtmlSerializerTextBuilder builder,
575             final HtmlRadioButtonInput htmlRadioButtonInput) {
576         appendCheckedState(builder, htmlRadioButtonInput.isChecked());
577     }
578 
579     /**
580      * Appends the state of a checkbox or radio button.
581      *
582      * @param builder the StringBuilder to add to
583      * @param checked the checked state
584      */
585     private static void appendCheckedState(final HtmlSerializerTextBuilder builder, final boolean checked) {
586         builder.append(checked ? "checked " : "unchecked ", Mode.NORMALIZE);
587     }
588 
589     /**
590      * Checks if the given node is visible; if masked elements are not ignored
591      * every node is visible. The result is cached for the current run because
592      * {@link DomNode#isDisplayed()} has to check all the ancestors and
593      * this is done for every text node.
594      *
595      * @param node the node to check
596      * @return true if the node is visible
597      */
598     private boolean isVisible(final DomNode node) {
599         if (!ignoreMaskedElements_) {
600             return true;
601         }
602         return visibilityCache_.computeIfAbsent(node, DomNode::isDisplayed);
603     }
604 
605     /**
606      * Indicates if element that are not displayed due to style settings
607      * (visibility or display) should be visible in generated text.
608      * @param ignore indicates if masked elements should be ignored or not
609      */
610     public void setIgnoreMaskedElements(final boolean ignore) {
611         ignoreMaskedElements_ = ignore;
612     }
613 
614     /**
615      * Helper to compose the text for the serializer based on several modes.
616      */
617     protected static class HtmlSerializerTextBuilder {
618 
619         /** Mode. */
620         protected enum Mode {
621             /** Collapse whitespace. */
622             NORMALIZE,
623 
624             /** Preserve tab, blank, newline. */
625             PRESERVE_BLANK_TAB_NEWLINE,
626 
627             /** Preserve blank, newline. */
628             PRESERVE_BLANK_NEWLINE
629         }
630 
631         private enum State {
632             DEFAULT,
633             EMPTY,
634             TRIM,
635             BLANK_AT_END,
636             BLANK_AT_END_AFTER_NEWLINE,
637             NEWLINE_AT_END,
638             BLOCK_SEPARATOR_AT_END
639         }
640 
641         private static final String LINE_SEPARATOR = "\n";
642         private static final int LINE_SEPARATOR_LENGTH = LINE_SEPARATOR.length();
643 
644         private State state_;
645         private final StringBuilder builder_;
646         private int trimRightPos_;
647 
648         /**
649          * Ctor.
650          */
651         public HtmlSerializerTextBuilder() {
652             builder_ = new StringBuilder();
653             state_ = State.EMPTY;
654             trimRightPos_ = builder_.length();
655         }
656 
657         /**
658          * Append the provided content.
659          *
660          * @param content the content to add
661          * @param mode the {@link Mode}
662          */
663         public void append(final String content, final Mode mode) {
664             if (content == null) {
665                 return;
666             }
667             final int length = content.length();
668             if (length == 0) {
669                 return;
670             }
671 
672             // Mode.PRESERVE_BLANK_NEWLINE only differs in the handling of tabs;
673             // it is used for textareas
674 
675             boolean crFound = false;
676             for (int i = 0; i < length; i++) {
677                 final char c = content.charAt(i);
678 
679                 if (mode == Mode.NORMALIZE) {
680                     if (isSpace(c)) {
681                         switch (state_) {
682                             case EMPTY:
683                             case TRIM:
684                             case BLANK_AT_END:
685                             case BLANK_AT_END_AFTER_NEWLINE:
686                             case BLOCK_SEPARATOR_AT_END:
687                                 break;
688                             case NEWLINE_AT_END:
689                                 builder_.append(' ');
690                                 state_ = State.BLANK_AT_END_AFTER_NEWLINE;
691                                 break;
692                             default:
693                                 builder_.append(' ');
694                                 state_ = State.BLANK_AT_END;
695                                 break;
696                         }
697                     }
698                     else if (c == (char) 160) {
699                         builder_.append(' ');
700                         state_ = State.DEFAULT;
701                         trimRightPos_ = builder_.length();
702                     }
703                     else {
704                         builder_.append(c);
705                         state_ = State.DEFAULT;
706                         trimRightPos_ = builder_.length();
707                     }
708                     continue;
709                 }
710 
711                 // preserve mode
712                 if (c == '\n') {
713                     appendNewLine();
714                     crFound = false;
715                 }
716                 else {
717                     if (crFound) {
718                         appendNewLine();
719                     }
720                     crFound = c == '\r';
721 
722                     if (c == '\t') {
723                         if (mode == Mode.PRESERVE_BLANK_TAB_NEWLINE) {
724                             appendTab();
725                         }
726                         else if (state_ != State.BLOCK_SEPARATOR_AT_END) {
727                             builder_.append(' ');
728                         }
729                     }
730                     else if (c == (char) 160) {
731                         appendBlank();
732                     }
733                     else if (c == ' ') {
734                         appendBlank();
735                     }
736                     else {
737                         builder_.append(c);
738                     }
739                     trimRightPos_ = builder_.length();
740                 }
741             }
742 
743             if (crFound) {
744                 appendNewLine();
745             }
746 
747             if (mode != Mode.NORMALIZE) {
748                 // reset state to empty to restart whitespace normalization afterward
749                 state_ = State.TRIM;
750             }
751         }
752 
753         /**
754          * Append a block separator.
755          */
756         public void appendBlockSeparator() {
757             switch (state_) {
758                 case EMPTY:
759                     break;
760                 case BLANK_AT_END:
761                     builder_.setLength(trimRightPos_);
762                     if (builder_.length() == 0) {
763                         state_ = State.EMPTY;
764                     }
765                     else {
766                         builder_.append(LINE_SEPARATOR);
767                         state_ = State.BLOCK_SEPARATOR_AT_END;
768                     }
769                     break;
770                 case BLANK_AT_END_AFTER_NEWLINE:
771                     builder_.setLength(trimRightPos_ - LINE_SEPARATOR_LENGTH);
772                     trimRightPos_ = trimRightPos_ - LINE_SEPARATOR_LENGTH;
773                     if (builder_.length() == 0) {
774                         state_ = State.EMPTY;
775                     }
776                     else {
777                         builder_.append(LINE_SEPARATOR);
778                         state_ = State.BLOCK_SEPARATOR_AT_END;
779                     }
780                     break;
781                 case BLOCK_SEPARATOR_AT_END:
782                     break;
783                 case NEWLINE_AT_END:
784                     builder_.setLength(builder_.length() - LINE_SEPARATOR_LENGTH);
785                     trimRightPos_ = trimRightPos_ - LINE_SEPARATOR_LENGTH;
786                     if (builder_.length() == 0) {
787                         state_ = State.EMPTY;
788                     }
789                     else {
790                         builder_.append(LINE_SEPARATOR);
791                         state_ = State.BLOCK_SEPARATOR_AT_END;
792                     }
793                     break;
794                 default:
795                     builder_.append(LINE_SEPARATOR);
796                     state_ = State.BLOCK_SEPARATOR_AT_END;
797                     break;
798             }
799         }
800 
801         /**
802          * Append a line separator.
803          */
804         public void appendNewLine() {
805             builder_.append(LINE_SEPARATOR);
806             state_ = State.NEWLINE_AT_END;
807             trimRightPos_ = builder_.length();
808         }
809 
810         /**
811          * Append a tab.
812          */
813         public void appendTab() {
814             builder_.append('\t');
815             trimRightPos_ = builder_.length();
816         }
817 
818         /**
819          * Append a blank.
820          */
821         private void appendBlank() {
822             builder_.append(' ');
823             trimRightPos_ = builder_.length();
824         }
825 
826         /**
827          * Returns the constructed text.
828          *
829          * @return the constructed text.
830          */
831         public String getText() {
832             return builder_.substring(0, trimRightPos_);
833         }
834 
835         private static boolean isSpace(final char ch) {
836             return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\f' || ch == '\r';
837         }
838     }
839 }