Module Haml::Precompiler
In: lib/haml/precompiler.rb

Handles the internal pre-compilation from Haml into Ruby code, which then runs the final creation of the HTML string.

Methods

Included Modules

Haml::Util

Classes and Modules

Class Haml::Precompiler::Line

Constants

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

Private Class methods

This is a class method so it can be accessed from Buffer.

[Source]

     # File lib/haml/precompiler.rb, line 514
514:     def self.build_attributes(is_html, attr_wrapper, attributes = {})
515:       quote_escape = attr_wrapper == '"' ? "&quot;" : "&apos;"
516:       other_quote_char = attr_wrapper == '"' ? "'" : '"'
517: 
518:       result = attributes.collect do |attr, value|
519:         next if value.nil?
520: 
521:         if value == true
522:           next " #{attr}" if is_html
523:           next " #{attr}=#{attr_wrapper}#{attr}#{attr_wrapper}"
524:         elsif value == false
525:           next
526:         end
527: 
528:         value = Haml::Helpers.preserve(Haml::Helpers.escape_once(value.to_s))
529:         # We want to decide whether or not to escape quotes
530:         value.gsub!('&quot;', '"')
531:         this_attr_wrapper = attr_wrapper
532:         if value.include? attr_wrapper
533:           if value.include? other_quote_char
534:             value = value.gsub(attr_wrapper, quote_escape)
535:           else
536:             this_attr_wrapper = other_quote_char
537:           end
538:         end
539:         " #{attr}=#{this_attr_wrapper}#{value}#{this_attr_wrapper}"
540:       end
541:       result.compact.sort.join
542:     end

Private Instance methods

[Source]

     # File lib/haml/precompiler.rb, line 985
985:     def balance(*args)
986:       res = Haml::Shared.balance(*args)
987:       return res if res
988:       raise SyntaxError.new("Unbalanced brackets.")
989:     end

[Source]

     # File lib/haml/precompiler.rb, line 991
991:     def block_opened?
992:       !flat? && @next_line.tabs > @line.tabs
993:     end

Closes the most recent item in `@to_close_stack`.

[Source]

     # File lib/haml/precompiler.rb, line 421
421:     def close
422:       tag, *rest = @to_close_stack.pop
423:       send("close_#{tag}", *rest)
424:     end

Closes a comment.

[Source]

     # File lib/haml/precompiler.rb, line 445
445:     def close_comment(has_conditional)
446:       @output_tabs -= 1
447:       @template_tabs -= 1
448:       close_tag = has_conditional ? "<![endif]-->" : "-->"
449:       push_text(close_tag, -1)
450:     end

Puts a line in `@precompiled` that will add the closing tag of the most recently opened tag.

[Source]

     # File lib/haml/precompiler.rb, line 428
428:     def close_element(value)
429:       tag, nuke_outer_whitespace, nuke_inner_whitespace = value
430:       @output_tabs -= 1 unless nuke_inner_whitespace
431:       @template_tabs -= 1
432:       rstrip_buffer! if nuke_inner_whitespace
433:       push_merged_text("</#{tag}>" + (nuke_outer_whitespace ? "" : "\n"),
434:                        nuke_inner_whitespace ? 0 : -1, !nuke_inner_whitespace)
435:       @dont_indent_next_line = nuke_outer_whitespace
436:     end

Closes a filtered block.

[Source]

     # File lib/haml/precompiler.rb, line 461
461:     def close_filtered(filter)
462:       filter.internal_compile(self, @filter_buffer)
463:       @flat = false
464:       @flat_spaces = nil
465:       @filter_buffer = nil
466:       @template_tabs -= 1
467:     end

[Source]

     # File lib/haml/precompiler.rb, line 469
469:     def close_haml_comment
470:       @haml_comment = false
471:       @template_tabs -= 1
472:     end

Closes a loud Ruby block.

[Source]

     # File lib/haml/precompiler.rb, line 453
453:     def close_loud(command, add_newline, push_end = true)
454:       push_silent('end', true) if push_end
455:       @precompiled << command
456:       @template_tabs -= 1
457:       concat_merged_text("\n") if add_newline
458:     end

[Source]

     # File lib/haml/precompiler.rb, line 474
474:     def close_nil(*args)
475:       @template_tabs -= 1
476:     end

Closes a Ruby block.

[Source]

     # File lib/haml/precompiler.rb, line 439
439:     def close_script(_1, _2, push_end = true)
440:       push_silent("end", true) if push_end
441:       @template_tabs -= 1
442:     end

