Advertisement
mohamedsabil83

beautifier.js

Jul 2nd, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*jshint node:true */
  2. /*
  3.  
  4.   The MIT License (MIT)
  5.  
  6.   Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
  7.  
  8.   Permission is hereby granted, free of charge, to any person
  9.   obtaining a copy of this software and associated documentation files
  10.   (the "Software"), to deal in the Software without restriction,
  11.   including without limitation the rights to use, copy, modify, merge,
  12.   publish, distribute, sublicense, and/or sell copies of the Software,
  13.   and to permit persons to whom the Software is furnished to do so,
  14.   subject to the following conditions:
  15.  
  16.   The above copyright notice and this permission notice shall be
  17.   included in all copies or substantial portions of the Software.
  18.  
  19.   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20.   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21.   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22.   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  23.   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  24.   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  25.   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26.   SOFTWARE.
  27. */
  28.  
  29. 'use strict';
  30.  
  31. var Options = require('../html/options').Options;
  32. var Output = require('../core/output').Output;
  33. var Tokenizer = require('../html/tokenizer').Tokenizer;
  34. var TOKEN = require('../html/tokenizer').TOKEN;
  35.  
  36. var lineBreak = /\r\n|[\r\n]/;
  37. var allLineBreaks = /\r\n|[\r\n]/g;
  38.  
  39. var Printer = function (options, base_indent_string) { //handles input/output and some other printing functions
  40.  
  41.   this.indent_level = 0;
  42.   this.alignment_size = 0;
  43.   this.max_preserve_newlines = options.max_preserve_newlines;
  44.   this.preserve_newlines = options.preserve_newlines;
  45.  
  46.   this._output = new Output(options, base_indent_string);
  47.  
  48. };
  49.  
  50. Printer.prototype.current_line_has_match = function (pattern) {
  51.   return this._output.current_line.has_match(pattern);
  52. };
  53.  
  54. Printer.prototype.set_space_before_token = function (value, non_breaking) {
  55.   this._output.space_before_token = value;
  56.   this._output.non_breaking_space = non_breaking;
  57. };
  58.  
  59. Printer.prototype.set_wrap_point = function () {
  60.   this._output.set_indent(this.indent_level, this.alignment_size);
  61.   this._output.set_wrap_point();
  62. };
  63.  
  64.  
  65. Printer.prototype.add_raw_token = function (token) {
  66.   this._output.add_raw_token(token);
  67. };
  68.  
  69. Printer.prototype.print_preserved_newlines = function (raw_token) {
  70.   var newlines = 0;
  71.   if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) {
  72.     newlines = raw_token.newlines ? 1 : 0;
  73.   }
  74.  
  75.   if (this.preserve_newlines) {
  76.     newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1;
  77.   }
  78.   for (var n = 0; n < newlines; n++) {
  79.     this.print_newline(n > 0);
  80.   }
  81.  
  82.   return newlines !== 0;
  83. };
  84.  
  85. Printer.prototype.traverse_whitespace = function (raw_token) {
  86.   if (raw_token.whitespace_before || raw_token.newlines) {
  87.     if (!this.print_preserved_newlines(raw_token)) {
  88.       this._output.space_before_token = true;
  89.     }
  90.     return true;
  91.   }
  92.   return false;
  93. };
  94.  
  95. Printer.prototype.previous_token_wrapped = function () {
  96.   return this._output.previous_token_wrapped;
  97. };
  98.  
  99. Printer.prototype.print_newline = function (force) {
  100.   this._output.add_new_line(force);
  101. };
  102.  
  103. Printer.prototype.print_token = function (token) {
  104.   if (token.text) {
  105.     this._output.set_indent(this.indent_level, this.alignment_size);
  106.     this._output.add_token(token.text);
  107.   }
  108. };
  109.  
  110. Printer.prototype.indent = function () {
  111.   this.indent_level++;
  112. };
  113.  
  114. Printer.prototype.get_full_indent = function (level) {
  115.   level = this.indent_level + (level || 0);
  116.   if (level < 1) {
  117.     return '';
  118.   }
  119.  
  120.   return this._output.get_indent_string(level);
  121. };
  122.  
  123. var get_type_attribute = function (start_token) {
  124.   var result = null;
  125.   var raw_token = start_token.next;
  126.  
  127.   // Search attributes for a type attribute
  128.   while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) {
  129.     if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') {
  130.       if (raw_token.next && raw_token.next.type === TOKEN.EQUALS &&
  131.         raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) {
  132.         result = raw_token.next.next.text;
  133.       }
  134.       break;
  135.     }
  136.     raw_token = raw_token.next;
  137.   }
  138.  
  139.   return result;
  140. };
  141.  
  142. var get_custom_beautifier_name = function (tag_check, raw_token) {
  143.   var typeAttribute = null;
  144.   var result = null;
  145.  
  146.   if (!raw_token.closed) {
  147.     return null;
  148.   }
  149.  
  150.   if (tag_check === 'script') {
  151.     typeAttribute = 'text/javascript';
  152.   } else if (tag_check === 'style') {
  153.     typeAttribute = 'text/css';
  154.   }
  155.  
  156.   typeAttribute = get_type_attribute(raw_token) || typeAttribute;
  157.  
  158.   // For script and style tags that have a type attribute, only enable custom beautifiers for matching values
  159.   // For those without a type attribute use default;
  160.   if (typeAttribute.search('text/css') > -1) {
  161.     result = 'css';
  162.   } else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect)/) > -1) {
  163.     result = 'javascript';
  164.   } else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/) > -1) {
  165.     result = 'html';
  166.   } else if (typeAttribute.search(/test\/null/) > -1) {
  167.     // Test only mime-type for testing the beautifier when null is passed as beautifing function
  168.     result = 'null';
  169.   }
  170.  
  171.   return result;
  172. };
  173.  
  174. function in_array(what, arr) {
  175.   return arr.indexOf(what) !== -1;
  176. }
  177.  
  178. function TagFrame(parent, parser_token, indent_level) {
  179.   this.parent = parent || null;
  180.   this.tag = parser_token ? parser_token.tag_name : '';
  181.   this.indent_level = indent_level || 0;
  182.   this.parser_token = parser_token || null;
  183. }
  184.  
  185. function TagStack(printer) {
  186.   this._printer = printer;
  187.   this._current_frame = null;
  188. }
  189.  
  190. TagStack.prototype.get_parser_token = function () {
  191.   return this._current_frame ? this._current_frame.parser_token : null;
  192. };
  193.  
  194. TagStack.prototype.record_tag = function (parser_token) { //function to record a tag and its parent in this.tags Object
  195.   var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level);
  196.   this._current_frame = new_frame;
  197. };
  198.  
  199. TagStack.prototype._try_pop_frame = function (frame) { //function to retrieve the opening tag to the corresponding closer
  200.   var parser_token = null;
  201.  
  202.   if (frame) {
  203.     parser_token = frame.parser_token;
  204.     this._printer.indent_level = frame.indent_level;
  205.     this._current_frame = frame.parent;
  206.   }
  207.  
  208.   return parser_token;
  209. };
  210.  
  211. TagStack.prototype._get_frame = function (tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer
  212.   var frame = this._current_frame;
  213.  
  214.   while (frame) { //till we reach '' (the initial value);
  215.     if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it
  216.       break;
  217.     } else if (stop_list && stop_list.indexOf(frame.tag) !== -1) {
  218.       frame = null;
  219.       break;
  220.     }
  221.     frame = frame.parent;
  222.   }
  223.  
  224.   return frame;
  225. };
  226.  
  227. TagStack.prototype.try_pop = function (tag, stop_list) { //function to retrieve the opening tag to the corresponding closer
  228.   var frame = this._get_frame([tag], stop_list);
  229.   return this._try_pop_frame(frame);
  230. };
  231.  
  232. TagStack.prototype.indent_to_tag = function (tag_list) {
  233.   var frame = this._get_frame(tag_list);
  234.   if (frame) {
  235.     this._printer.indent_level = frame.indent_level;
  236.   }
  237. };
  238.  
  239. function Beautifier(source_text, options, js_beautify, css_beautify) {
  240.   //Wrapper function to invoke all the necessary constructors and deal with the output.
  241.   this._source_text = source_text || '';
  242.   options = options || {};
  243.   this._js_beautify = js_beautify;
  244.   this._css_beautify = css_beautify;
  245.   this._tag_stack = null;
  246.  
  247.   // Allow the setting of language/file-type specific options
  248.   // with inheritance of overall settings
  249.   var optionHtml = new Options(options, 'html');
  250.  
  251.   this._options = optionHtml;
  252.  
  253.   this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force';
  254.   this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline');
  255.   this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned');
  256.   this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple');
  257.   this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve';
  258.   this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned');
  259. }
  260.  
  261. Beautifier.prototype.beautify = function () {
  262.  
  263.   // if disabled, return the input unchanged.
  264.   if (this._options.disabled) {
  265.     return this._source_text;
  266.   }
  267.  
  268.   var source_text = this._source_text;
  269.  
  270.   // BEGIN
  271.   source_text = source_text.replace(/\{\{(--)?((?:(?!(--)?\}\}).)+)(--)?\}\}/g, function (m, ds, c, dh, de) {
  272.     if (c) {
  273.       c = c.replace(/(^[ \t]*|[ \t]*$)/g, '');
  274.       c = c.replace(/'/g, '&#39;');
  275.       c = c.replace(/"/g, '&#34;');
  276.       c = encodeURIComponent(c);
  277.     }
  278.     return "{{" + (ds ? ds : "") + c + (de ? de : "") + "}}";
  279.   });
  280.   source_text = source_text.replace(/^[ \t]*@([a-z]+)([^\n]*)$/gim, function (m, d, c) {
  281.     if (c) {
  282.       c = c.replace(/'/g, '&#39;');
  283.       c = c.replace(/"/g, '&#34;');
  284.       c = "|" + encodeURIComponent(c);
  285.     }
  286.     switch (d) {
  287.       case 'break':
  288.       case 'case':
  289.       case 'continue':
  290.       case 'default':
  291.       case 'empty':
  292.       case 'endsection':
  293.       case 'else':
  294.       case 'elseif':
  295.       case 'extends':
  296.       case 'csrf':
  297.       case 'include':
  298.       case 'json':
  299.       case 'method':
  300.       case 'parent':
  301.       case 'section':
  302.       case 'stack':
  303.       case 'yield':
  304.         return "<blade " + d + c + "/>";
  305.       default:
  306.         if (d.startsWith('end')) {
  307.           return "</blade " + d + c + ">";
  308.         } else {
  309.           return "<blade " + d + c + ">";
  310.         }
  311.     }
  312.   });
  313.   // END
  314.  
  315.   var eol = this._options.eol;
  316.   if (this._options.eol === 'auto') {
  317.     eol = '\n';
  318.     if (source_text && lineBreak.test(source_text)) {
  319.       eol = source_text.match(lineBreak)[0];
  320.     }
  321.   }
  322.  
  323.   // HACK: newline parsing inconsistent. This brute force normalizes the input.
  324.   source_text = source_text.replace(allLineBreaks, '\n');
  325.  
  326.   var baseIndentString = source_text.match(/^[\t ]*/)[0];
  327.  
  328.   var last_token = {
  329.     text: '',
  330.     type: ''
  331.   };
  332.  
  333.   var last_tag_token = new TagOpenParserToken();
  334.  
  335.   var printer = new Printer(this._options, baseIndentString);
  336.   var tokens = new Tokenizer(source_text, this._options).tokenize();
  337.  
  338.   this._tag_stack = new TagStack(printer);
  339.  
  340.   var parser_token = null;
  341.   var raw_token = tokens.next();
  342.   while (raw_token.type !== TOKEN.EOF) {
  343.  
  344.     if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) {
  345.       parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token);
  346.       last_tag_token = parser_token;
  347.     } else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) ||
  348.       (raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) {
  349.       parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, tokens);
  350.     } else if (raw_token.type === TOKEN.TAG_CLOSE) {
  351.       parser_token = this._handle_tag_close(printer, raw_token, last_tag_token);
  352.     } else if (raw_token.type === TOKEN.TEXT) {
  353.       parser_token = this._handle_text(printer, raw_token, last_tag_token);
  354.     } else {
  355.       // This should never happen, but if it does. Print the raw token
  356.       printer.add_raw_token(raw_token);
  357.     }
  358.  
  359.     last_token = parser_token;
  360.  
  361.     raw_token = tokens.next();
  362.   }
  363.   var sweet_code = printer._output.get_code(eol);
  364.  
  365.   // BEGIN
  366.   sweet_code = sweet_code.replace(/^([ \t]*)<\/?blade ([a-z]+)\|?([^>\/]+)?\/?>$/gim, function toDirective(m, s, d, c) {
  367.     if (c) {
  368.       c = decodeURIComponent(c);
  369.       c = c.replace(/&#39;/g, "'");
  370.       c = c.replace(/&#34;/g, '"');
  371.       c = c.replace(/^[ \t]*/g, '');
  372.     } else {
  373.       c = "";
  374.     }
  375.     if (!s) {
  376.       s = "";
  377.     }
  378.     switch (d) {
  379.       case 'else':
  380.       case 'elseif':
  381.         s = s.replace(printer._output.__indent_cache.__indent_string, '');
  382.         break;
  383.     }
  384.     return s + "@" + d + c.trim();
  385.   });
  386.   sweet_code = sweet_code.replace(/@(case|default)((?:(?!@break).|\n)+)@break/gim, function addMoreIndent(m, t, c) {
  387.     var indent = printer._output.__indent_cache.__base_string;
  388.     c = c.replace(/\n/g, "\n" + indent + printer._output.__indent_cache.__indent_string);
  389.     c = c.replace(new RegExp(indent + '@' + t, 'gi'), '@' + t);
  390.     return "@" + t + c + "@break";
  391.   });
  392.   sweet_code = sweet_code.replace(/\{\{(--)?((?:(?!(--)?\}\}).)+)(--)?\}\}/g, function (m, ds, c, dh, de) {
  393.     if (c) {
  394.       c = decodeURIComponent(c);
  395.       c = c.replace(/&#39;/g, "'");
  396.       c = c.replace(/&#34;/g, '"');
  397.       c = c.replace(/(^[ \t]*|[ \t]*$)/g, ' ');
  398.     }
  399.     return "{{" + (ds ? ds : "") + c + (de ? de : "") + "}}";
  400.   });
  401.   // END
  402.  
  403.   return sweet_code;
  404. };
  405.  
  406. Beautifier.prototype._handle_tag_close = function (printer, raw_token, last_tag_token) {
  407.   var parser_token = {
  408.     text: raw_token.text,
  409.     type: raw_token.type
  410.   };
  411.   printer.alignment_size = 0;
  412.   last_tag_token.tag_complete = true;
  413.  
  414.   printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
  415.   if (last_tag_token.is_unformatted) {
  416.     printer.add_raw_token(raw_token);
  417.   } else {
  418.     if (last_tag_token.tag_start_char === '<') {
  419.       printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before >
  420.       if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) {
  421.         printer.print_newline(false);
  422.       }
  423.     }
  424.     printer.print_token(raw_token);
  425.  
  426.   }
  427.  
  428.   if (last_tag_token.indent_content &&
  429.     !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
  430.     printer.indent();
  431.  
  432.     // only indent once per opened tag
  433.     last_tag_token.indent_content = false;
  434.   }
  435.  
  436.   if (!last_tag_token.is_inline_element &&
  437.     !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
  438.     printer.set_wrap_point();
  439.   }
  440.  
  441.   return parser_token;
  442. };
  443.  
  444. Beautifier.prototype._handle_inside_tag = function (printer, raw_token, last_tag_token, tokens) {
  445.   var wrapped = last_tag_token.has_wrapped_attrs;
  446.   var parser_token = {
  447.     text: raw_token.text,
  448.     type: raw_token.type
  449.   };
  450.  
  451.   printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
  452.   if (last_tag_token.is_unformatted) {
  453.     printer.add_raw_token(raw_token);
  454.   } else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) {
  455.     // For the insides of handlebars allow newlines or a single space between open and contents
  456.     if (printer.print_preserved_newlines(raw_token)) {
  457.       raw_token.newlines = 0;
  458.       printer.add_raw_token(raw_token);
  459.     } else {
  460.       printer.print_token(raw_token);
  461.     }
  462.   } else {
  463.     if (raw_token.type === TOKEN.ATTRIBUTE) {
  464.       printer.set_space_before_token(true);
  465.       last_tag_token.attr_count += 1;
  466.     } else if (raw_token.type === TOKEN.EQUALS) { //no space before =
  467.       printer.set_space_before_token(false);
  468.     } else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value
  469.       printer.set_space_before_token(false);
  470.     }
  471.  
  472.     if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') {
  473.       if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) {
  474.         printer.traverse_whitespace(raw_token);
  475.         wrapped = wrapped || raw_token.newlines !== 0;
  476.       }
  477.  
  478.  
  479.       if (this._is_wrap_attributes_force) {
  480.         var force_attr_wrap = last_tag_token.attr_count > 1;
  481.         if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.attr_count === 1) {
  482.           var is_only_attribute = true;
  483.           var peek_index = 0;
  484.           var peek_token;
  485.           do {
  486.             peek_token = tokens.peek(peek_index);
  487.             if (peek_token.type === TOKEN.ATTRIBUTE) {
  488.               is_only_attribute = false;
  489.               break;
  490.             }
  491.             peek_index += 1;
  492.           } while (peek_index < 4 && peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE);
  493.  
  494.           force_attr_wrap = !is_only_attribute;
  495.         }
  496.  
  497.         if (force_attr_wrap) {
  498.           printer.print_newline(false);
  499.           wrapped = true;
  500.         }
  501.       }
  502.     }
  503.     printer.print_token(raw_token);
  504.     wrapped = wrapped || printer.previous_token_wrapped();
  505.     last_tag_token.has_wrapped_attrs = wrapped;
  506.   }
  507.   return parser_token;
  508. };
  509.  
  510. Beautifier.prototype._handle_text = function (printer, raw_token, last_tag_token) {
  511.   var parser_token = {
  512.     text: raw_token.text,
  513.     type: 'TK_CONTENT'
  514.   };
  515.   if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript
  516.     this._print_custom_beatifier_text(printer, raw_token, last_tag_token);
  517.   } else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) {
  518.     printer.add_raw_token(raw_token);
  519.   } else {
  520.     printer.traverse_whitespace(raw_token);
  521.     printer.print_token(raw_token);
  522.   }
  523.   return parser_token;
  524. };
  525.  
  526. Beautifier.prototype._print_custom_beatifier_text = function (printer, raw_token, last_tag_token) {
  527.   var local = this;
  528.   if (raw_token.text !== '') {
  529.  
  530.     var text = raw_token.text,
  531.       _beautifier,
  532.       script_indent_level = 1,
  533.       pre = '',
  534.       post = '';
  535.     if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') {
  536.       _beautifier = this._js_beautify;
  537.     } else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') {
  538.       _beautifier = this._css_beautify;
  539.     } else if (last_tag_token.custom_beautifier_name === 'html') {
  540.       _beautifier = function (html_source, options) {
  541.         var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify);
  542.         return beautifier.beautify();
  543.       };
  544.     }
  545.  
  546.     if (this._options.indent_scripts === "keep") {
  547.       script_indent_level = 0;
  548.     } else if (this._options.indent_scripts === "separate") {
  549.       script_indent_level = -printer.indent_level;
  550.     }
  551.  
  552.     var indentation = printer.get_full_indent(script_indent_level);
  553.  
  554.     // if there is at least one empty line at the end of this text, strip it
  555.     // we'll be adding one back after the text but before the containing tag.
  556.     text = text.replace(/\n[ \t]*$/, '');
  557.  
  558.     // Handle the case where content is wrapped in a comment or cdata.
  559.     if (last_tag_token.custom_beautifier_name !== 'html' &&
  560.       text[0] === '<' && text.match(/^(<!--|<!\[CDATA\[)/)) {
  561.       var matched = /^(<!--[^\n]*|<!\[CDATA\[)(\n?)([ \t\n]*)([\s\S]*)(-->|]]>)$/.exec(text);
  562.  
  563.       // if we start to wrap but don't finish, print raw
  564.       if (!matched) {
  565.         printer.add_raw_token(raw_token);
  566.         return;
  567.       }
  568.  
  569.       pre = indentation + matched[1] + '\n';
  570.       text = matched[4];
  571.       if (matched[5]) {
  572.         post = indentation + matched[5];
  573.       }
  574.  
  575.       // if there is at least one empty line at the end of this text, strip it
  576.       // we'll be adding one back after the text but before the containing tag.
  577.       text = text.replace(/\n[ \t]*$/, '');
  578.  
  579.       if (matched[2] || matched[3].indexOf('\n') !== -1) {
  580.         // if the first line of the non-comment text has spaces
  581.         // use that as the basis for indenting in null case.
  582.         matched = matched[3].match(/[ \t]+$/);
  583.         if (matched) {
  584.           raw_token.whitespace_before = matched[0];
  585.         }
  586.       }
  587.     }
  588.  
  589.     if (text) {
  590.       if (_beautifier) {
  591.  
  592.         // call the Beautifier if avaliable
  593.         var Child_options = function () {
  594.           this.eol = '\n';
  595.         };
  596.         Child_options.prototype = this._options.raw_options;
  597.         var child_options = new Child_options();
  598.         text = _beautifier(indentation + text, child_options);
  599.       } else {
  600.         // simply indent the string otherwise
  601.         var white = raw_token.whitespace_before;
  602.         if (white) {
  603.           text = text.replace(new RegExp('\n(' + white + ')?', 'g'), '\n');
  604.         }
  605.  
  606.         text = indentation + text.replace(/\n/g, '\n' + indentation);
  607.       }
  608.     }
  609.  
  610.     if (pre) {
  611.       if (!text) {
  612.         text = pre + post;
  613.       } else {
  614.         text = pre + text + '\n' + post;
  615.       }
  616.     }
  617.  
  618.     printer.print_newline(false);
  619.     if (text) {
  620.       raw_token.text = text;
  621.       raw_token.whitespace_before = '';
  622.       raw_token.newlines = 0;
  623.       printer.add_raw_token(raw_token);
  624.       printer.print_newline(true);
  625.     }
  626.   }
  627. };
  628.  
  629. Beautifier.prototype._handle_tag_open = function (printer, raw_token, last_tag_token, last_token) {
  630.   var parser_token = this._get_tag_open_token(raw_token);
  631.  
  632.   if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) &&
  633.     raw_token.type === TOKEN.TAG_OPEN && raw_token.text.indexOf('</') === 0) {
  634.     // End element tags for unformatted or content_unformatted elements
  635.     // are printed raw to keep any newlines inside them exactly the same.
  636.     printer.add_raw_token(raw_token);
  637.   } else {
  638.     printer.traverse_whitespace(raw_token);
  639.     this._set_tag_position(printer, raw_token, parser_token, last_tag_token, last_token);
  640.     if (!parser_token.is_inline_element) {
  641.       printer.set_wrap_point();
  642.     }
  643.     printer.print_token(raw_token);
  644.   }
  645.  
  646.   //indent attributes an auto, forced, aligned or forced-align line-wrap
  647.   if (this._is_wrap_attributes_force_aligned || this._is_wrap_attributes_aligned_multiple || this._is_wrap_attributes_preserve_aligned) {
  648.     parser_token.alignment_size = raw_token.text.length + 1;
  649.   }
  650.  
  651.   if (!parser_token.tag_complete && !parser_token.is_unformatted) {
  652.     printer.alignment_size = parser_token.alignment_size;
  653.   }
  654.  
  655.   return parser_token;
  656. };
  657.  
  658. var TagOpenParserToken = function (parent, raw_token) {
  659.   this.parent = parent || null;
  660.   this.text = '';
  661.   this.type = 'TK_TAG_OPEN';
  662.   this.tag_name = '';
  663.   this.is_inline_element = false;
  664.   this.is_unformatted = false;
  665.   this.is_content_unformatted = false;
  666.   this.is_empty_element = false;
  667.   this.is_start_tag = false;
  668.   this.is_end_tag = false;
  669.   this.indent_content = false;
  670.   this.multiline_content = false;
  671.   this.custom_beautifier_name = null;
  672.   this.start_tag_token = null;
  673.   this.attr_count = 0;
  674.   this.has_wrapped_attrs = false;
  675.   this.alignment_size = 0;
  676.   this.tag_complete = false;
  677.   this.tag_start_char = '';
  678.   this.tag_check = '';
  679.  
  680.   if (!raw_token) {
  681.     this.tag_complete = true;
  682.   } else {
  683.     var tag_check_match;
  684.  
  685.     this.tag_start_char = raw_token.text[0];
  686.     this.text = raw_token.text;
  687.  
  688.     if (this.tag_start_char === '<') {
  689.       tag_check_match = raw_token.text.match(/^<([^\s>]*)/);
  690.       this.tag_check = tag_check_match ? tag_check_match[1] : '';
  691.     } else {
  692.       tag_check_match = raw_token.text.match(/^{{[#\^]?([^\s}]+)/);
  693.       this.tag_check = tag_check_match ? tag_check_match[1] : '';
  694.     }
  695.     this.tag_check = this.tag_check.toLowerCase();
  696.  
  697.     if (raw_token.type === TOKEN.COMMENT) {
  698.       this.tag_complete = true;
  699.     }
  700.  
  701.     this.is_start_tag = this.tag_check.charAt(0) !== '/';
  702.     this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check;
  703.     this.is_end_tag = !this.is_start_tag ||
  704.       (raw_token.closed && raw_token.closed.text === '/>');
  705.  
  706.     // handlebars tags that don't start with # or ^ are single_tags, and so also start and end.
  707.     this.is_end_tag = this.is_end_tag ||
  708.       (this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\^]/.test(this.text.charAt(2)))));
  709.   }
  710. };
  711.  
  712. Beautifier.prototype._get_tag_open_token = function (raw_token) { //function to get a full tag and parse its type
  713.   var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token);
  714.  
  715.   parser_token.alignment_size = this._options.wrap_attributes_indent_size;
  716.  
  717.   parser_token.is_end_tag = parser_token.is_end_tag ||
  718.     in_array(parser_token.tag_check, this._options.void_elements);
  719.  
  720.   parser_token.is_empty_element = parser_token.tag_complete ||
  721.     (parser_token.is_start_tag && parser_token.is_end_tag);
  722.  
  723.   parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted);
  724.   parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted);
  725.   parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_start_char === '{';
  726.  
  727.   return parser_token;
  728. };
  729.  
  730. Beautifier.prototype._set_tag_position = function (printer, raw_token, parser_token, last_tag_token, last_token) {
  731.  
  732.   if (!parser_token.is_empty_element) {
  733.     if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
  734.       parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors
  735.     } else { // it's a start-tag
  736.       // check if this tag is starting an element that has optional end element
  737.       // and do an ending needed
  738.       if (this._do_optional_end_element(parser_token)) {
  739.         if (!parser_token.is_inline_element) {
  740.           if (parser_token.parent) {
  741.             parser_token.parent.multiline_content = true;
  742.           }
  743.           printer.print_newline(false);
  744.         }
  745.  
  746.       }
  747.  
  748.       this._tag_stack.record_tag(parser_token); //push it on the tag stack
  749.  
  750.       if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') &&
  751.         !(parser_token.is_unformatted || parser_token.is_content_unformatted)) {
  752.         parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token);
  753.       }
  754.     }
  755.   }
  756.  
  757.   if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line
  758.     printer.print_newline(false);
  759.     if (!printer._output.just_added_blankline()) {
  760.       printer.print_newline(true);
  761.     }
  762.   }
  763.  
  764.   if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /)
  765.  
  766.     // if you hit an else case, reset the indent level if you are inside an:
  767.     // 'if', 'unless', or 'each' block.
  768.     if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') {
  769.       this._tag_stack.indent_to_tag(['if', 'unless', 'each']);
  770.       parser_token.indent_content = true;
  771.       // Don't add a newline if opening {{#if}} tag is on the current line
  772.       var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/);
  773.       if (!foundIfOnCurrentLine) {
  774.         printer.print_newline(false);
  775.       }
  776.     }
  777.  
  778.     // Don't add a newline before elements that should remain where they are.
  779.     if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE &&
  780.       last_tag_token.is_end_tag && parser_token.text.indexOf('\n') === -1) {
  781.       //Do nothing. Leave comments on same line.
  782.     } else if (!parser_token.is_inline_element && !parser_token.is_unformatted) {
  783.       printer.print_newline(false);
  784.     }
  785.   } else if (parser_token.is_unformatted || parser_token.is_content_unformatted) {
  786.     if (!parser_token.is_inline_element && !parser_token.is_unformatted) {
  787.       printer.print_newline(false);
  788.     }
  789.   } else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
  790.     if ((parser_token.start_tag_token && parser_token.start_tag_token.multiline_content) ||
  791.       !(parser_token.is_inline_element ||
  792.         (last_tag_token.is_inline_element) ||
  793.         (last_token.type === TOKEN.TAG_CLOSE &&
  794.           parser_token.start_tag_token === last_tag_token) ||
  795.         (last_token.type === 'TK_CONTENT')
  796.       )) {
  797.       printer.print_newline(false);
  798.     }
  799.   } else { // it's a start-tag
  800.     parser_token.indent_content = !parser_token.custom_beautifier_name;
  801.  
  802.     if (parser_token.tag_start_char === '<') {
  803.       if (parser_token.tag_name === 'html') {
  804.         parser_token.indent_content = this._options.indent_inner_html;
  805.       } else if (parser_token.tag_name === 'head') {
  806.         parser_token.indent_content = this._options.indent_head_inner_html;
  807.       } else if (parser_token.tag_name === 'body') {
  808.         parser_token.indent_content = this._options.indent_body_inner_html;
  809.       }
  810.     }
  811.  
  812.     if (!parser_token.is_inline_element && last_token.type !== 'TK_CONTENT') {
  813.       if (parser_token.parent) {
  814.         parser_token.parent.multiline_content = true;
  815.       }
  816.       printer.print_newline(false);
  817.     }
  818.   }
  819. };
  820.  
  821. //To be used for <p> tag special case:
  822. //var p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];
  823.  
  824. Beautifier.prototype._do_optional_end_element = function (parser_token) {
  825.   var result = null;
  826.   // NOTE: cases of "if there is no more content in the parent element"
  827.   // are handled automatically by the beautifier.
  828.   // It assumes parent or ancestor close tag closes all children.
  829.   // https://www.w3.org/TR/html5/syntax.html#optional-tags
  830.   if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {
  831.     return;
  832.  
  833.   } else if (parser_token.tag_name === 'body') {
  834.     // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.
  835.     result = result || this._tag_stack.try_pop('head');
  836.  
  837.     //} else if (parser_token.tag_name === 'body') {
  838.     // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.
  839.  
  840.   } else if (parser_token.tag_name === 'li') {
  841.     // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.
  842.     result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);
  843.  
  844.   } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {
  845.     // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.
  846.     // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.
  847.     result = result || this._tag_stack.try_pop('dt', ['dl']);
  848.     result = result || this._tag_stack.try_pop('dd', ['dl']);
  849.  
  850.     //} else if (p_closers.indexOf(parser_token.tag_name) !== -1) {
  851.     //TODO: THIS IS A BUG FARM. We are not putting this into 1.8.0 as it is likely to blow up.
  852.     //A p element’s end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hr, main, nav, ol, p, pre, section, table, or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an a, audio, del, ins, map, noscript, or video element, or an autonomous custom element.
  853.     //result = result || this._tag_stack.try_pop('p', ['body']);
  854.  
  855.   } else if (parser_token.tag_name === 'rp' || parser_token.tag_name === 'rt') {
  856.     // An rt element’s end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
  857.     // An rp element’s end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
  858.     result = result || this._tag_stack.try_pop('rt', ['ruby', 'rtc']);
  859.     result = result || this._tag_stack.try_pop('rp', ['ruby', 'rtc']);
  860.  
  861.   } else if (parser_token.tag_name === 'optgroup') {
  862.     // An optgroup element’s end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.
  863.     // An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
  864.     result = result || this._tag_stack.try_pop('optgroup', ['select']);
  865.     //result = result || this._tag_stack.try_pop('option', ['select']);
  866.  
  867.   } else if (parser_token.tag_name === 'option') {
  868.     // An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
  869.     result = result || this._tag_stack.try_pop('option', ['select', 'datalist', 'optgroup']);
  870.  
  871.   } else if (parser_token.tag_name === 'colgroup') {
  872.     // DONE: A colgroup element’s end tag may be omitted if the colgroup element is not immediately followed by a space character or a comment.
  873.     // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
  874.     result = result || this._tag_stack.try_pop('caption', ['table']);
  875.  
  876.   } else if (parser_token.tag_name === 'thead') {
  877.     // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
  878.     // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
  879.     result = result || this._tag_stack.try_pop('caption', ['table']);
  880.     result = result || this._tag_stack.try_pop('colgroup', ['table']);
  881.  
  882.     //} else if (parser_token.tag_name === 'caption') {
  883.     // DONE: A caption element’s end tag may be omitted if the caption element is not immediately followed by a space character or a comment.
  884.  
  885.   } else if (parser_token.tag_name === 'tbody' || parser_token.tag_name === 'tfoot') {
  886.     // A thead element’s end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.
  887.     // A tbody element’s end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.
  888.     // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
  889.     // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
  890.     result = result || this._tag_stack.try_pop('caption', ['table']);
  891.     result = result || this._tag_stack.try_pop('colgroup', ['table']);
  892.     result = result || this._tag_stack.try_pop('thead', ['table']);
  893.     result = result || this._tag_stack.try_pop('tbody', ['table']);
  894.  
  895.     //} else if (parser_token.tag_name === 'tfoot') {
  896.     // DONE: A tfoot element’s end tag may be omitted if there is no more content in the parent element.
  897.  
  898.   } else if (parser_token.tag_name === 'tr') {
  899.     // A tr element’s end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.
  900.     // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
  901.     // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
  902.     result = result || this._tag_stack.try_pop('caption', ['table']);
  903.     result = result || this._tag_stack.try_pop('colgroup', ['table']);
  904.     result = result || this._tag_stack.try_pop('tr', ['table', 'thead', 'tbody', 'tfoot']);
  905.  
  906.   } else if (parser_token.tag_name === 'th' || parser_token.tag_name === 'td') {
  907.     // A td element’s end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
  908.     // A th element’s end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
  909.     result = result || this._tag_stack.try_pop('td', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
  910.     result = result || this._tag_stack.try_pop('th', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
  911.   }
  912.  
  913.   // Start element omission not handled currently
  914.   // A head element’s start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.
  915.   // A tbody element’s start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can’t be omitted if the element is empty.)
  916.   // A colgroup element’s start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can’t be omitted if the element is empty.)
  917.  
  918.   // Fix up the parent of the parser token
  919.   parser_token.parent = this._tag_stack.get_parser_token();
  920.  
  921.   return result;
  922. };
  923.  
  924. module.exports.Beautifier = Beautifier;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement