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