[Source]

     # File lib/haml/precompiler.rb, line 936
936:     def closes_flat?(line)
937:       line && !line.text.empty? && line.full !~ /^#{@flat_spaces}/
938:     end

Concatenate `text` to `@buffer` without tabulation.

[Source]

     # File lib/haml/precompiler.rb, line 308
308:     def concat_merged_text(text)
309:       @to_merge << [:text, text, 0]
310:     end

[Source]

     # File lib/haml/precompiler.rb, line 965
965:     def contains_interpolation?(str)
966:       str.include?('#{')
967:     end

[Source]

      # File lib/haml/precompiler.rb, line 1002
1002:     def flat?
1003:       @flat
1004:     end

[Source]

     # File lib/haml/precompiler.rb, line 316
316:     def flush_merged_text
317:       return if @to_merge.empty?
318: 
319:       text, tab_change = @to_merge.inject(["", 0]) do |(str, mtabs), (type, val, tabs)|
320:         case type
321:         when :text
322:           [str << val.inspect[1...-1], mtabs + tabs]
323:         when :script
324:           if mtabs != 0 && !@options[:ugly]
325:             val = "_hamlout.adjust_tabs(#{mtabs}); " + val
326:           end
327:           [str << "\#{#{val}}", 0]
328:         else
329:           raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Precompiler@to_merge.")
330:         end
331:       end
332: 
333:       @precompiled <<
334:         if @options[:ugly]
335:           "_hamlout.buffer << \"#{text}\";"
336:         else
337:           "_hamlout.push_text(\"#{text}\", #{tab_change}, #{@dont_tab_up_next_text.inspect});"
338:         end
339:       @to_merge = []
340:       @dont_tab_up_next_text = false
341:     end

[Source]

     # File lib/haml/precompiler.rb, line 945
945:     def handle_multiline(line)
946:       if is_multiline?(line.text)
947:         line.text.slice!(-1)
948:         while new_line = raw_next_line.first
949:           break if new_line == :eod
950:           newline and next if new_line.strip.empty?
951:           break unless is_multiline?(new_line.strip)
952:           line.text << new_line.strip[0...-1]
953:           newline
954:         end
955:         un_next_line new_line
956:         resolve_newlines
957:       end
958:     end

Checks whether or not line is in a multiline sequence.

[Source]

     # File lib/haml/precompiler.rb, line 961
961:     def is_multiline?(text)
962:       text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s
963:     end

[Source]

     # 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.

[Source]

     # File lib/haml/precompiler.rb, line 287
287:     def mid_block_keyword?(text)
288:       text[MID_BLOCK_KEYWORD_REGEX, 1]
289:     end

[Source]

      # File lib/haml/precompiler.rb, line 1006
1006:     def newline
1007:       @newlines += 1
1008:     end

[Source]

      # File lib/haml/precompiler.rb, line 1010
1010:     def newline_now
1011:       @precompiled << "\n"
1012:       @newlines -= 1
1013:     end

[Source]

     # File lib/haml/precompiler.rb, line 906
