Module | Haml::Precompiler |
In: |
lib/haml/template/plugin.rb
lib/haml/precompiler.rb |
ELEMENT | = | ?% | Designates an XHTML/XML element. | |
DIV_CLASS | = | ?. | Designates a `<div>` element with the given class. | |
DIV_ID | = | ?# | Designates a `<div>` element with the given id. | |
COMMENT | = | ?/ | Designates an XHTML/XML comment. | |
DOCTYPE | = | ?! | Designates an XHTML doctype or script that is never HTML-escaped. | |
SCRIPT | = | ?= | Designates script, the result of which is output. | |
SANITIZE | = | ?& | Designates script that is always HTML-escaped. | |
FLAT_SCRIPT | = | ?~ | Designates script, the result of which is flattened and output. | |
SILENT_SCRIPT | = | ?- | Designates script which is run but not output. | |
SILENT_COMMENT | = | ?# | When following SILENT_SCRIPT, designates a comment that is not output. | |
ESCAPE | = | ?\\ | Designates a non-parsed line. | |
FILTER | = | ?: | Designates a block of filtered text. | |
PLAIN_TEXT | = | -1 | Designates a non-parsed line. Not actually a character. | |
SPECIAL_CHARACTERS | = | [ ELEMENT, DIV_CLASS, DIV_ID, COMMENT, DOCTYPE, SCRIPT, SANITIZE, FLAT_SCRIPT, SILENT_SCRIPT, ESCAPE, FILTER | Keeps track of the ASCII values of the characters that begin a specially-interpreted line. | |
MULTILINE_CHAR_VALUE | = | ?| | The value of the character that designates that a line is part of a multiline string. | |
MID_BLOCK_KEYWORD_REGEX | = | /^-\s*(#{%w[else elsif rescue ensure when end].join('|')})\b/ |
Regex to match keywords that appear in the middle of a Ruby block with
lowered indentation. If a block has been started using indentation,
lowering the indentation with one of these won‘t end the block. For
example:
- if foo %p yes! - else %p no! The block is ended after `%p no!`, because `else` is a member of this array. |
|
DOCTYPE_REGEX | = | /(\d(?:\.\d)?)?[\s]*([a-z]*)/i | The Regex that matches a Doctype command. | |
LITERAL_VALUE_REGEX | = | /:(\w*)|(["'])((?![\\#]|\2).|\\.)*\2/ | The Regex that matches a literal string or symbol value |
push_silent | -> | push_silent_without_haml_block_deprecation |
This is a class method so it can be accessed from Buffer.
# File lib/haml/precompiler.rb, line 520 520: def self.build_attributes(is_html, attr_wrapper, attributes = {}) 521: quote_escape = attr_wrapper == '"' ? """ : "'" 522: other_quote_char = attr_wrapper == '"' ? "'" : '"' 523: 524: if attributes['data'].is_a?(Hash) 525: attributes = attributes.dup 526: attributes = 527: Haml::Util.map_keys(attributes.delete('data')) {|name| "data-#{name}"}.merge(attributes) 528: end 529: 530: result = attributes.collect do |attr, value| 531: next if value.nil? 532: 533: value = filter_and_join(value, ' ') if attr == :class 534: value = filter_and_join(value, '_') if attr == :id 535: 536: if value == true 537: next " #{attr}" if is_html 538: next " #{attr}=#{attr_wrapper}#{attr}#{attr_wrapper}" 539: elsif value == false 540: next 541: end 542: 543: value = Haml::Helpers.preserve(Haml::Helpers.escape_once(value.to_s)) 544: # We want to decide whether or not to escape quotes 545: value.gsub!('"', '"') 546: this_attr_wrapper = attr_wrapper 547: if value.include? attr_wrapper 548: if value.include? other_quote_char 549: value = value.gsub(attr_wrapper, quote_escape) 550: else 551: this_attr_wrapper = other_quote_char 552: end 553: end 554: " #{attr}=#{this_attr_wrapper}#{value}#{this_attr_wrapper}" 555: end 556: result.compact.sort.join 557: end
# File lib/haml/precompiler.rb, line 559 559: def self.filter_and_join(value, separator) 560: value = [value] unless value.is_a?(Array) 561: return value.flatten.collect {|item| item ? item.to_s : nil}.compact.join(separator) 562: end
This is a class method so it can be accessed from {Haml::Helpers}.
Iterates through the classes and ids supplied through `.` and `#` syntax, and returns a hash with them as attributes, that can then be merged with another attributes hash.
# File lib/haml/precompiler.rb, line 487 487: def self.parse_class_and_id(list) 488: attributes = {} 489: list.scan(/([#.])([-:_a-zA-Z0-9]+)/) do |type, property| 490: case type 491: when '.' 492: if attributes['class'] 493: attributes['class'] += " " 494: else 495: attributes['class'] = "" 496: end 497: attributes['class'] += property 498: when '#'; attributes['id'] = property 499: end 500: end 501: attributes 502: end
# File lib/haml/template/plugin.rb, line 49 49: def push_silent_with_haml_block_deprecation(text, can_suppress = false) 50: unless can_suppress && block_opened? && !mid_block_keyword?("- #{text}") && 51: text =~ ActionView::Template::Handlers::Erubis::BLOCK_EXPR 52: return push_silent_without_haml_block_deprecation(text, can_suppress) 53: end 54: 55: push_silent_without_haml_block_deprecation("_hamlout.append_if_string= #{text}", can_suppress) 56: end
# File lib/haml/precompiler.rb, line 1028 1028: def balance(*args) 1029: res = Haml::Shared.balance(*args) 1030: return res if res 1031: raise SyntaxError.new("Unbalanced brackets.") 1032: end
# File lib/haml/precompiler.rb, line 1034 1034: def block_opened? 1035: !flat? && @next_line.tabs > @line.tabs 1036: end
Closes the most recent item in `@to_close_stack`.
# File lib/haml/precompiler.rb, line 425 425: def close 426: tag, *rest = @to_close_stack.pop 427: send("close_#{tag}", *rest) 428: end
Closes a comment.
# File lib/haml/precompiler.rb, line 449 449: def close_comment(has_conditional) 450: @output_tabs -= 1 451: @template_tabs -= 1 452: close_tag = has_conditional ? "<![endif]-->" : "-->" 453: push_text(close_tag, -1) 454: end
Puts a line in `@precompiled` that will add the closing tag of the most recently opened tag.
# File lib/haml/precompiler.rb, line 432 432: def close_element(value) 433: tag, nuke_outer_whitespace, nuke_inner_whitespace = value 434: @output_tabs -= 1 unless nuke_inner_whitespace 435: @template_tabs -= 1 436: rstrip_buffer! if nuke_inner_whitespace 437: push_merged_text("</#{tag}>" + (nuke_outer_whitespace ? "" : "\n"), 438: nuke_inner_whitespace ? 0 : -1, !nuke_inner_whitespace) 439: @dont_indent_next_line = nuke_outer_whitespace 440: end
Closes a filtered block.
# File lib/haml/precompiler.rb, line 465 465: def close_filtered(filter) 466: filter.internal_compile(self, @filter_buffer) 467: @flat = false 468: @flat_spaces = nil 469: @filter_buffer = nil 470: @template_tabs -= 1 471: end
# File lib/haml/precompiler.rb, line 473 473: def close_haml_comment 474: @haml_comment = false 475: @template_tabs -= 1 476: end
Closes a loud Ruby block.
# File lib/haml/precompiler.rb, line 457 457: def close_loud(command, add_newline, push_end = true) 458: push_silent('end', true) if push_end 459: @precompiled << command 460: @template_tabs -= 1 461: concat_merged_text("\n") if add_newline 462: end
# File lib/haml/precompiler.rb, line 478 478: def close_nil(*args) 479: @template_tabs -= 1 480: end
Closes a Ruby block.
# File lib/haml/precompiler.rb, line 443 443: def close_script(_1, _2, push_end = true) 444: push_silent("end", true) if push_end 445: @template_tabs -= 1 446: end
# File lib/haml/precompiler.rb, line 960 960: def closes_flat?(line) 961: line && !line.text.empty? && line.full !~ /^#{@flat_spaces}/ 962: end
Concatenate `text` to `@buffer` without tabulation.
# File lib/haml/precompiler.rb, line 302 302: def concat_merged_text(text) 303: @to_merge << [:text, text, 0] 304: end
# File lib/haml/precompiler.rb, line 1008 1008: def contains_interpolation?(str) 1009: str.include?('#{') 1010: end
# File lib/haml/precompiler.rb, line 310 310: def flush_merged_text 311: return if @to_merge.empty? 312: 313: str = "" 314: mtabs = 0 315: newlines = 0 316: @to_merge.each do |type, val, tabs| 317: case type 318: when :text 319: str << val.inspect[1...-1] 320: mtabs += tabs 321: when :script 322: if mtabs != 0 && !@options[:ugly] 323: val = "_hamlout.adjust_tabs(#{mtabs}); " + val 324: end 325: str << "\#{#{"\n" * newlines}#{val}}" 326: mtabs = 0 327: newlines = 0 328: when :newlines 329: newlines += val 330: else 331: raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Precompiler@to_merge.") 332: end 333: end 334: 335: @precompiled << 336: if @options[:ugly] 337: "_hamlout.buffer << \"#{str}\";" 338: else 339: "_hamlout.push_text(\"#{str}\", #{mtabs}, #{@dont_tab_up_next_text.inspect});" 340: end 341: @precompiled << "\n" * newlines 342: @to_merge = [] 343: @dont_tab_up_next_text = false 344: end
# File lib/haml/precompiler.rb, line 969 969: def handle_multiline(line) 970: return unless is_multiline?(line.text) 971: line.text.slice!(-1) 972: while new_line = raw_next_line.first 973: break if new_line == :eod 974: newline and next if new_line.strip.empty? 975: break unless is_multiline?(new_line.strip) 976: line.text << new_line.strip[0...-1] 977: newline 978: end 979: un_next_line new_line 980: resolve_newlines 981: end
# File lib/haml/precompiler.rb, line 988 988: def handle_ruby_multiline(text) 989: text = text.rstrip 990: return text unless is_ruby_multiline?(text) 991: un_next_line @next_line.full 992: begin 993: new_line = raw_next_line.first 994: break if new_line == :eod 995: newline and next if new_line.strip.empty? 996: text << " " << new_line.strip 997: newline 998: end while is_ruby_multiline?(new_line.strip) 999: next_line 1000: resolve_newlines 1001: text 1002: end
Checks whether or not line is in a multiline sequence.
# File lib/haml/precompiler.rb, line 984 984: def is_multiline?(text) 985: text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s 986: end
# File lib/haml/precompiler.rb, line 1004 1004: def is_ruby_multiline?(text) 1005: text && text.length > 1 && text[-1] == ?, && text[-2] != ?? && text[-3..-2] != "?\\" 1006: end
# File lib/haml/precompiler.rb, line 118 118: def locals_code(names) 119: names = names.keys if Hash == names 120: 121: names.map do |name| 122: # Can't use || because someone might explicitly pass in false with a symbol 123: sym_local = "_haml_locals[#{name.to_sym.inspect}]" 124: str_local = "_haml_locals[#{name.to_s.inspect}]" 125: "#{name} = #{sym_local}.nil? ? #{str_local} : #{sym_local}" 126: end.join(';') + ';' 127: end
If the text is a silent script text with one of Ruby‘s mid-block keywords, returns the name of that keyword. Otherwise, returns nil.
# File lib/haml/precompiler.rb, line 281 281: def mid_block_keyword?(text) 282: text[MID_BLOCK_KEYWORD_REGEX, 1] 283: end
# File lib/haml/precompiler.rb, line 1053 1053: def newline_now 1054: @precompiled << "\n" 1055: @newlines -= 1 1056: end
# File lib/haml/precompiler.rb, line 930 930: def next_line 931: text, index = raw_next_line 932: return unless text 933: 934: # :eod is a special end-of-document marker 935: line = 936: if text == :eod 937: Line.new '-#', '-#', '-#', index, self, true 938: else 939: Line.new text.strip, text.lstrip.chomp, text, index, self, false 940: end 941: 942: # `flat?' here is a little outdated, 943: # so we have to manually check if either the previous or current line 944: # closes the flat block, 945: # as well as whether a new block is opened 946: @line.tabs if @line 947: unless (flat? && !closes_flat?(line) && !closes_flat?(@line)) || 948: (@line && @line.text[0] == ?: && line.full =~ %r[^#{@line.full[/^\s+/]}\s]) 949: if line.text.empty? 950: newline 951: return next_line 952: end 953: 954: handle_multiline(line) 955: end 956: 957: @next_line = line 958: end
# File lib/haml/precompiler.rb, line 666 666: def parse_new_attribute(scanner) 667: unless name = scanner.scan(/[-:\w]+/) 668: return if scanner.scan(/\)/) 669: return false 670: end 671: 672: scanner.scan(/\s*/) 673: return name, [:static, true] unless scanner.scan(/=/) #/end 674: 675: scanner.scan(/\s*/) 676: unless quote = scanner.scan(/["']/) 677: return false unless var = scanner.scan(/(@@?|\$)?\w+/) 678: return name, [:dynamic, var] 679: end 680: 681: re = /((?:\\.|\#(?!\{)|[^#{quote}\\#])*)(#{quote}|#\{)/ 682: content = [] 683: loop do 684: return false unless scanner.scan(re) 685: content << [:str, scanner[1].gsub(/\\(.)/, '\1')] 686: break if scanner[2] == quote 687: content << [:ruby, balance(scanner, ?{, ?}, 1).first[0...-1]] 688: end 689: 690: return name, [:static, content.first[1]] if content.size == 1 691: return name, [:dynamic, 692: '"' + content.map {|(t, v)| t == :str ? v.inspect[1...-1] : "\#{#{v}}"}.join + '"'] 693: end
# File lib/haml/precompiler.rb, line 625 625: def parse_new_attributes(line) 626: line = line.dup 627: scanner = StringScanner.new(line) 628: last_line = @index 629: attributes = {} 630: 631: scanner.scan(/\(\s*/) 632: loop do 633: name, value = parse_new_attribute(scanner) 634: break if name.nil? 635: 636: if name == false 637: text = (Haml::Shared.balance(line, ?(, ?)) || [line]).first 638: raise Haml::SyntaxError.new("Invalid attribute list: #{text.inspect}.", last_line - 1) 639: end 640: attributes[name] = value 641: scanner.scan(/\s*/) 642: 643: if scanner.eos? 644: line << " " << @next_line.text 645: last_line += 1 646: next_line 647: scanner.scan(/\s*/) 648: end 649: end 650: 651: static_attributes = {} 652: dynamic_attributes = "{" 653: attributes.each do |name, (type, val)| 654: if type == :static 655: static_attributes[name] = val 656: else 657: dynamic_attributes << name.inspect << " => " << val << "," 658: end 659: end 660: dynamic_attributes << "}" 661: dynamic_attributes = nil if dynamic_attributes == "{}" 662: 663: return [static_attributes, dynamic_attributes], scanner.rest, last_line 664: end
# File lib/haml/precompiler.rb, line 604 604: def parse_old_attributes(line) 605: line = line.dup 606: last_line = @index 607: 608: begin 609: attributes_hash, rest = balance(line, ?{, ?}) 610: rescue SyntaxError => e 611: if line.strip[-1] == ?, && e.message == "Unbalanced brackets." 612: line << "\n" << @next_line.text 613: last_line += 1 614: next_line 615: retry 616: end 617: 618: raise e 619: end 620: 621: attributes_hash = attributes_hash[1...-1] if attributes_hash 622: return attributes_hash, rest, last_line 623: end
# File lib/haml/precompiler.rb, line 504 504: def parse_static_hash(text) 505: attributes = {} 506: scanner = StringScanner.new(text) 507: scanner.scan(/\s+/) 508: until scanner.eos? 509: return unless key = scanner.scan(LITERAL_VALUE_REGEX) 510: return unless scanner.scan(/\s*=>\s*/) 511: return unless value = scanner.scan(LITERAL_VALUE_REGEX) 512: return unless scanner.scan(/\s*(?:,|$)\s*/) 513: attributes[eval(key).to_s] = eval(value).to_s 514: end 515: text.count("\n").times { newline } 516: attributes 517: end
Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value
# File lib/haml/precompiler.rb, line 570 570: def parse_tag(line) 571: raise SyntaxError.new("Invalid tag: \"#{line}\".") unless match = line.scan(/%([-:\w]+)([-:\w\.\#]*)(.*)/)[0] 572: tag_name, attributes, rest = match 573: new_attributes_hash = old_attributes_hash = last_line = object_ref = nil 574: attributes_hashes = [] 575: while rest 576: case rest[0] 577: when ?{ 578: break if old_attributes_hash 579: old_attributes_hash, rest, last_line = parse_old_attributes(rest) 580: attributes_hashes << [:old, old_attributes_hash] 581: when ?( 582: break if new_attributes_hash 583: new_attributes_hash, rest, last_line = parse_new_attributes(rest) 584: attributes_hashes << [:new, new_attributes_hash] 585: when ?[ 586: break if object_ref 587: object_ref, rest = balance(rest, ?[, ?]) 588: else; break 589: end 590: end 591: 592: if rest 593: nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0] 594: nuke_whitespace ||= '' 595: nuke_outer_whitespace = nuke_whitespace.include? '>' 596: nuke_inner_whitespace = nuke_whitespace.include? '<' 597: end 598: 599: value = value.to_s.strip 600: [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, 601: nuke_inner_whitespace, action, value, last_line || @index] 602: end
# File lib/haml/precompiler.rb, line 163 163: def precompile 164: @haml_comment = @dont_indent_next_line = @dont_tab_up_next_text = false 165: @indentation = nil 166: @line = next_line 167: resolve_newlines 168: newline 169: 170: raise SyntaxError.new("Indenting at the beginning of the document is illegal.", @line.index) if @line.tabs != 0 171: 172: while next_line 173: process_indent(@line) unless @line.text.empty? 174: 175: if flat? 176: push_flat(@line) 177: @line = @next_line 178: next 179: end 180: 181: process_line(@line.text, @line.index) unless @line.text.empty? || @haml_comment 182: 183: if !flat? && @next_line.tabs - @line.tabs > 1 184: raise SyntaxError.new("The line was indented #{@next_line.tabs - @line.tabs} levels deeper than the previous line.", @next_line.index) 185: end 186: 187: resolve_newlines unless @next_line.eod? 188: @line = @next_line 189: newline unless @next_line.eod? 190: end 191: 192: # Close all the open tags 193: close until @to_close_stack.empty? 194: flush_merged_text 195: end
Returns the string used as the return value of the precompiled method. This method exists so it can be monkeypatched to return modified values.
# File lib/haml/precompiler.rb, line 114 114: def precompiled_method_return_value 115: "_erbout" 116: end
Returns the precompiled string with the preamble and postamble
# File lib/haml/precompiler.rb, line 93 93: def precompiled_with_ambles(local_names) 94: preamble = "begin\nextend Haml::Helpers\n_hamlout = @haml_buffer = Haml::Buffer.new(@haml_buffer, \#{options_for_buffer.inspect})\n_erbout = _hamlout.buffer\n__in_erb_template = true\n".gsub("\n", ";") 95: postamble = "\#{precompiled_method_return_value}\nensure\n@haml_buffer = @haml_buffer.upper\nend\n".gsub("\n", ";") 96: preamble + locals_code(local_names) + precompiled + postamble 97: end
# File lib/haml/precompiler.rb, line 564 564: def prerender_tag(name, self_close, attributes) 565: attributes_string = Precompiler.build_attributes(html?, @options[:attr_wrapper], attributes) 566: "<#{name}#{attributes_string}#{self_close && xhtml? ? ' /' : ''}>" 567: end
Processes and deals with lowering indentation.
# File lib/haml/precompiler.rb, line 198 198: def process_indent(line) 199: return unless line.tabs <= @template_tabs && @template_tabs > 0 200: 201: to_close = @template_tabs - line.tabs 202: to_close.times {|i| close unless to_close - 1 - i == 0 && mid_block_keyword?(line.text)} 203: end
Processes a single line of Haml.
This method doesn‘t return anything; it simply processes the line and adds the appropriate code to `@precompiled`.
# File lib/haml/precompiler.rb, line 209 209: def process_line(text, index) 210: @index = index + 1 211: 212: case text[0] 213: when DIV_CLASS; render_div(text) 214: when DIV_ID 215: return push_plain(text) if text[1] == ?{ 216: render_div(text) 217: when ELEMENT; render_tag(text) 218: when COMMENT; render_comment(text[1..-1].strip) 219: when SANITIZE 220: return push_plain(text[3..-1].strip, :escape_html => true) if text[1..2] == "==" 221: return push_script(text[2..-1].strip, :escape_html => true) if text[1] == SCRIPT 222: return push_flat_script(text[2..-1].strip, :escape_html => true) if text[1] == FLAT_SCRIPT 223: return push_plain(text[1..-1].strip, :escape_html => true) if text[1] == ?\s 224: push_plain text 225: when SCRIPT 226: return push_plain(text[2..-1].strip) if text[1] == SCRIPT 227: push_script(text[1..-1]) 228: when FLAT_SCRIPT; push_flat_script(text[1..-1]) 229: when SILENT_SCRIPT 230: return start_haml_comment if text[1] == SILENT_COMMENT 231: 232: raise SyntaxError.new("You don't need to use \"- end\" in Haml. Un-indent to close a block:\n- if foo?\n %strong Foo!\n- else\n Not foo.\n%p This line is un-indented, so it isn't part of the \"if\" block\n".rstrip, index) if text[1..-1].strip == "end" 233: 234: text = handle_ruby_multiline(text) 235: push_silent(text[1..-1], true) 236: newline_now 237: 238: # Handle stuff like - end.join("|") 239: @to_close_stack.last << false if text =~ /^-\s*end\b/ && !block_opened? 240: 241: keyword = mid_block_keyword?(text) 242: block = block_opened? && !keyword 243: 244: # It's important to preserve tabulation modification for keywords 245: # that involve choosing between posible blocks of code. 246: if %w[else elsif when].include?(keyword) 247: @dont_indent_next_line, @dont_tab_up_next_text = @to_close_stack.last[1..2] 248: 249: # when is unusual in that either it will be indented twice, 250: # or the case won't have created its own indentation 251: if keyword == "when" 252: push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text, false]) 253: end 254: elsif block || text =~ /^-\s*(case|if)\b/ 255: push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text]) 256: end 257: when FILTER; start_filtered(text[1..-1].downcase) 258: when DOCTYPE 259: return render_doctype(text) if text[0...3] == '!!!' 260: return push_plain(text[3..-1].strip, :escape_html => false) if text[1..2] == "==" 261: return push_script(text[2..-1].strip, :escape_html => false) if text[1] == SCRIPT 262: return push_flat_script(text[2..-1].strip, :escape_html => false) if text[1] == FLAT_SCRIPT 263: return push_plain(text[1..-1].strip, :escape_html => false) if text[1] == ?\s 264: push_plain text 265: when ESCAPE; push_plain text[1..-1] 266: else push_plain text 267: end 268: end
Pushes value onto `@to_close_stack` and increases `@template_tabs`.
# File lib/haml/precompiler.rb, line 1040 1040: def push_and_tabulate(value) 1041: @to_close_stack.push(value) 1042: @template_tabs += 1 1043: end
Adds text to `@buffer` while flattening text.
# File lib/haml/precompiler.rb, line 364 364: def push_flat(line) 365: text = line.full.dup 366: text = "" unless text.gsub!(/^#{@flat_spaces}/, '') 367: @filter_buffer << "#{text}\n" 368: end
Causes `text` to be evaluated, and Haml::Helpers#find_and_flatten to be run on it afterwards.
# File lib/haml/precompiler.rb, line 410 410: def push_flat_script(text, options = {}) 411: flush_merged_text 412: 413: raise SyntaxError.new("There's no Ruby code for ~ to evaluate.") if text.empty? 414: push_script(text, options.merge(:preserve_script => true)) 415: end
Adds `text` to `@buffer` with appropriate tabulation without parsing it.
# File lib/haml/precompiler.rb, line 295 295: def push_merged_text(text, tab_change = 0, indent = true) 296: text = !indent || @dont_indent_next_line || @options[:ugly] ? text : "#{' ' * @output_tabs}#{text}" 297: @to_merge << [:text, text, tab_change] 298: @dont_indent_next_line = false 299: end
Renders a block of text as plain text. Also checks for an illegally opened block.
# File lib/haml/precompiler.rb, line 348 348: def push_plain(text, options = {}) 349: if block_opened? 350: raise SyntaxError.new("Illegal nesting: nesting within plain text is illegal.", @next_line.index) 351: end 352: 353: if contains_interpolation?(text) 354: options[:escape_html] = self.options[:escape_html] if options[:escape_html].nil? 355: push_script( 356: unescape_interpolation(text, :escape_html => options[:escape_html]), 357: :escape_html => false) 358: else 359: push_text text 360: end 361: end
Causes `text` to be evaluated in the context of the scope object and the result to be added to `@buffer`.
If `opts[:preserve_script]` is true, Haml::Helpers#find_and_flatten is run on the result before it is added to `@buffer`
# File lib/haml/precompiler.rb, line 375 375: def push_script(text, opts = {}) 376: raise SyntaxError.new("There's no Ruby code for = to evaluate.") if text.empty? 377: text = handle_ruby_multiline(text) 378: return if options[:suppress_eval] 379: opts[:escape_html] = options[:escape_html] if opts[:escape_html].nil? 380: 381: args = %w[preserve_script in_tag preserve_tag escape_html nuke_inner_whitespace] 382: args.map! {|name| opts[name.to_sym]} 383: args << !block_opened? << @options[:ugly] 384: 385: no_format = @options[:ugly] && 386: !(opts[:preserve_script] || opts[:preserve_tag] || opts[:escape_html]) 387: output_expr = "(#{text}\n)" 388: static_method = "_hamlout.#{static_method_name(:format_script, *args)}" 389: 390: # Prerender tabulation unless we're in a tag 391: push_merged_text '' unless opts[:in_tag] 392: 393: unless block_opened? 394: @to_merge << [:script, no_format ? "#{text}\n" : "#{static_method}(#{output_expr});"] 395: concat_merged_text("\n") unless opts[:in_tag] || opts[:nuke_inner_whitespace] 396: @newlines -= 1 397: return 398: end 399: 400: flush_merged_text 401: 402: push_silent "haml_temp = #{text}" 403: newline_now 404: push_and_tabulate([:loud, "_hamlout.buffer << #{no_format ? "haml_temp.to_s;" : "#{static_method}(haml_temp);"}", 405: !(opts[:in_tag] || opts[:nuke_inner_whitespace] || @options[:ugly])]) 406: end
Evaluates `text` in the context of the scope object, but does not output the result.
# File lib/haml/precompiler.rb, line 287 287: def push_silent(text, can_suppress = false) 288: flush_merged_text 289: return if can_suppress && options[:suppress_eval] 290: @precompiled << "#{text};" 291: end
# File lib/haml/precompiler.rb, line 306 306: def push_text(text, tab_change = 0) 307: push_merged_text("#{text}\n", tab_change) 308: end
# File lib/haml/precompiler.rb, line 920 920: def raw_next_line 921: text = @template.shift 922: return unless text 923: 924: index = @template_index 925: @template_index += 1 926: 927: return text, index 928: end
Renders an XHTML comment.
# File lib/haml/precompiler.rb, line 836 836: def render_comment(line) 837: conditional, line = balance(line, ?[, ?]) if line[0] == ?[ 838: line.strip! 839: conditional << ">" if conditional 840: 841: if block_opened? && !line.empty? 842: raise SyntaxError.new('Illegal nesting: nesting within a tag that already has content is illegal.', @next_line.index) 843: end 844: 845: open = "<!--#{conditional}" 846: 847: # Render it statically if possible 848: unless line.empty? 849: return push_text("#{open} #{line} #{conditional ? "<![endif]-->" : "-->"}") 850: end 851: 852: push_text(open, 1) 853: @output_tabs += 1 854: push_and_tabulate([:comment, !conditional.nil?]) 855: unless line.empty? 856: push_text(line) 857: close 858: end 859: end
Renders a line that creates an XHTML tag and has an implicit div because of `.` or `#`.
# File lib/haml/precompiler.rb, line 831 831: def render_div(line) 832: render_tag('%div' + line) 833: end
Renders an XHTML doctype or XML shebang.
# File lib/haml/precompiler.rb, line 862 862: def render_doctype(line) 863: raise SyntaxError.new("Illegal nesting: nesting within a header command is illegal.", @next_line.index) if block_opened? 864: doctype = text_for_doctype(line) 865: push_text doctype if doctype 866: end
Parses a line that will render as an XHTML tag, and adds the code that will render that tag to `@precompiled`.
# File lib/haml/precompiler.rb, line 697 697: def render_tag(line) 698: tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, 699: nuke_inner_whitespace, action, value, last_line = parse_tag(line) 700: 701: raise SyntaxError.new("Illegal element: classes and ids must have values.") if attributes =~ /[\.#](\.|#|\z)/ 702: 703: # Get rid of whitespace outside of the tag if we need to 704: rstrip_buffer! if nuke_outer_whitespace 705: 706: preserve_tag = options[:preserve].include?(tag_name) 707: nuke_inner_whitespace ||= preserve_tag 708: preserve_tag &&= !options[:ugly] 709: 710: escape_html = (action == '&' || (action != '!' && @options[:escape_html])) 711: 712: case action 713: when '/'; self_closing = true 714: when '~'; parse = preserve_script = true 715: when '=' 716: parse = true 717: if value[0] == ?= 718: value = unescape_interpolation(value[1..-1].strip, :escape_html => escape_html) 719: escape_html = false 720: end 721: when '&', '!' 722: if value[0] == ?= || value[0] == ?~ 723: parse = true 724: preserve_script = (value[0] == ?~) 725: if value[1] == ?= 726: value = unescape_interpolation(value[2..-1].strip, :escape_html => escape_html) 727: escape_html = false 728: else 729: value = value[1..-1].strip 730: end 731: elsif contains_interpolation?(value) 732: value = unescape_interpolation(value, :escape_html => escape_html) 733: parse = true 734: escape_html = false 735: end 736: else 737: if contains_interpolation?(value) 738: value = unescape_interpolation(value, :escape_html => escape_html) 739: parse = true 740: escape_html = false 741: end 742: end 743: 744: if parse && @options[:suppress_eval] 745: parse = false 746: value = '' 747: end 748: 749: object_ref = "nil" if object_ref.nil? || @options[:suppress_eval] 750: 751: attributes = Precompiler.parse_class_and_id(attributes) 752: attributes_hashes.map! do |syntax, attributes_hash| 753: if syntax == :old 754: static_attributes = parse_static_hash(attributes_hash) 755: attributes_hash = nil if static_attributes || @options[:suppress_eval] 756: else 757: static_attributes, attributes_hash = attributes_hash 758: end 759: Buffer.merge_attrs(attributes, static_attributes) if static_attributes 760: attributes_hash 761: end.compact! 762: 763: raise SyntaxError.new("Illegal nesting: nesting within a self-closing tag is illegal.", @next_line.index) if block_opened? && self_closing 764: raise SyntaxError.new("There's no Ruby code for #{action} to evaluate.", last_line - 1) if parse && value.empty? 765: raise SyntaxError.new("Self-closing tags can't have content.", last_line - 1) if self_closing && !value.empty? 766: 767: if block_opened? && !value.empty? && !is_ruby_multiline?(value) 768: raise SyntaxError.new("Illegal nesting: content can't be both given on the same line as %#{tag_name} and nested within it.", @next_line.index) 769: end 770: 771: self_closing ||= !!(!block_opened? && value.empty? && @options[:autoclose].any? {|t| t === tag_name}) 772: value = nil if value.empty? && (block_opened? || self_closing) 773: 774: dont_indent_next_line = 775: (nuke_outer_whitespace && !block_opened?) || 776: (nuke_inner_whitespace && block_opened?) 777: 778: # Check if we can render the tag directly to text and not process it in the buffer 779: if object_ref == "nil" && attributes_hashes.empty? && !preserve_script 780: tag_closed = !block_opened? && !self_closing && !parse 781: 782: open_tag = prerender_tag(tag_name, self_closing, attributes) 783: if tag_closed 784: open_tag << "#{value}</#{tag_name}>" 785: open_tag << "\n" unless nuke_outer_whitespace 786: else 787: open_tag << "\n" unless parse || nuke_inner_whitespace || (self_closing && nuke_outer_whitespace) 788: end 789: 790: push_merged_text(open_tag, tag_closed || self_closing || nuke_inner_whitespace ? 0 : 1, 791: !nuke_outer_whitespace) 792: 793: @dont_indent_next_line = dont_indent_next_line 794: return if tag_closed 795: else 796: flush_merged_text 797: content = parse ? 'nil' : value.inspect 798: if attributes_hashes.empty? 799: attributes_hashes = '' 800: elsif attributes_hashes.size == 1 801: attributes_hashes = ", #{attributes_hashes.first}" 802: else 803: attributes_hashes = ", (#{attributes_hashes.join(").merge(")})" 804: end 805: 806: args = [tag_name, self_closing, !block_opened?, preserve_tag, escape_html, 807: attributes, nuke_outer_whitespace, nuke_inner_whitespace 808: ].map { |v| v.inspect }.join(', ') 809: push_silent "_hamlout.open_tag(#{args}, #{object_ref}, #{content}#{attributes_hashes})" 810: @dont_tab_up_next_text = @dont_indent_next_line = dont_indent_next_line 811: end 812: 813: return if self_closing 814: 815: if value.nil? 816: push_and_tabulate([:element, [tag_name, nuke_outer_whitespace, nuke_inner_whitespace]]) 817: @output_tabs += 1 unless nuke_inner_whitespace 818: return 819: end 820: 821: if parse 822: push_script(value, :preserve_script => preserve_script, :in_tag => true, 823: :preserve_tag => preserve_tag, :escape_html => escape_html, 824: :nuke_inner_whitespace => nuke_inner_whitespace) 825: concat_merged_text("</#{tag_name}>" + (nuke_outer_whitespace ? "" : "\n")) 826: end 827: end
# File lib/haml/precompiler.rb, line 1058 1058: def resolve_newlines 1059: return unless @newlines > 0 1060: @to_merge << [:newlines, @newlines] 1061: @newlines = 0 1062: end
Get rid of and whitespace at the end of the buffer or the merged text
# File lib/haml/precompiler.rb, line 1066 1066: def rstrip_buffer!(index = -1) 1067: last = @to_merge[index] 1068: if last.nil? 1069: push_silent("_hamlout.rstrip!", false) 1070: @dont_tab_up_next_text = true 1071: return 1072: end 1073: 1074: case last.first 1075: when :text 1076: last[1].rstrip! 1077: if last[1].empty? 1078: @to_merge.slice! index 1079: rstrip_buffer! index 1080: end 1081: when :script 1082: last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);') 1083: rstrip_buffer! index - 1 1084: when :newlines 1085: rstrip_buffer! index - 1 1086: else 1087: raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Precompiler@to_merge.") 1088: end 1089: end
Starts a filtered block.
# File lib/haml/precompiler.rb, line 908 908: def start_filtered(name) 909: raise Error.new("Invalid filter name \":#{name}\".") unless name =~ /^\w+$/ 910: raise Error.new("Filter \"#{name}\" is not defined.") unless filter = Filters.defined[name] 911: 912: push_and_tabulate([:filtered, filter]) 913: @flat = true 914: @filter_buffer = String.new 915: 916: # If we don't know the indentation by now, it'll be set in Line#tabs 917: @flat_spaces = @indentation * @template_tabs if @indentation 918: end
# File lib/haml/precompiler.rb, line 417 417: def start_haml_comment 418: return unless block_opened? 419: 420: @haml_comment = true 421: push_and_tabulate([:haml_comment]) 422: end
# File lib/haml/precompiler.rb, line 868 868: def text_for_doctype(text) 869: text = text[3..-1].lstrip.downcase 870: if text.index("xml") == 0 871: return nil if html? 872: wrapper = @options[:attr_wrapper] 873: return "<?xml version=#{wrapper}1.0#{wrapper} encoding=#{wrapper}#{text.split(' ')[1] || "utf-8"}#{wrapper} ?>" 874: end 875: 876: if html5? 877: '<!DOCTYPE html>' 878: else 879: version, type = text.scan(DOCTYPE_REGEX)[0] 880: 881: if xhtml? 882: if version == "1.1" 883: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' 884: elsif version == "5" 885: '<!DOCTYPE html>' 886: else 887: case type 888: when "strict"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' 889: when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' 890: when "mobile"; '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' 891: when "rdfa"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">' 892: when "basic"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">' 893: else '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 894: end 895: end 896: 897: elsif html4? 898: case type 899: when "strict"; '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' 900: when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">' 901: else '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">' 902: end 903: end 904: end 905: end
# File lib/haml/precompiler.rb, line 964 964: def un_next_line(line) 965: @template.unshift line 966: @template_index -= 1 967: end
# File lib/haml/precompiler.rb, line 1012 1012: def unescape_interpolation(str, opts = {}) 1013: res = '' 1014: rest = Haml::Shared.handle_interpolation str.dump do |scan| 1015: escapes = (scan[2].size - 1) / 2 1016: res << scan.matched[0...-3 - escapes] 1017: if escapes % 2 == 1 1018: res << '#{' 1019: else 1020: content = eval('"' + balance(scan, ?{, ?}, 1)[0][0...-1] + '"') 1021: content = "Haml::Helpers.html_escape(#{content})" if opts[:escape_html] 1022: res << '#{' + content + "}"# Use eval to get rid of string escapes 1023: end 1024: end 1025: res + rest 1026: end