906:     def next_line
907:       text, index = raw_next_line
908:       return unless text
909: 
910:       # :eod is a special end-of-document marker
911:       line =
912:         if text == :eod
913:           Line.new '-#', '-#', '-#', index, self, true
914:         else
915:           Line.new text.strip, text.lstrip.chomp, text, index, self, false
916:         end
917: 
918:       # `flat?' here is a little outdated,
919:       # so we have to manually check if either the previous or current line
920:       # closes the flat block,
921:       # as well as whether a new block is opened
922:       @line.tabs if @line
923:       unless (flat? && !closes_flat?(line) && !closes_flat?(@line)) ||
924:           (@line && @line.text[0] == ?: && line.full =~ %r[^#{@line.full[/^\s+/]}\s])
925:         if line.text.empty?
926:           newline
927:           return next_line
928:         end
929: 
930:         handle_multiline(line)
931:       end
932: 
933:       @next_line = line
934:     end

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.

[Source]

     # File lib/haml/precompiler.rb, line 481
481:     def parse_class_and_id(list)
482:       attributes = {}
483:       list.scan(/([#.])([-_a-zA-Z0-9]+)/) do |type, property|
484:         case type
485:         when '.'
486:           if attributes['class']
487:             attributes['class'] += " "
488:           else
489:             attributes['class'] = ""
490:           end
491:           attributes['class'] += property
492:         when '#'; attributes['id'] = property
493:         end
494:       end
495:       attributes
496:     end

[Source]

     # File lib/haml/precompiler.rb, line 646
646:     def parse_new_attribute(scanner)
647:       unless name = scanner.scan(/[-:\w]+/)
648:         return if scanner.scan(/\)/)
649:         return false
650:       end
651: 
652:       scanner.scan(/\s*/)
653:       return name, [:static, true] unless scanner.scan(/=/) #/end
654: 
655:       scanner.scan(/\s*/)
656:       unless quote = scanner.scan(/["']/)
657:         return false unless var = scanner.scan(/(@@?|\$)?\w+/)
658:         return name, [:dynamic, var]
659:       end
660: 
661:       re = /((?:\\.|\#[^{]|[^#{quote}\\#])*#?)(#{quote}|#\{)/
662:       content = []
663:       loop do
664:         return false unless scanner.scan(re)
665:         content << [:str, scanner[1].gsub(/\\(.)/, '\1')]
666:         break if scanner[2] == quote
667:         content << [:ruby, balance(scanner, ?{, ?}, 1).first[0...-1]]
668:       end
669: 
670:       return name, [:static, content.first[1]] if content.size == 1
671:       return name, [:dynamic,
672:         '"' + content.map {|(t, v)| t == :str ? v.inspect[1...-1] : "\#{#{v}}"}.join + '"']
673:     end

[Source]

     # File lib/haml/precompiler.rb, line 605
605:     def parse_new_attributes(line)
606:       line = line.dup
607:       scanner = StringScanner.new(line)
608:       last_line = @index
609:       attributes = {}
610: 
611:       scanner.scan(/\(\s*/)
612:       loop do
613:         name, value = parse_new_attribute(scanner)
614:         break if name.nil?
615: 
616:         if name == false
617:           text = (Haml::Shared.balance(line, ?(, ?)) || [line]).first
618:           raise Haml::SyntaxError.new("Invalid attribute list: #{text.inspect}.", last_line - 1)
619:         end
620:         attributes[name] = value
621:         scanner.scan(/\s*/)
622: 
623:         if scanner.eos?
624:           line << " " << @next_line.text
625:           last_line += 1
626:           next_line
627:           scanner.scan(/\s*/)
628:         end
629:       end
630: 
631:       static_attributes = {}
632:       dynamic_attributes = "{"
633:       attributes.each do |name, (type, val)|
634:         if type == :static
635:           static_attributes[name] = val
636:         else
637:           dynamic_attributes << name.inspect << " => " << val << ","
638:         end
639:       end
640:       dynamic_attributes << "}"
641:       dynamic_attributes = nil if dynamic_attributes == "{}"
642: 
643:       return [static_attributes, dynamic_attributes], scanner.rest, last_line
644:     end

[Source]

     # File lib/haml/precompiler.rb, line 584
584:     def parse_old_attributes(line)
585:       line = line.dup
586:       last_line = @index
587: 
588:       begin
589:         attributes_hash, rest = balance(line, ?{, ?})
590:       rescue SyntaxError => e
591:         if line.strip[-1] == ?, && e.message == "Unbalanced brackets."
592:           line << "\n" << @next_line.text
593:           last_line += 1
594:           next_line
595:           retry
596:         end
597: 
598:         raise e
599:       end
600: 
601:       attributes_hash = attributes_hash[1...-1] if attributes_hash
602:       return attributes_hash, rest, last_line
603:     end

[Source]

     # File lib/haml/precompiler.rb, line 498
498:     def parse_static_hash(text)
499:       attributes = {}
500:       scanner = StringScanner.new(text)
501:       scanner.scan(/\s+/)
502:       until scanner.eos?
503:         return unless key = scanner.scan(LITERAL_VALUE_REGEX)
504:         return unless scanner.scan(/\s*=>\s*/)
505:         return unless value = scanner.scan(LITERAL_VALUE_REGEX)
506:         return unless scanner.scan(/\s*(?:,|$)\s*/)
507:         attributes[eval(key).to_s] = eval(value).to_s
508:       end
509:       text.count("\n").times { newline }
510:       attributes
511:     end

Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value

[Source]

     # File lib/haml/precompiler.rb, line 550
550:     def parse_tag(line)
551:       raise SyntaxError.new("Invalid tag: \"#{line}\".") unless match = line.scan(/%([-:\w]+)([-\w\.\#]*)(.*)/)[0]
552:       tag_name, attributes, rest = match
553:       new_attributes_hash = old_attributes_hash = last_line = object_ref = nil
554:       attributes_hashes = []
555:       while rest
556:         case rest[0]
557:         when ?{
558:           break if old_attributes_hash
559:           old_attributes_hash, rest, last_line = parse_old_attributes(rest)
560:           attributes_hashes << [:old, old_attributes_hash]
561:         when ?(
562:           break if new_attributes_hash
563:           new_attributes_hash, rest, last_line = parse_new_attributes(rest)
564:           attributes_hashes << [:new, new_attributes_hash]
565:         when ?[
566:           break if object_ref
567:           object_ref, rest = balance(rest, ?[, ?])
568:         else; break
569:         end
570:       end
571: 
572:       if rest
573:         nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0]
574:         nuke_whitespace ||= ''
575:         nuke_outer_whitespace = nuke_whitespace.include? '>'
576:         nuke_inner_whitespace = nuke_whitespace.include? '<'
577:       end
578: 
579:       value = value.to_s.strip
580:       [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
581:        nuke_inner_whitespace, action, value, last_line || @index]
582:     end

[Source]

     # File lib/haml/precompiler.rb, line 161
161:     def precompile
162:       @haml_comment = @dont_indent_next_line = @dont_tab_up_next_text = false
163:       @indentation = nil
164:       @line = next_line
165:       resolve_newlines
166:       newline
167: 
168:       raise SyntaxError.new("Indenting at the beginning of the document is illegal.", @line.index) if @line.tabs != 0
169: 
170:       while next_line
171:         process_indent(@line) unless @line.text.empty?
172: 
173:         if flat?
174:           push_flat(@line)
175:           @line = @next_line
176:           newline
177:           next
178:         end
179: 
180:         process_line(@line.text, @line.index) unless @line.text.empty? || @haml_comment
181: 
182:         if !flat? && @next_line.tabs - @line.tabs > 1
183:           raise SyntaxError.new("The line was indented #{@next_line.tabs - @line.tabs} levels deeper than the previous line.", @next_line.index)
184:         end
185: 
186:         resolve_newlines unless @next_line.eod?
187:         @line = @next_line
188:         newline unless @next_line.eod?
189:       end
190: 
191:       # Close all the open tags
192:       close until @to_close_stack.empty?
193:       flush_merged_text
194:     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.

[Source]

     # 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

[Source]

    # 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

[Source]

     # File lib/haml/precompiler.rb, line 544
544:     def prerender_tag(name, self_close, attributes)
545:       attributes_string = Precompiler.build_attributes(html?, @options[:attr_wrapper], attributes)
546:       "<#{name}#{attributes_string}#{self_close && xhtml? ? ' /' : ''}>"
547:     end

Processes and deals with lowering indentation.

[Source]

     # File lib/haml/precompiler.rb, line 197
197:     def process_indent(line)
198:       return unless line.tabs <= @template_tabs && @template_tabs > 0
199: 
200:       to_close = @template_tabs - line.tabs
201:       to_close.times {|i| close unless to_close - 1 - i == 0 && mid_block_keyword?(line.text)}
202:     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`.

[Source]

     # File lib/haml/precompiler.rb, line 208
208:     def process_line(text, index)
209:       @index = index + 1
210: 
211:       case text[0]
212:       when DIV_CLASS; render_div(text)
213:       when DIV_ID
214:         return push_plain(text) if text[1] == ?{
215:         render_div(text)
216:       when ELEMENT; render_tag(text)
217:       when COMMENT; render_comment(text[1..-1].strip)
218:       when SANITIZE
219:         return push_plain(text[3..-1].strip, :escape_html => true) if text[1..2] == "=="
220:         return push_script(text[2..-1].strip, :escape_html => true) if text[1] == SCRIPT
221:         return push_flat_script(text[2..-1].strip, :escape_html => true) if text[1] == FLAT_SCRIPT
222:         return push_plain(text[1..-1].strip, :escape_html => true) if text[1] == ?\s
223:         push_plain text
224:       when SCRIPT
225:         return push_plain(text[2..-1].strip) if text[1] == SCRIPT
226:         push_script(text[1..-1])
227:       when FLAT_SCRIPT; push_flat_script(text[1..-1])
228:       when SILENT_SCRIPT
229:         return start_haml_comment if text[1] == SILENT_COMMENT
230: 
231:         raise SyntaxError.new("You don't need to use \"- end\" in Haml. Use indentation instead:\n- if foo?\n  %strong Foo!\n- else\n  Not foo.\n".rstrip, index) if text[1..-1].strip == "end"
232: 
233:         push_silent(text[1..-1], true)
234:         newline_now
235: 
236:         # Handle stuff like - end.join("|")
237:         @to_close_stack.last << false if text =~ /^-\s*end\b/ && !block_opened?
238: 
239:         case_stmt = text =~ /^-\s*case\b/
240:         keyword = mid_block_keyword?(text)
241:         block = block_opened? && !keyword
242: 
243:         # It's important to preserve tabulation modification for keywords
244:         # that involve choosing between posible blocks of code.
245:         if %w[else elsif when].include?(keyword)
246:           # @to_close_stack may not have a :script on top
247:           # when the preceding "- if" has nothing nested
248:           if @to_close_stack.last && @to_close_stack.last.first == :script
249:             @dont_indent_next_line, @dont_tab_up_next_text = @to_close_stack.last[1..2]
250:           else
251:             push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text])
252:           end
253: 
254:           # when is unusual in that either it will be indented twice,
255:           # or the case won't have created its own indentation
256:           if keyword == "when"
257:             push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text, false])
258:           end
259:         elsif block || case_stmt
260:           push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text])
261:         elsif block && case_stmt
262:           push_and_tabulate([:script, @dont_indent_next_line, @dont_tab_up_next_text])
263:         end
264:       when FILTER; start_filtered(text[1..-1].downcase)
265:       when DOCTYPE
266:         return render_doctype(text) if text[0...3] == '!!!'
267:         return push_plain(text[3..-1].strip, :escape_html => false) if text[1..2] == "=="
268:         return push_script(text[2..-1].strip, :escape_html => false) if text[1] == SCRIPT
269:         return push_flat_script(text[2..-1].strip, :escape_html => false) if text[1] == FLAT_SCRIPT
270:         return push_plain(text[1..-1].strip, :escape_html => false) if text[1] == ?\s
271:         push_plain text
272:       when ESCAPE; push_plain text[1..-1]
273:       else push_plain text
274:       end
275:     end

Pushes value onto `@to_close_stack` and increases `@template_tabs`.

[Source]

      # File lib/haml/precompiler.rb, line 997
 997:     def push_and_tabulate(value)
 998:       @to_close_stack.push(value)
 999:       @template_tabs += 1
1000:     end

Adds text to `@buffer` while flattening text.

[Source]

     # File lib/haml/precompiler.rb, line 361
361:     def push_flat(line)
362:       text = line.full.dup
363:       text = "" unless text.gsub!(/^#{@flat_spaces}/, '')
364:       @filter_buffer << "#{text}\n"
365:     end

Causes `text` to be evaluated, and Haml::Helpers#find_and_flatten to be run on it afterwards.

[Source]

     # File lib/haml/precompiler.rb, line 406
406:     def push_flat_script(text, options = {})
407:       flush_merged_text
408: 
409:       raise SyntaxError.new("There's no Ruby code for ~ to evaluate.") if text.empty?
410:       push_script(text, options.merge(:preserve_script => true))
411:     end

Adds `text` to `@buffer` with appropriate tabulation without parsing it.

[Source]

     # File lib/haml/precompiler.rb, line 301
301:     def push_merged_text(text, tab_change = 0, indent = true)
302:       text = !indent || @dont_indent_next_line || @options[:ugly] ? text : "#{'  ' * @output_tabs}#{text}"
303:       @to_merge << [:text, text, tab_change]
304:       @dont_indent_next_line = false
305:     end

Renders a block of text as plain text. Also checks for an illegally opened block.

[Source]

     # File lib/haml/precompiler.rb, line 345
345:     def push_plain(text, options = {})
346:       if block_opened?
347:         raise SyntaxError.new("Illegal nesting: nesting within plain text is illegal.", @next_line.index)
348:       end
349: 
350:       if contains_interpolation?(text)
351:         options[:escape_html] = self.options[:escape_html] if options[:escape_html].nil?
352:         push_script(
353:           unescape_interpolation(text, :escape_html => options[:escape_html]),
354:           :escape_html => false)
355:       else
356:         push_text text
357:       end
358:     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`

[Source]

     # File lib/haml/precompiler.rb, line 372
372:     def push_script(text, opts = {})
373:       raise SyntaxError.new("There's no Ruby code for = to evaluate.") if text.empty?
374:       return if options[:suppress_eval]
375:       opts[:escape_html] = options[:escape_html] if opts[:escape_html].nil?
376: 
377:       args = %w[preserve_script in_tag preserve_tag escape_html nuke_inner_whitespace]
378:       args.map! {|name| opts[name.to_sym]}
379:       args << !block_opened? << @options[:ugly]
380: 
381:       no_format = @options[:ugly] &&
382:         !(opts[:preserve_script] || opts[:preserve_tag] || opts[:escape_html])
383:       output_temp = "(haml_very_temp = haml_temp; haml_temp = nil; haml_very_temp)"
384:       out = "_hamlout.#{static_method_name(:format_script, *args)}(#{output_temp});"
385: 
386:       # Prerender tabulation unless we're in a tag
387:       push_merged_text '' unless opts[:in_tag]
388: 
389:       unless block_opened?
390:         @to_merge << [:script, no_format ? "#{text}\n" : "haml_temp = #{text}\n#{out}"]
391:         concat_merged_text("\n") unless opts[:in_tag] || opts[:nuke_inner_whitespace]
392:         @newlines -= 1
393:         return
394:       end
395: 
396:       flush_merged_text
397: 
398:       push_silent "haml_temp = #{text}"
399:       newline_now
400:       push_and_tabulate([:loud, "_hamlout.buffer << #{no_format ? "#{output_temp}.to_s;" : out}",
401:         !(opts[:in_tag] || opts[:nuke_inner_whitespace] || @options[:ugly])])
402:     end

Evaluates `text` in the context of the scope object, but does not output the result.

[Source]

     # File lib/haml/precompiler.rb, line 293
293:     def push_silent(text, can_suppress = false)
294:       flush_merged_text
295:       return if can_suppress && options[:suppress_eval]
296:       @precompiled << "#{text};"
297:     end

[Source]

     # File lib/haml/precompiler.rb, line 312
312:     def push_text(text, tab_change = 0)
313:       push_merged_text("#{text}\n", tab_change)
314:     end

[Source]

     # File lib/haml/precompiler.rb, line 896
896:     def raw_next_line
897:       text = @template.shift
898:       return unless text
899: 
900:       index = @template_index
901:       @template_index += 1
902: 
903:       return text, index
904:     end

Renders an XHTML comment.

[Source]

     # File lib/haml/precompiler.rb, line 813
813:     def render_comment(line)
814:       conditional, line = balance(line, ?[, ?]) if line[0] == ?[
815:       line.strip!
816:       conditional << ">" if conditional
817: 
818:       if block_opened? && !line.empty?
819:         raise SyntaxError.new('Illegal nesting: nesting within a tag that already has content is illegal.', @next_line.index)
820:       end
821: 
822:       open = "<!--#{conditional}"
823: 
824:       # Render it statically if possible
825:       unless line.empty?
826:         return push_text("#{open} #{line} #{conditional ? "<![endif]-->" : "-->"}")
827:       end
828: 
829:       push_text(open, 1)
830:       @output_tabs += 1
831:       push_and_tabulate([:comment, !conditional.nil?])
832:       unless line.empty?
833:         push_text(line)
834:         close
835:       end
836:     end

Renders a line that creates an XHTML tag and has an implicit div because of `.` or `#`.

[Source]

     # File lib/haml/precompiler.rb, line 808
808:     def render_div(line)
809:       render_tag('%div' + line)
810:     end

Renders an XHTML doctype or XML shebang.

[Source]

     # File lib/haml/precompiler.rb, line 839
839:     def render_doctype(line)
840:       raise SyntaxError.new("Illegal nesting: nesting within a header command is illegal.", @next_line.index) if block_opened?
841:       doctype = text_for_doctype(line)
842:       push_text doctype if doctype
843:     end

Parses a line that will render as an XHTML tag, and adds the code that will render that tag to `@precompiled`.

[Source]

     # File lib/haml/precompiler.rb, line 677
677:     def render_tag(line)
678:       tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
679:         nuke_inner_whitespace, action, value, last_line = parse_tag(line)
680: 
681:       raise SyntaxError.new("Illegal element: classes and ids must have values.") if attributes =~ /[\.#](\.|#|\z)/
682: 
683:       # Get rid of whitespace outside of the tag if we need to
684:       rstrip_buffer! if nuke_outer_whitespace
685: 
686:       preserve_tag = options[:preserve].include?(tag_name)
687:       nuke_inner_whitespace ||= preserve_tag
688:       preserve_tag &&= !options[:ugly]
689: 
690:       escape_html = (action == '&' || (action != '!' && @options[:escape_html]))
691: 
692:       case action
693:       when '/'; self_closing = true
694:       when '~'; parse = preserve_script = true
695:       when '='
696:         parse = true
697:         if value[0] == ?=
698:           value = unescape_interpolation(value[1..-1].strip, :escape_html => escape_html)
699:           escape_html = false
700:         end
701:       when '&', '!'
702:         if value[0] == ?= || value[0] == ?~
703:           parse = true
704:           preserve_script = (value[0] == ?~)
705:           if value[1] == ?=
706:             value = unescape_interpolation(value[2..-1].strip, :escape_html => escape_html)
707:             escape_html = false
708:           else
709:             value = value[1..-1].strip
710:           end
711:         elsif contains_interpolation?(value)
712:           value = unescape_interpolation(value, :escape_html => escape_html)
713:           parse = true
714:           escape_html = false
715:         end
716:       else
717:         if contains_interpolation?(value)
718:           value = unescape_interpolation(value, :escape_html => escape_html)
719:           parse = true
720:           escape_html = false
721:         end
722:       end
723: 
724:       if parse && @options[:suppress_eval]
725:         parse = false
726:         value = ''
727:       end
728: 
729:       object_ref = "nil" if object_ref.nil? || @options[:suppress_eval]
730: 
731:       attributes = parse_class_and_id(attributes)
732:       attributes_hashes.map! do |syntax, attributes_hash|
733:         if syntax == :old
734:           static_attributes = parse_static_hash(attributes_hash)
735:           attributes_hash = nil if static_attributes || @options[:suppress_eval]
736:         else
737:           static_attributes, attributes_hash = attributes_hash
738:         end
739:         Buffer.merge_attrs(attributes, static_attributes) if static_attributes
740:         attributes_hash
741:       end.compact!
742: 
743:       raise SyntaxError.new("Illegal nesting: nesting within a self-closing tag is illegal.", @next_line.index) if block_opened? && self_closing
744:       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) if block_opened? && !value.empty?
745:       raise SyntaxError.new("There's no Ruby code for #{action} to evaluate.", last_line - 1) if parse && value.empty?
746:       raise SyntaxError.new("Self-closing tags can't have content.", last_line - 1) if self_closing && !value.empty?
747: 
748:       self_closing ||= !!( !block_opened? && value.empty? && @options[:autoclose].include?(tag_name) )
749:       value = nil if value.empty? && (block_opened? || self_closing)
750: 
751:       dont_indent_next_line =
752:         (nuke_outer_whitespace && !block_opened?) ||
753:         (nuke_inner_whitespace && block_opened?)
754: 
755:       # Check if we can render the tag directly to text and not process it in the buffer
756:       if object_ref == "nil" && attributes_hashes.empty? && !preserve_script
757:         tag_closed = !block_opened? && !self_closing && !parse
758: 
759:         open_tag  = prerender_tag(tag_name, self_closing, attributes)
760:         if tag_closed
761:           open_tag << "#{value}</#{tag_name}>"
762:           open_tag << "\n" unless nuke_outer_whitespace
763:         else
764:           open_tag << "\n" unless parse || nuke_inner_whitespace || (self_closing && nuke_outer_whitespace)
765:         end
766: 
767:         push_merged_text(open_tag, tag_closed || self_closing || nuke_inner_whitespace ? 0 : 1,
768:                          !nuke_outer_whitespace)
769: 
770:         @dont_indent_next_line = dont_indent_next_line
771:         return if tag_closed
772:       else
773:         flush_merged_text
774:         content = parse ? 'nil' : value.inspect
775:         if attributes_hashes.empty?
776:           attributes_hashes = ''
777:         elsif attributes_hashes.size == 1
778:           attributes_hashes = ", #{attributes_hashes.first}"
779:         else
780:           attributes_hashes = ", (#{attributes_hashes.join(").merge(")})"
781:         end
782: 
783:         args = [tag_name, self_closing, !block_opened?, preserve_tag, escape_html,
784:                 attributes, nuke_outer_whitespace, nuke_inner_whitespace
785:                ].map { |v| v.inspect }.join(', ')
786:         push_silent "_hamlout.open_tag(#{args}, #{object_ref}, #{content}#{attributes_hashes})"
787:         @dont_tab_up_next_text = @dont_indent_next_line = dont_indent_next_line
788:       end
789: 
790:       return if self_closing
791: 
792:       if value.nil?
793:         push_and_tabulate([:element, [tag_name, nuke_outer_whitespace, nuke_inner_whitespace]])
794:         @output_tabs += 1 unless nuke_inner_whitespace
795:         return
796:       end
797: 
798:       if parse
799:         push_script(value, :preserve_script => preserve_script, :in_tag => true,
800:           :preserve_tag => preserve_tag, :escape_html => escape_html,
801:           :nuke_inner_whitespace => nuke_inner_whitespace)
802:         concat_merged_text("</#{tag_name}>" + (nuke_outer_whitespace ? "" : "\n"))
803:       end
804:     end

[Source]

      # File lib/haml/precompiler.rb, line 1015
1015:     def resolve_newlines
1016:       return unless @newlines > 0
1017:       flush_merged_text unless @to_merge.all? {|type, *_| type == :text}
1018:       @precompiled << "\n" * @newlines
1019:       @newlines = 0
1020:     end

Get rid of and whitespace at the end of the buffer or the merged text

[Source]

      # File lib/haml/precompiler.rb, line 1024
1024:     def rstrip_buffer!(index = -1)
1025:       last = @to_merge[index]
1026:       if last.nil?
1027:         push_silent("_hamlout.rstrip!", false)
1028:         @dont_tab_up_next_text = true
1029:         return
1030:       end
1031: 
1032:       case last.first
1033:       when :text
1034:         last[1].rstrip!
1035:         if last[1].empty?
1036:           @to_merge.slice! index
1037:           rstrip_buffer! index
1038:         end
1039:       when :script
1040:         last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);')
1041:         rstrip_buffer! index - 1
1042:       else
1043:         raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Precompiler@to_merge.")
1044:       end
1045:     end

Starts a filtered block.

[Source]

     # File lib/haml/precompiler.rb, line 884
884:     def start_filtered(name)
885:       raise Error.new("Invalid filter name \":#{name}\".") unless name =~ /^\w+$/
886:       raise Error.new("Filter \"#{name}\" is not defined.") unless filter = Filters.defined[name]
887: 
888:       push_and_tabulate([:filtered, filter])
889:       @flat = true
890:       @filter_buffer = String.new
891: 
892:       # If we don't know the indentation by now, it'll be set in Line#tabs
893:       @flat_spaces = @indentation * @template_tabs if @indentation
894:     end

[Source]

     # File lib/haml/precompiler.rb, line 413
413:     def start_haml_comment
414:       return unless block_opened?
415: 
416:       @haml_comment = true
417:       push_and_tabulate([:haml_comment])
418:     end

[Source]

     # File lib/haml/precompiler.rb, line 845
845:     def text_for_doctype(text)
846:       text = text[3..-1].lstrip.downcase
847:       if text.index("xml") == 0
848:         return nil if html?
849:         wrapper = @options[:attr_wrapper]
850:         return "<?xml version=#{wrapper}1.0#{wrapper} encoding=#{wrapper}#{text.split(' ')[1] || "utf-8"}#{wrapper} ?>"
851:       end
852: 
853:       if html5?
854:         '<!DOCTYPE html>'
855:       else
856:         version, type = text.scan(DOCTYPE_REGEX)[0]
857: 
858:         if xhtml?
859:           if version == "1.1"
860:             '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
861:           elsif version == "5"
862:             '<!DOCTYPE html>'
863:           else
864:             case type
865:             when "strict";   '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
866:             when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">'
867:             when "mobile";   '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">'
868:             when "basic";    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">'
869:             else             '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
870:             end
871:           end
872: 
873:         elsif html4?
874:           case type
875:           when "strict";   '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
876:           when "frameset"; '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'
877:           else             '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'
878:           end
879:         end
880:       end
881:     end

[Source]

     # File lib/haml/precompiler.rb, line 940
940:     def un_next_line(line)
941:       @template.unshift line
942:       @template_index -= 1
943:     end

[Source]

     # File lib/haml/precompiler.rb, line 969
969:     def unescape_interpolation(str, opts = {})
970:       res = ''
971:       rest = Haml::Shared.handle_interpolation str.dump do |scan|
972:         escapes = (scan[2].size - 1) / 2
973:         res << scan.matched[0...-3 - escapes]
974:         if escapes % 2 == 1
975:           res << '#{'
976:         else
977:           content = eval('"' + balance(scan, ?{, ?}, 1)[0][0...-1] + '"')
978:           content = "Haml::Helpers.html_escape(#{content})" if opts[:escape_html]
979:           res << '#{' + content + "}"# Use eval to get rid of string escapes
980:         end
981:       end
982:       res + rest
983:     end

[Validate]