` element with the given id.
DIV_ID = ?#
# Designates an XHTML/XML comment.
COMMENT = ?/
# Designates an XHTML doctype or script that is never HTML-escaped.
DOCTYPE = ?!
# Designates script, the result of which is output.
SCRIPT = ?=
# Designates script that is always HTML-escaped.
SANITIZE = ?&
# Designates script, the result of which is flattened and output.
FLAT_SCRIPT = ?~
# Designates script which is run but not output.
SILENT_SCRIPT = ?-
# When following SILENT_SCRIPT, designates a comment that is not output.
SILENT_COMMENT = ?#
# Designates a non-parsed line.
ESCAPE = ?\\
# Designates a block of filtered text.
FILTER = ?:
# Designates a non-parsed line. Not actually a character.
PLAIN_TEXT = -1
# Keeps track of the ASCII values of the characters that begin a
# specially-interpreted line.
SPECIAL_CHARACTERS = [
ELEMENT,
DIV_CLASS,
DIV_ID,
COMMENT,
DOCTYPE,
SCRIPT,
SANITIZE,
FLAT_SCRIPT,
SILENT_SCRIPT,
ESCAPE,
FILTER
]
# The value of the character that designates that a line is part
# of a multiline string.
MULTILINE_CHAR_VALUE = ?|
# Regex to check for blocks with spaces around arguments. Not to be confused
# with multiline script.
# For example:
# foo.each do | bar |
# = bar
#
BLOCK_WITH_SPACES = /do[\s]*\|[\s]*[^\|]*[\s]+\|\z/
MID_BLOCK_KEYWORDS = %w[else elsif rescue ensure end when]
START_BLOCK_KEYWORDS = %w[if begin case unless]
# Try to parse assignments to block starters as best as possible
START_BLOCK_KEYWORD_REGEX = /(?:\w+(?:,\s*\w+)*\s*=\s*)?(#{START_BLOCK_KEYWORDS.join('|')})/
BLOCK_KEYWORD_REGEX = /^-?\s*(?:(#{MID_BLOCK_KEYWORDS.join('|')})|#{START_BLOCK_KEYWORD_REGEX.source})\b/
# The Regex that matches a Doctype command.
DOCTYPE_REGEX = /(\d(?:\.\d)?)?[\s]*([a-z]*)\s*([^ ]+)?/i
# The Regex that matches a literal string or symbol value
LITERAL_VALUE_REGEX = /:(\w*)|(["'])((?!\\|\#\{|\#@|\#\$|\2).|\\.)*\2/
def initialize(template, options)
# :eod is a special end-of-document marker
@template = (template.rstrip).split(/\r\n|\r|\n/) + [:eod, :eod]
@options = options
@flat = false
@index = 0
# Record the indent levels of "if" statements to validate the subsequent
# elsif and else statements are indented at the appropriate level.
@script_level_stack = []
@template_index = 0
@template_tabs = 0
end
def parse
@root = @parent = ParseNode.new(:root)
@haml_comment = false
@indentation = nil
@line = next_line
raise SyntaxError.new(Error.message(:indenting_at_start), @line.index) if @line.tabs != 0
while next_line
process_indent(@line) unless @line.text.empty?
if flat?
text = @line.full.dup
text = "" unless text.gsub!(/^#{@flat_spaces}/, '')
@filter_buffer << "#{text}\n"
@line = @next_line
next
end
@tab_up = nil
process_line(@line.text, @line.index) unless @line.text.empty? || @haml_comment
if @parent.type != :haml_comment && (block_opened? || @tab_up)
@template_tabs += 1
@parent = @parent.children.last
end
if !@haml_comment && !flat? && @next_line.tabs - @line.tabs > 1
raise SyntaxError.new(Error.message(:deeper_indenting, @next_line.tabs - @line.tabs), @next_line.index)
end
@line = @next_line
end
# Close all the open tags
close until @parent.type == :root
@root
rescue Haml::Error => e
e.backtrace.unshift "#{@options[:filename]}:#{(e.line ? e.line + 1 : @index) + @options[:line] - 1}"
raise
end
private
# @private
class Line < Struct.new(:text, :unstripped, :full, :index, :compiler, :eod)
alias_method :eod?, :eod
# @private
def tabs
line = self
@tabs ||= compiler.instance_eval do
break 0 if line.text.empty? || !(whitespace = line.full[/^\s+/])
if @indentation.nil?
@indentation = whitespace
if @indentation.include?(?\s) && @indentation.include?(?\t)
raise SyntaxError.new(Error.message(:cant_use_tabs_and_spaces), line.index)
end
@flat_spaces = @indentation * (@template_tabs+1) if flat?
break 1
end
tabs = whitespace.length / @indentation.length
break tabs if whitespace == @indentation * tabs
break @template_tabs + 1 if flat? && whitespace =~ /^#{@flat_spaces}/
message = Error.message(:inconsistent_indentation,
Haml::Util.human_indentation(whitespace),
Haml::Util.human_indentation(@indentation)
)
raise SyntaxError.new(message, line.index)
end
end
end
# @private
class ParseNode < Struct.new(:type, :line, :value, :parent, :children)
def initialize(*args)
super
self.children ||= []
end
def inspect
text = "(#{type} #{value.inspect}"
children.each {|c| text << "\n" << c.inspect.gsub(/^/, " ")}
text + ")"
end
end
# Processes and deals with lowering indentation.
def process_indent(line)
return unless line.tabs <= @template_tabs && @template_tabs > 0
to_close = @template_tabs - line.tabs
to_close.times {|i| close unless to_close - 1 - i == 0 && mid_block_keyword?(line.text)}
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`.
def process_line(text, index)
@index = index + 1
case text[0]
when DIV_CLASS; push div(text)
when DIV_ID
return push plain(text) if text[1] == ?{
push div(text)
when ELEMENT; push tag(text)
when COMMENT; push comment(text[1..-1].strip)
when SANITIZE
return push plain(text[3..-1].strip, :escape_html) if text[1..2] == "=="
return push script(text[2..-1].strip, :escape_html) if text[1] == SCRIPT
return push flat_script(text[2..-1].strip, :escape_html) if text[1] == FLAT_SCRIPT
return push plain(text[1..-1].strip, :escape_html) if text[1] == ?\s
push plain(text)
when SCRIPT
return push plain(text[2..-1].strip) if text[1] == SCRIPT
push script(text[1..-1])
when FLAT_SCRIPT; push flat_script(text[1..-1])
when SILENT_SCRIPT; push silent_script(text)
when FILTER; push filter(text[1..-1].downcase)
when DOCTYPE
return push doctype(text) if text[0...3] == '!!!'
return push plain(text[3..-1].strip, false) if text[1..2] == "=="
return push script(text[2..-1].strip, false) if text[1] == SCRIPT
return push flat_script(text[2..-1].strip, false) if text[1] == FLAT_SCRIPT
return push plain(text[1..-1].strip, false) if text[1] == ?\s
push plain(text)
when ESCAPE; push plain(text[1..-1])
else; push plain(text)
end
end
def block_keyword(text)
return unless keyword = text.scan(BLOCK_KEYWORD_REGEX)[0]
keyword[0] || keyword[1]
end
def mid_block_keyword?(text)
MID_BLOCK_KEYWORDS.include?(block_keyword(text))
end
def push(node)
@parent.children << node
node.parent = @parent
end
def plain(text, escape_html = nil)
if block_opened?
raise SyntaxError.new(Error.message(:illegal_nesting_plain), @next_line.index)
end
unless contains_interpolation?(text)
return ParseNode.new(:plain, @index, :text => text)
end
escape_html = @options[:escape_html] if escape_html.nil?
script(unescape_interpolation(text, escape_html), false)
end
def script(text, escape_html = nil, preserve = false)
raise SyntaxError.new(Error.message(:no_ruby_code, '=')) if text.empty?
text = handle_ruby_multiline(text)
escape_html = @options[:escape_html] if escape_html.nil?
keyword = block_keyword(text)
check_push_script_stack(keyword)
ParseNode.new(:script, @index, :text => text, :escape_html => escape_html,
:preserve => preserve, :keyword => keyword)
end
def flat_script(text, escape_html = nil)
raise SyntaxError.new(Error.message(:no_ruby_code, '~')) if text.empty?
script(text, escape_html, :preserve)
end
def silent_script(text)
return haml_comment(text[2..-1]) if text[1] == SILENT_COMMENT
raise SyntaxError.new(Error.message(:no_end), @index - 1) if text[1..-1].strip == "end"
text = handle_ruby_multiline(text)
keyword = block_keyword(text)
check_push_script_stack(keyword)
if ["else", "elsif", "when"].include?(keyword)
if @script_level_stack.empty?
raise Haml::SyntaxError.new(Error.message(:missing_if, keyword), @line.index)
end
if keyword == 'when' and !@script_level_stack.last[2]
if @script_level_stack.last[1] + 1 == @line.tabs
@script_level_stack.last[1] += 1
end
@script_level_stack.last[2] = true
end
if @script_level_stack.last[1] != @line.tabs
message = Error.message(:bad_script_indent, keyword, @script_level_stack.last[1], @line.tabs)
raise Haml::SyntaxError.new(message, @line.index)
end
end
ParseNode.new(:silent_script, @index,
:text => text[1..-1], :keyword => keyword)
end
def check_push_script_stack(keyword)
if ["if", "case", "unless"].include?(keyword)
# @script_level_stack contents are arrays of form
# [:keyword, stack_level, other_info]
@script_level_stack.push([keyword.to_sym, @line.tabs])
@script_level_stack.last << false if keyword == 'case'
@tab_up = true
end
end
def haml_comment(text)
@haml_comment = block_opened?
ParseNode.new(:haml_comment, @index, :text => text)
end
def tag(line)
tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
nuke_inner_whitespace, action, value, last_line = parse_tag(line)
preserve_tag = @options[:preserve].include?(tag_name)
nuke_inner_whitespace ||= preserve_tag
preserve_tag = false if @options[:ugly]
escape_html = (action == '&' || (action != '!' && @options[:escape_html]))
case action
when '/'; self_closing = true
when '~'; parse = preserve_script = true
when '='
parse = true
if value[0] == ?=
value = unescape_interpolation(value[1..-1].strip, escape_html)
escape_html = false
end
when '&', '!'
if value[0] == ?= || value[0] == ?~
parse = true
preserve_script = (value[0] == ?~)
if value[1] == ?=
value = unescape_interpolation(value[2..-1].strip, escape_html)
escape_html = false
else
value = value[1..-1].strip
end
elsif contains_interpolation?(value)
value = unescape_interpolation(value, escape_html)
parse = true
escape_html = false
end
else
if contains_interpolation?(value)
value = unescape_interpolation(value, escape_html)
parse = true
escape_html = false
end
end
attributes = Parser.parse_class_and_id(attributes)
attributes_list = []
if attributes_hashes[:new]
static_attributes, attributes_hash = attributes_hashes[:new]
Buffer.merge_attrs(attributes, static_attributes) if static_attributes
attributes_list << attributes_hash
end
if attributes_hashes[:old]
static_attributes = parse_static_hash(attributes_hashes[:old])
Buffer.merge_attrs(attributes, static_attributes) if static_attributes
attributes_list << attributes_hashes[:old] unless static_attributes || @options[:suppress_eval]
end
attributes_list.compact!
raise SyntaxError.new(Error.message(:illegal_nesting_self_closing), @next_line.index) if block_opened? && self_closing
raise SyntaxError.new(Error.message(:no_ruby_code, action), last_line - 1) if parse && value.empty?
raise SyntaxError.new(Error.message(:self_closing_content), last_line - 1) if self_closing && !value.empty?
if block_opened? && !value.empty? && !is_ruby_multiline?(value)
raise SyntaxError.new(Error.message(:illegal_nesting_line, tag_name), @next_line.index)
end
self_closing ||= !!(!block_opened? && value.empty? && @options[:autoclose].any? {|t| t === tag_name})
value = nil if value.empty? && (block_opened? || self_closing)
value = handle_ruby_multiline(value) if parse
ParseNode.new(:tag, @index, :name => tag_name, :attributes => attributes,
:attributes_hashes => attributes_list, :self_closing => self_closing,
:nuke_inner_whitespace => nuke_inner_whitespace,
:nuke_outer_whitespace => nuke_outer_whitespace, :object_ref => object_ref,
:escape_html => escape_html, :preserve_tag => preserve_tag,
:preserve_script => preserve_script, :parse => parse, :value => value)
end
# Renders a line that creates an XHTML tag and has an implicit div because of
# `.` or `#`.
def div(line)
tag('%div' + line)
end
# Renders an XHTML comment.
def comment(line)
conditional, line = balance(line, ?[, ?]) if line[0] == ?[
line.strip!
conditional << ">" if conditional
if block_opened? && !line.empty?
raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index)
end
ParseNode.new(:comment, @index, :conditional => conditional, :text => line)
end
# Renders an XHTML doctype or XML shebang.
def doctype(line)
raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened?
version, type, encoding = line[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0]
ParseNode.new(:doctype, @index, :version => version, :type => type, :encoding => encoding)
end
def filter(name)
raise Error.new(Error.message(:invalid_filter_name, name)) unless name =~ /^\w+$/
@filter_buffer = String.new
if filter_opened?
@flat = true
# If we don't know the indentation by now, it'll be set in Line#tabs
@flat_spaces = @indentation * (@template_tabs+1) if @indentation
end
ParseNode.new(:filter, @index, :name => name, :text => @filter_buffer)
end
def close
node, @parent = @parent, @parent.parent
@template_tabs -= 1
send("close_#{node.type}", node) if respond_to?("close_#{node.type}", :include_private)
end
def close_filter(_)
@flat = false
@flat_spaces = nil
@filter_buffer = nil
end
def close_haml_comment(_)
@haml_comment = false
end
def close_silent_script(node)
@script_level_stack.pop if ["if", "case", "unless"].include? node.value[:keyword]
# Post-process case statements to normalize the nesting of "when" clauses
return unless node.value[:keyword] == "case"
return unless first = node.children.first
return unless first.type == :silent_script && first.value[:keyword] == "when"
return if first.children.empty?
# If the case node has a "when" child with children, it's the
# only child. Then we want to put everything nested beneath it
# beneath the case itself (just like "if").
node.children = [first, *first.children]
first.children = []
end
alias :close_script :close_silent_script
# 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.
def self.parse_class_and_id(list)
attributes = {}
list.scan(/([#.])([-:_a-zA-Z0-9]+)/) do |type, property|
case type
when '.'
if attributes['class']
attributes['class'] += " "
else
attributes['class'] = ""
end
attributes['class'] += property
when '#'; attributes['id'] = property
end
end
attributes
end
def parse_static_hash(text)
attributes = {}
scanner = StringScanner.new(text)
scanner.scan(/\s+/)
until scanner.eos?
return unless key = scanner.scan(LITERAL_VALUE_REGEX)
return unless scanner.scan(/\s*=>\s*/)
return unless value = scanner.scan(LITERAL_VALUE_REGEX)
return unless scanner.scan(/\s*(?:,|$)\s*/)
attributes[eval(key).to_s] = eval(value).to_s
end
attributes
end
# Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value
def parse_tag(line)
match = line.scan(/%([-:\w]+)([-:\w\.\#]*)(.*)/)[0]
raise SyntaxError.new(Error.message(:invalid_tag, line)) unless match
tag_name, attributes, rest = match
if attributes =~ /[\.#](\.|#|\z)/
raise SyntaxError.new(Error.message(:illegal_element))
end
new_attributes_hash = old_attributes_hash = last_line = nil
object_ref = "nil"
attributes_hashes = {}
while rest
case rest[0]
when ?{
break if old_attributes_hash
old_attributes_hash, rest, last_line = parse_old_attributes(rest)
attributes_hashes[:old] = old_attributes_hash
when ?(
break if new_attributes_hash
new_attributes_hash, rest, last_line = parse_new_attributes(rest)
attributes_hashes[:new] = new_attributes_hash
when ?[
break unless object_ref == "nil"
object_ref, rest = balance(rest, ?[, ?])
else; break
end
end
if rest
nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0]
nuke_whitespace ||= ''
nuke_outer_whitespace = nuke_whitespace.include? '>'
nuke_inner_whitespace = nuke_whitespace.include? '<'
end
if @options[:remove_whitespace]
nuke_outer_whitespace = true
nuke_inner_whitespace = true
end
value = value.to_s.strip
[tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace,
nuke_inner_whitespace, action, value, last_line || @index]
end
def parse_old_attributes(line)
line = line.dup
last_line = @index
begin
attributes_hash, rest = balance(line, ?{, ?})
rescue SyntaxError => e
if line.strip[-1] == ?, && e.message == Error.message(:unbalanced_brackets)
line << "\n" << @next_line.text
last_line += 1
next_line
retry
end
raise e
end
attributes_hash = attributes_hash[1...-1] if attributes_hash
return attributes_hash, rest, last_line
end
def parse_new_attributes(line)
line = line.dup
scanner = StringScanner.new(line)
last_line = @index
attributes = {}
scanner.scan(/\(\s*/)
loop do
name, value = parse_new_attribute(scanner)
break if name.nil?
if name == false
text = (Haml::Util.balance(line, ?(, ?)) || [line]).first
raise Haml::SyntaxError.new(Error.message(:invalid_attribute_list, text.inspect), last_line - 1)
end
attributes[name] = value
scanner.scan(/\s*/)
if scanner.eos?
line << " " << @next_line.text
last_line += 1
next_line
scanner.scan(/\s*/)
end
end
static_attributes = {}
dynamic_attributes = "{"
attributes.each do |name, (type, val)|
if type == :static
static_attributes[name] = val
else
dynamic_attributes << inspect_obj(name) << " => " << val << ","
end
end
dynamic_attributes << "}"
dynamic_attributes = nil if dynamic_attributes == "{}"
return [static_attributes, dynamic_attributes], scanner.rest, last_line
end
def parse_new_attribute(scanner)
unless name = scanner.scan(/[-:\w]+/)
return if scanner.scan(/\)/)
return false
end
scanner.scan(/\s*/)
return name, [:static, true] unless scanner.scan(/=/) #/end
scanner.scan(/\s*/)
unless quote = scanner.scan(/["']/)
return false unless var = scanner.scan(/(@@?|\$)?\w+/)
return name, [:dynamic, var]
end
re = /((?:\\.|\#(?!\{)|[^#{quote}\\#])*)(#{quote}|#\{)/
content = []
loop do
return false unless scanner.scan(re)
content << [:str, scanner[1].gsub(/\\(.)/, '\1')]
break if scanner[2] == quote
content << [:ruby, balance(scanner, ?{, ?}, 1).first[0...-1]]
end
return name, [:static, content.first[1]] if content.size == 1
return name, [:dynamic,
'"' + content.map {|(t, v)| t == :str ? inspect_obj(v)[1...-1] : "\#{#{v}}"}.join + '"']
end
def raw_next_line
text = @template.shift
return unless text
index = @template_index
@template_index += 1
return text, index
end
def next_line
text, index = raw_next_line
return unless text
# :eod is a special end-of-document marker
line =
if text == :eod
Line.new '-#', '-#', '-#', index, self, true
else
Line.new text.strip, text.lstrip.chomp, text, index, self, false
end
# `flat?' here is a little outdated,
# so we have to manually check if either the previous or current line
# closes the flat block, as well as whether a new block is opened.
line_defined = instance_variable_defined?('@line')
@line.tabs if line_defined
unless (flat? && !closes_flat?(line) && !closes_flat?(@line)) ||
(line_defined && @line.text[0] == ?: && line.full =~ %r[^#{@line.full[/^\s+/]}\s])
return next_line if line.text.empty?
handle_multiline(line)
end
@next_line = line
end
def closes_flat?(line)
line && !line.text.empty? && line.full !~ /^#{@flat_spaces}/
end
def un_next_line(line)
@template.unshift line
@template_index -= 1
end
def handle_multiline(line)
return unless is_multiline?(line.text)
line.text.slice!(-1)
while new_line = raw_next_line.first
break if new_line == :eod
next if new_line.strip.empty?
break unless is_multiline?(new_line.strip)
line.text << new_line.strip[0...-1]
end
un_next_line new_line
end
# Checks whether or not `line` is in a multiline sequence.
def is_multiline?(text)
text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES
end
def handle_ruby_multiline(text)
text = text.rstrip
return text unless is_ruby_multiline?(text)
un_next_line @next_line.full
begin
new_line = raw_next_line.first
break if new_line == :eod
next if new_line.strip.empty?
text << " " << new_line.strip
end while is_ruby_multiline?(new_line.strip)
next_line
text
end
# `text' is a Ruby multiline block if it:
# - ends with a comma
# - but not "?," which is a character literal
# (however, "x?," is a method call and not a literal)
# - and not "?\," which is a character literal
#
def is_ruby_multiline?(text)
text && text.length > 1 && text[-1] == ?, &&
!((text[-3..-2] =~ /\W\?/) || text[-3..-2] == "?\\")
end
def balance(*args)
res = Haml::Util.balance(*args)
return res if res
raise SyntaxError.new(Error.message(:unbalanced_brackets))
end
def block_opened?
@next_line.tabs > @line.tabs
end
# Same semantics as block_opened?, except that block_opened? uses Line#tabs,
# which doesn't interact well with filter lines
def filter_opened?
@next_line.full =~ (@indentation ? /^#{@indentation * @template_tabs}/ : /^\s/)
end
def flat?
@flat
end
end
end
haml-4.0.7/lib/haml/options.rb 0000644 0000041 0000041 00000023412 12564177327 016222 0 ustar www-data www-data module Haml
# This class encapsulates all of the configuration options that Haml
# understands. Please see the {file:REFERENCE.md#options Haml Reference} to
# learn how to set the options.
class Options
@defaults = {
:attr_wrapper => "'",
:autoclose => %w(area base basefont br col command embed frame
hr img input isindex keygen link menuitem meta
param source track wbr),
:encoding => "UTF-8",
:escape_attrs => true,
:escape_html => false,
:filename => '(haml)',
:format => :html5,
:hyphenate_data_attrs => true,
:line => 1,
:mime_type => 'text/html',
:preserve => %w(textarea pre code),
:remove_whitespace => false,
:suppress_eval => false,
:ugly => false,
:cdata => false,
:parser_class => ::Haml::Parser,
:compiler_class => ::Haml::Compiler
}
@valid_formats = [:html4, :html5, :xhtml]
@buffer_option_keys = [:autoclose, :preserve, :attr_wrapper, :ugly, :format,
:encoding, :escape_html, :escape_attrs, :hyphenate_data_attrs, :cdata]
# The default option values.
# @return Hash
def self.defaults
@defaults
end
# An array of valid values for the `:format` option.
# @return Array
def self.valid_formats
@valid_formats
end
# An array of keys that will be used to provide a hash of options to
# {Haml::Buffer}.
# @return Hash
def self.buffer_option_keys
@buffer_option_keys
end
# The character that should wrap element attributes. This defaults to `'`
# (an apostrophe). Characters of this type within the attributes will be
# escaped (e.g. by replacing them with `'`) if the character is an
# apostrophe or a quotation mark.
attr_reader :attr_wrapper
# A list of tag names that should be automatically self-closed if they have
# no content. This can also contain regular expressions that match tag names
# (or any object which responds to `#===`). Defaults to `['meta', 'img',
# 'link', 'br', 'hr', 'input', 'area', 'param', 'col', 'base']`.
attr_accessor :autoclose
# The encoding to use for the HTML output.
# Only available on Ruby 1.9 or higher.
# This can be a string or an `Encoding` Object. Note that Haml **does not**
# automatically re-encode Ruby values; any strings coming from outside the
# application should be converted before being passed into the Haml
# template. Defaults to `Encoding.default_internal`; if that's not set,
# defaults to the encoding of the Haml template; if that's `US-ASCII`,
# defaults to `"UTF-8"`.
attr_reader :encoding
# Sets whether or not to escape HTML-sensitive characters in attributes. If
# this is true, all HTML-sensitive characters in attributes are escaped. If
# it's set to false, no HTML-sensitive characters in attributes are escaped.
# If it's set to `:once`, existing HTML escape sequences are preserved, but
# other HTML-sensitive characters are escaped.
#
# Defaults to `true`.
attr_accessor :escape_attrs
# Sets whether or not to escape HTML-sensitive characters in script. If this
# is true, `=` behaves like {file:REFERENCE.md#escaping_html `&=`};
# otherwise, it behaves like {file:REFERENCE.md#unescaping_html `!=`}. Note
# that if this is set, `!=` should be used for yielding to subtemplates and
# rendering partials. See also {file:REFERENCE.md#escaping_html Escaping HTML} and
# {file:REFERENCE.md#unescaping_html Unescaping HTML}.
#
# Defaults to false.
attr_accessor :escape_html
# The name of the Haml file being parsed.
# This is only used as information when exceptions are raised. This is
# automatically assigned when working through ActionView, so it's really
# only useful for the user to assign when dealing with Haml programatically.
attr_accessor :filename
# If set to `true`, Haml will convert underscores to hyphens in all
# {file:REFERENCE.md#html5_custom_data_attributes Custom Data Attributes} As
# of Haml 4.0, this defaults to `true`.
attr_accessor :hyphenate_data_attrs
# The line offset of the Haml template being parsed. This is useful for
# inline templates, similar to the last argument to `Kernel#eval`.
attr_accessor :line
# Determines the output format. The default is `:html5`. The other options
# are `:html4` and `:xhtml`. If the output is set to XHTML, then Haml
# automatically generates self-closing tags and wraps the output of the
# Javascript and CSS-like filters inside CDATA. When the output is set to
# `:html5` or `:html4`, XML prologs are ignored. In all cases, an appropriate
# doctype is generated from `!!!`.
#
# If the mime_type of the template being rendered is `text/xml` then a
# format of `:xhtml` will be used even if the global output format is set to
# `:html4` or `:html5`.
attr :format
# The mime type that the rendered document will be served with. If this is
# set to `text/xml` then the format will be overridden to `:xhtml` even if
# it has set to `:html4` or `:html5`.
attr_accessor :mime_type
# A list of tag names that should automatically have their newlines
# preserved using the {Haml::Helpers#preserve} helper. This means that any
# content given on the same line as the tag will be preserved. For example,
# `%textarea= "Foo\nBar"` compiles to `
`.
# Defaults to `['textarea', 'pre']`. See also
# {file:REFERENCE.md#whitespace_preservation Whitespace Preservation}.
attr_accessor :preserve
# If set to `true`, all tags are treated as if both
# {file:REFERENCE.md#whitespace_removal__and_ whitespace removal} options
# were present. Use with caution as this may cause whitespace-related
# formatting errors.
#
# Defaults to `false`.
attr_reader :remove_whitespace
# Whether or not attribute hashes and Ruby scripts designated by `=` or `~`
# should be evaluated. If this is `true`, said scripts are rendered as empty
# strings.
#
# Defaults to `false`.
attr_accessor :suppress_eval
# If set to `true`, Haml makes no attempt to properly indent or format the
# HTML output. This significantly improves rendering performance but makes
# viewing the source unpleasant.
#
# Defaults to `true` in Rails production mode, and `false` everywhere else.
attr_accessor :ugly
# Whether to include CDATA sections around javascript and css blocks when
# using the `:javascript` or `:css` filters.
#
# This option also affects the `:sass`, `:scss`, `:less` and `:coffeescript`
# filters.
#
# Defaults to `false` for html, `true` for xhtml. Cannot be changed when using
# xhtml.
attr_accessor :cdata
# The parser class to use. Defaults to Haml::Parser.
attr_accessor :parser_class
# The compiler class to use. Defaults to Haml::Compiler.
attr_accessor :compiler_class
def initialize(values = {}, &block)
defaults.each {|k, v| instance_variable_set :"@#{k}", v}
values.reject {|k, v| !defaults.has_key?(k) || v.nil?}.each {|k, v| send("#{k}=", v)}
yield if block_given?
end
# Retrieve an option value.
# @param key The value to retrieve.
def [](key)
send key
end
# Set an option value.
# @param key The key to set.
# @param value The value to set for the key.
def []=(key, value)
send "#{key}=", value
end
[:escape_attrs, :hyphenate_data_attrs, :remove_whitespace, :suppress_eval,
:ugly].each do |method|
class_eval(<<-END)
def #{method}?
!! @#{method}
end
END
end
# @return [Boolean] Whether or not the format is XHTML.
def xhtml?
not html?
end
# @return [Boolean] Whether or not the format is any flavor of HTML.
def html?
html4? or html5?
end
# @return [Boolean] Whether or not the format is HTML4.
def html4?
format == :html4
end
# @return [Boolean] Whether or not the format is HTML5.
def html5?
format == :html5
end
def attr_wrapper=(value)
@attr_wrapper = value || self.class.defaults[:attr_wrapper]
end
# Undef :format to suppress warning. It's defined above with the `:attr`
# macro in order to make it appear in Yard's list of instance attributes.
undef :format
def format
mime_type == "text/xml" ? :xhtml : @format
end
def format=(value)
unless self.class.valid_formats.include?(value)
raise Haml::Error, "Invalid output format #{value.inspect}"
end
@format = value
end
undef :cdata
def cdata
xhtml? || @cdata
end
def remove_whitespace=(value)
@ugly = true if value
@remove_whitespace = value
end
if RUBY_VERSION < "1.9"
attr_writer :encoding
else
def encoding=(value)
return unless value
@encoding = value.is_a?(Encoding) ? value.name : value.to_s
@encoding = "UTF-8" if @encoding.upcase == "US-ASCII"
end
end
# Returns a subset of options: those that {Haml::Buffer} cares about.
# All of the values here are such that when `#inspect` is called on the hash,
# it can be `Kernel#eval`ed to get the same result back.
#
# See {file:REFERENCE.md#options the Haml options documentation}.
#
# @return [{Symbol => Object}] The options hash
def for_buffer
self.class.buffer_option_keys.inject({}) do |hash, key|
hash[key] = send(key)
hash
end
end
private
def defaults
self.class.defaults
end
end
end
haml-4.0.7/lib/haml/engine.rb 0000644 0000041 0000041 00000021762 12564177327 016002 0 ustar www-data www-data require 'forwardable'
require 'haml/parser'
require 'haml/compiler'
require 'haml/options'
require 'haml/helpers'
require 'haml/buffer'
require 'haml/filters'
require 'haml/error'
module Haml
# This is the frontend for using Haml programmatically.
# It can be directly used by the user by creating a
# new instance and calling \{#render} to render the template.
# For example:
#
# template = File.read('templates/really_cool_template.haml')
# haml_engine = Haml::Engine.new(template)
# output = haml_engine.render
# puts output
class Engine
extend Forwardable
include Haml::Util
# The Haml::Options instance.
# See {file:REFERENCE.md#options the Haml options documentation}.
#
# @return Haml::Options
attr_accessor :options
# The indentation used in the Haml document,
# or `nil` if the indentation is ambiguous
# (for example, for a single-level document).
#
# @return [String]
attr_accessor :indentation
attr_accessor :compiler
attr_accessor :parser
# Tilt currently depends on these moved methods, provide a stable API
def_delegators :compiler, :precompiled, :precompiled_method_return_value
def options_for_buffer
@options.for_buffer
end
# Precompiles the Haml template.
#
# @param template [String] The Haml template
# @param options [{Symbol => Object}] An options hash;
# see {file:REFERENCE.md#options the Haml options documentation}
# @raise [Haml::Error] if there's a Haml syntax error in the template
def initialize(template, options = {})
@options = Options.new(options)
@template = check_haml_encoding(template) do |msg, line|
raise Haml::Error.new(msg, line)
end
initialize_encoding options[:encoding]
@parser = @options.parser_class.new(@template, @options)
@compiler = @options.compiler_class.new(@options)
@compiler.compile(@parser.parse)
end
# Processes the template and returns the result as a string.
#
# `scope` is the context in which the template is evaluated.
# If it's a `Binding` or `Proc` object,
# Haml uses it as the second argument to `Kernel#eval`;
# otherwise, Haml just uses its `#instance_eval` context.
#
# Note that Haml modifies the evaluation context
# (either the scope object or the `self` object of the scope binding).
# It extends {Haml::Helpers}, and various instance variables are set
# (all prefixed with `haml_`).
# For example:
#
# s = "foobar"
# Haml::Engine.new("%p= upcase").render(s) #=> "
FOOBAR
"
#
# # s now extends Haml::Helpers
# s.respond_to?(:html_attrs) #=> true
#
# `locals` is a hash of local variables to make available to the template.
# For example:
#
# Haml::Engine.new("%p= foo").render(Object.new, :foo => "Hello, world!") #=> "
Hello, world!
"
#
# If a block is passed to render,
# that block is run when `yield` is called
# within the template.
#
# Due to some Ruby quirks,
# if `scope` is a `Binding` or `Proc` object and a block is given,
# the evaluation context may not be quite what the user expects.
# In particular, it's equivalent to passing `eval("self", scope)` as `scope`.
# This won't have an effect in most cases,
# but if you're relying on local variables defined in the context of `scope`,
# they won't work.
#
# @param scope [Binding, Proc, Object] The context in which the template is evaluated
# @param locals [{Symbol => Object}] Local variables that will be made available
# to the template
# @param block [#to_proc] A block that can be yielded to within the template
# @return [String] The rendered template
def render(scope = Object.new, locals = {}, &block)
parent = scope.instance_variable_defined?('@haml_buffer') ? scope.instance_variable_get('@haml_buffer') : nil
buffer = Haml::Buffer.new(parent, @options.for_buffer)
if scope.is_a?(Binding) || scope.is_a?(Proc)
scope_object = eval("self", scope)
scope = scope_object.instance_eval{binding} if block_given?
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object)
scope_object.instance_eval do
extend Haml::Helpers
@haml_buffer = buffer
end
begin
eval(@compiler.precompiled_with_return_value, scope, @options[:filename], @options[:line])
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
ensure
# Get rid of the current buffer
scope_object.instance_eval do
@haml_buffer = buffer.upper if buffer
end
end
alias_method :to_html, :render
# Returns a proc that, when called,
# renders the template and returns the result as a string.
#
# `scope` works the same as it does for render.
#
# The first argument of the returned proc is a hash of local variable names to values.
# However, due to an unfortunate Ruby quirk,
# the local variables which can be assigned must be pre-declared.
# This is done with the `local_names` argument.
# For example:
#
# # This works
# Haml::Engine.new("%p= foo").render_proc(Object.new, :foo).call :foo => "Hello!"
# #=> "
Hello!
"
#
# # This doesn't
# Haml::Engine.new("%p= foo").render_proc.call :foo => "Hello!"
# #=> NameError: undefined local variable or method `foo'
#
# The proc doesn't take a block; any yields in the template will fail.
#
# @param scope [Binding, Proc, Object] The context in which the template is evaluated
# @param local_names [Array
] The names of the locals that can be passed to the proc
# @return [Proc] The proc that will run the template
def render_proc(scope = Object.new, *local_names)
if scope.is_a?(Binding) || scope.is_a?(Proc)
scope_object = eval("self", scope)
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
begin
eval("Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {};" +
compiler.precompiled_with_ambles(local_names) + "}\n", scope, @options[:filename], @options[:line])
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
end
# Defines a method on `object` with the given name
# that renders the template and returns the result as a string.
#
# If `object` is a class or module,
# the method will instead by defined as an instance method.
# For example:
#
# t = Time.now
# Haml::Engine.new("%p\n Today's date is\n .date= self.to_s").def_method(t, :render)
# t.render #=> "\n Today's date is\n
Fri Nov 23 18:28:29 -0800 2007
\n\n"
#
# Haml::Engine.new(".upcased= upcase").def_method(String, :upcased_div)
# "foobar".upcased_div #=> "FOOBAR
\n"
#
# The first argument of the defined method is a hash of local variable names to values.
# However, due to an unfortunate Ruby quirk,
# the local variables which can be assigned must be pre-declared.
# This is done with the `local_names` argument.
# For example:
#
# # This works
# obj = Object.new
# Haml::Engine.new("%p= foo").def_method(obj, :render, :foo)
# obj.render(:foo => "Hello!") #=> "Hello!
"
#
# # This doesn't
# obj = Object.new
# Haml::Engine.new("%p= foo").def_method(obj, :render)
# obj.render(:foo => "Hello!") #=> NameError: undefined local variable or method `foo'
#
# Note that Haml modifies the evaluation context
# (either the scope object or the `self` object of the scope binding).
# It extends {Haml::Helpers}, and various instance variables are set
# (all prefixed with `haml_`).
#
# @param object [Object, Module] The object on which to define the method
# @param name [String, Symbol] The name of the method to define
# @param local_names [Array] The names of the locals that can be passed to the proc
def def_method(object, name, *local_names)
method = object.is_a?(Module) ? :module_eval : :instance_eval
object.send(method, "def #{name}(_haml_locals = {}); #{compiler.precompiled_with_ambles(local_names)}; end",
@options[:filename], @options[:line])
end
private
if RUBY_VERSION < "1.9"
def initialize_encoding(given_value)
end
else
def initialize_encoding(given_value)
unless given_value
@options.encoding = Encoding.default_internal || @template.encoding
end
end
end
def set_locals(locals, scope, scope_object)
scope_object.send(:instance_variable_set, '@_haml_locals', locals)
set_locals = locals.keys.map { |k| "#{k} = @_haml_locals[#{k.inspect}]" }.join("\n")
eval(set_locals, scope)
end
end
end
haml-4.0.7/lib/haml/exec.rb 0000644 0000041 0000041 00000024410 12564177327 015452 0 ustar www-data www-data require 'optparse'
require 'fileutils'
require 'rbconfig'
require 'pp'
module Haml
# This module handles the various Haml executables (`haml` and `haml-convert`).
module Exec
# An abstract class that encapsulates the executable code for all three executables.
class Generic
# @param args [Array] The command-line arguments
def initialize(args)
@args = args
@options = {:for_engine => {}}
end
# Parses the command-line arguments and runs the executable.
# Calls `Kernel#exit` at the end, so it never returns.
#
# @see #parse
def parse!
begin
parse
rescue Exception => e
raise e if @options[:trace] || e.is_a?(SystemExit)
$stderr.print "#{e.class}: " unless e.class == RuntimeError
$stderr.puts "#{e.message}"
$stderr.puts " Use --trace for backtrace."
exit 1
end
exit 0
end
# Parses the command-line arguments and runs the executable.
# This does not handle exceptions or exit the program.
#
# @see #parse!
def parse
@opts = OptionParser.new(&method(:set_opts))
@opts.parse!(@args)
process_result
@options
end
# @return [String] A description of the executable
def to_s
@opts.to_s
end
protected
# Finds the line of the source template
# on which an exception was raised.
#
# @param exception [Exception] The exception
# @return [String] The line number
def get_line(exception)
# SyntaxErrors have weird line reporting
# when there's trailing whitespace,
# which there is for Haml documents.
return (exception.message.scan(/:(\d+)/).first || ["??"]).first if exception.is_a?(::SyntaxError)
(exception.backtrace[0].scan(/:(\d+)/).first || ["??"]).first
end
# Tells optparse how to parse the arguments
# available for all executables.
#
# This is meant to be overridden by subclasses
# so they can add their own options.
#
# @param opts [OptionParser]
def set_opts(opts)
opts.on('-s', '--stdin', :NONE, 'Read input from standard input instead of an input file') do
@options[:input] = $stdin
end
opts.on('--trace', :NONE, 'Show a full traceback on error') do
@options[:trace] = true
end
opts.on('--unix-newlines', 'Use Unix-style newlines in written files.') do
# Note that this is the preferred way to check for Windows, since
# JRuby and Rubinius also run there.
if RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i
@options[:unix_newlines] = true
end
end
opts.on_tail("-?", "-h", "--help", "Show this message") do
puts opts
exit
end
opts.on_tail("-v", "--version", "Print version") do
puts("Haml #{::Haml::VERSION}")
exit
end
end
# Processes the options set by the command-line arguments.
# In particular, sets `@options[:input]` and `@options[:output]`
# to appropriate IO streams.
#
# This is meant to be overridden by subclasses
# so they can run their respective programs.
def process_result
input, output = @options[:input], @options[:output]
args = @args.dup
input ||=
begin
filename = args.shift
@options[:filename] = filename
open_file(filename) || $stdin
end
output ||= open_file(args.shift, 'w') || $stdout
@options[:input], @options[:output] = input, output
end
COLORS = { :red => 31, :green => 32, :yellow => 33 }
# Prints a status message about performing the given action,
# colored using the given color (via terminal escapes) if possible.
#
# @param name [#to_s] A short name for the action being performed.
# Shouldn't be longer than 11 characters.
# @param color [Symbol] The name of the color to use for this action.
# Can be `:red`, `:green`, or `:yellow`.
def puts_action(name, color, arg)
return if @options[:for_engine][:quiet]
printf color(color, "%11s %s\n"), name, arg
end
# Same as `Kernel.puts`, but doesn't print anything if the `--quiet` option is set.
#
# @param args [Array] Passed on to `Kernel.puts`
def puts(*args)
return if @options[:for_engine][:quiet]
Kernel.puts(*args)
end
# Wraps the given string in terminal escapes
# causing it to have the given color.
# If terminal esapes aren't supported on this platform,
# just returns the string instead.
#
# @param color [Symbol] The name of the color to use.
# Can be `:red`, `:green`, or `:yellow`.
# @param str [String] The string to wrap in the given color.
# @return [String] The wrapped string.
def color(color, str)
raise "[BUG] Unrecognized color #{color}" unless COLORS[color]
# Almost any real Unix terminal will support color,
# so we just filter for Windows terms (which don't set TERM)
# and not-real terminals, which aren't ttys.
return str if ENV["TERM"].nil? || ENV["TERM"].empty? || !STDOUT.tty?
return "\e[#{COLORS[color]}m#{str}\e[0m"
end
private
def open_file(filename, flag = 'r')
return if filename.nil?
flag = 'wb' if @options[:unix_newlines] && flag == 'w'
File.open(filename, flag)
end
def handle_load_error(err)
dep = err.message[/^no such file to load -- (.*)/, 1]
raise err if @options[:trace] || dep.nil? || dep.empty?
$stderr.puts <] The command-line arguments
def initialize(args)
super
@options[:for_engine] = {}
@options[:requires] = []
@options[:load_paths] = []
end
# Tells optparse how to parse the arguments.
#
# @param opts [OptionParser]
def set_opts(opts)
super
opts.banner = < e
raise e if @options[:trace]
case e
when ::Haml::SyntaxError; raise "Syntax error on line #{get_line e}: #{e.message}"
when ::Haml::Error; raise "Haml error on line #{get_line e}: #{e.message}"
else raise "Exception on line #{get_line e}: #{e.message}"
end
end
output.write(result)
output.close() if output.is_a? File
end
end
end
end
haml-4.0.7/lib/haml/template/ 0000755 0000041 0000041 00000000000 12564177327 016013 5 ustar www-data www-data haml-4.0.7/lib/haml/template/options.rb 0000644 0000041 0000041 00000000642 12564177327 020035 0 ustar www-data www-data # We keep options in its own self-contained file
# so that we can load it independently in Rails 3,
# where the full template stuff is lazy-loaded.
module Haml
module Template
extend self
@options = {}
# The options hash for Haml when used within Rails.
# See {file:REFERENCE.md#options the Haml options documentation}.
#
# @return [{Symbol => Object}]
attr_accessor :options
end
end
haml-4.0.7/lib/haml/template/plugin.rb 0000644 0000041 0000041 00000002547 12564177327 017646 0 ustar www-data www-data module Haml
# This module makes Haml work with Rails using the template handler API.
class Plugin < ActionView::Template::Handlers::ERB.superclass
# Rails 3.1+, template handlers don't inherit from anything. In <= 3.0, they
# do. To avoid messy logic figuring this out, we just inherit from whatever
# the ERB handler does.
# In Rails 3.1+, we don't need to include Compilable.
if (ActionPack::VERSION::MAJOR == 3) && (ActionPack::VERSION::MINOR < 1)
include ActionView::Template::Handlers::Compilable
end
def handles_encoding?; true; end
def compile(template)
options = Haml::Template.options.dup
if (ActionPack::VERSION::MAJOR >= 4) && template.respond_to?(:type)
options[:mime_type] = template.type
elsif template.respond_to? :mime_type
options[:mime_type] = template.mime_type
end
options[:filename] = template.identifier
Haml::Engine.new(template.source, options).compiler.precompiled_with_ambles([])
end
# In Rails 3.1+, #call takes the place of #compile
def self.call(template)
new.compile(template)
end
def cache_fragment(block, name = {}, options = nil)
@view.fragment_for(block, name, options) do
eval("_hamlout.buffer", block.binding)
end
end
end
end
ActionView::Template.register_template_handler(:haml, Haml::Plugin) haml-4.0.7/lib/haml/sass_rails_filter.rb 0000644 0000041 0000041 00000002055 12564177327 020237 0 ustar www-data www-data module Haml
module Filters
# This is an extension of Sass::Rails's SassTemplate class that allows
# Rails's asset helpers to be used inside Haml Sass filter.
class SassRailsTemplate < ::Sass::Rails::SassTemplate
def render(scope=Object.new, locals={}, &block)
scope = ::Rails.application.assets.context_class.new(::Rails.application.assets, "/", "/")
super
end
def sass_options(scope)
options = super
options[:custom][:resolver] = ::ActionView::Base.new
options
end
end
# This is an extension of Sass::Rails's SassTemplate class that allows
# Rails's asset helpers to be used inside a Haml SCSS filter.
class ScssRailsTemplate < SassRailsTemplate
self.default_mime_type = 'text/css'
def syntax
:scss
end
end
remove_filter :Sass
remove_filter :Scss
register_tilt_filter "Sass", :extend => "Css", :template_class => SassRailsTemplate
register_tilt_filter "Scss", :extend => "Css", :template_class => ScssRailsTemplate
end
end haml-4.0.7/lib/haml/helpers.rb 0000755 0000041 0000041 00000050301 12564177327 016171 0 ustar www-data www-data module Haml
# This module contains various helpful methods to make it easier to do various tasks.
# {Haml::Helpers} is automatically included in the context
# that a Haml template is parsed in, so all these methods are at your
# disposal from within the template.
module Helpers
# An object that raises an error when \{#to\_s} is called.
# It's used to raise an error when the return value of a helper is used
# when it shouldn't be.
class ErrorReturn
def initialize(method)
@message = < e
e.backtrace.shift
# If the ErrorReturn is used directly in the template,
# we don't want Haml's stuff to get into the backtrace,
# so we get rid of the format_script line.
#
# We also have to subtract one from the Haml line number
# since the value is passed to format_script the line after
# it's actually used.
if e.backtrace.first =~ /^\(eval\):\d+:in `format_script/
e.backtrace.shift
e.backtrace.first.gsub!(/^\(haml\):(\d+)/) {|s| "(haml):#{$1.to_i - 1}"}
end
raise e
end
# @return [String] A human-readable string representation
def inspect
"Haml::Helpers::ErrorReturn(#{@message.inspect})"
end
end
self.extend self
@@action_view_defined = false
# @return [Boolean] Whether or not ActionView is loaded
def self.action_view?
@@action_view_defined
end
# Note: this does **not** need to be called when using Haml helpers
# normally in Rails.
#
# Initializes the current object as though it were in the same context
# as a normal ActionView instance using Haml.
# This is useful if you want to use the helpers in a context
# other than the normal setup with ActionView.
# For example:
#
# context = Object.new
# class << context
# include Haml::Helpers
# end
# context.init_haml_helpers
# context.haml_tag :p, "Stuff"
#
def init_haml_helpers
@haml_buffer = Haml::Buffer.new(haml_buffer, Options.new.for_buffer)
nil
end
# Runs a block of code in a non-Haml context
# (i.e. \{#is\_haml?} will return false).
#
# This is mainly useful for rendering sub-templates such as partials in a non-Haml language,
# particularly where helpers may behave differently when run from Haml.
#
# Note that this is automatically applied to Rails partials.
#
# @yield A block which won't register as Haml
def non_haml
was_active = @haml_buffer.active?
@haml_buffer.active = false
yield
ensure
@haml_buffer.active = was_active
end
# Uses \{#preserve} to convert any newlines inside whitespace-sensitive tags
# into the HTML entities for endlines.
#
# @param tags [Array] Tags that should have newlines escaped
#
# @overload find_and_preserve(input, tags = haml_buffer.options[:preserve])
# Escapes newlines within a string.
#
# @param input [String] The string within which to escape newlines
# @overload find_and_preserve(tags = haml_buffer.options[:preserve])
# Escapes newlines within a block of Haml code.
#
# @yield The block within which to escape newlines
def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
return find_and_preserve(capture_haml(&block), input || tags) if block
re = /<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\1>)/im
input.to_s.gsub(re) do |s|
s =~ re # Can't rely on $1, etc. existing since Rails' SafeBuffer#gsub is incompatible
"<#{$1}#{$2}>#{preserve($3)}#{$1}>"
end
end
# Takes any string, finds all the newlines, and converts them to
# HTML entities so they'll render correctly in
# whitespace-sensitive tags without screwing up the indentation.
#
# @overload perserve(input)
# Escapes newlines within a string.
#
# @param input [String] The string within which to escape all newlines
# @overload perserve
# Escapes newlines within a block of Haml code.
#
# @yield The block within which to escape newlines
def preserve(input = nil, &block)
return preserve(capture_haml(&block)) if block
input.to_s.chomp("\n").gsub(/\n/, '
').gsub(/\r/, '')
end
alias_method :flatten, :preserve
# Takes an `Enumerable` object and a block
# and iterates over the enum,
# yielding each element to a Haml block
# and putting the result into `` elements.
# This creates a list of the results of the block.
# For example:
#
# = list_of([['hello'], ['yall']]) do |i|
# = i[0]
#
# Produces:
#
# hello
# yall
#
# And:
#
# = list_of({:title => 'All the stuff', :description => 'A book about all the stuff.'}) do |key, val|
# %h3= key.humanize
# %p= val
#
# Produces:
#
#
# Title
# All the stuff
#
#
# Description
# A book about all the stuff.
#
#
# While:
#
# = list_of(["Home", "About", "Contact", "FAQ"], {class: "nav", role: "nav"}) do |item|
# %a{ href="#" }= item
#
# Produces:
#
#
# Home
#
#
# About
#
#
# Contact
#
#
# FAQ
#
#
# `[[class", "nav"], [role", "nav"]]` could have been used instead of `{class: "nav", role: "nav"}` (or any enumerable collection where each pair of items responds to #to_s)
#
# @param enum [Enumerable] The list of objects to iterate over
# @param [Enumerable<#to_s,#to_s>] opts Each key/value pair will become an attribute pair for each list item element.
# @yield [item] A block which contains Haml code that goes within list items
# @yieldparam item An element of `enum`
def list_of(enum, opts={}, &block)
opts_attributes = opts.empty? ? "" : " ".<<(opts.map{|k,v| "#{k}='#{v}'" }.join(" "))
to_return = enum.collect do |i|
result = capture_haml(i, &block)
if result.count("\n") > 1
result = result.gsub("\n", "\n ")
result = "\n #{result.strip}\n"
else
result = result.strip
end
%Q!#{result} !
end
to_return.join("\n")
end
# Returns a hash containing default assignments for the `xmlns`, `lang`, and `xml:lang`
# attributes of the `html` HTML element.
# For example,
#
# %html{html_attrs}
#
# becomes
#
#
#
# @param lang [String] The value of `xml:lang` and `lang`
# @return [{#to_s => String}] The attribute hash
def html_attrs(lang = 'en-US')
{:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
end
# Increments the number of tabs the buffer automatically adds
# to the lines of the template.
# For example:
#
# %h1 foo
# - tab_up
# %p bar
# - tab_down
# %strong baz
#
# Produces:
#
# foo
# bar
# baz
#
# @param i [Fixnum] The number of tabs by which to increase the indentation
# @see #tab_down
def tab_up(i = 1)
haml_buffer.tabulation += i
end
# Decrements the number of tabs the buffer automatically adds
# to the lines of the template.
#
# @param i [Fixnum] The number of tabs by which to decrease the indentation
# @see #tab_up
def tab_down(i = 1)
haml_buffer.tabulation -= i
end
# Sets the number of tabs the buffer automatically adds
# to the lines of the template,
# but only for the duration of the block.
# For example:
#
# %h1 foo
# - with_tabs(2) do
# %p bar
# %strong baz
#
# Produces:
#
# foo
# bar
# baz
#
#
# @param i [Fixnum] The number of tabs to use
# @yield A block in which the indentation will be `i` spaces
def with_tabs(i)
old_tabs = haml_buffer.tabulation
haml_buffer.tabulation = i
yield
ensure
haml_buffer.tabulation = old_tabs
end
# Surrounds a block of Haml code with strings,
# with no whitespace in between.
# For example:
#
# = surround '(', ')' do
# %a{:href => "food"} chicken
#
# Produces:
#
# (chicken )
#
# and
#
# = surround '*' do
# %strong angry
#
# Produces:
#
# *angry *
#
# @param front [String] The string to add before the Haml
# @param back [String] The string to add after the Haml
# @yield A block of Haml to surround
def surround(front, back = front, &block)
output = capture_haml(&block)
"#{front}#{output.chomp}#{back}\n"
end
# Prepends a string to the beginning of a Haml block,
# with no whitespace between.
# For example:
#
# = precede '*' do
# %span.small Not really
#
# Produces:
#
# *Not really
#
# @param str [String] The string to add before the Haml
# @yield A block of Haml to prepend to
def precede(str, &block)
"#{str}#{capture_haml(&block).chomp}\n"
end
# Appends a string to the end of a Haml block,
# with no whitespace between.
# For example:
#
# click
# = succeed '.' do
# %a{:href=>"thing"} here
#
# Produces:
#
# click
# here .
#
# @param str [String] The string to add after the Haml
# @yield A block of Haml to append to
def succeed(str, &block)
"#{capture_haml(&block).chomp}#{str}\n"
end
# Captures the result of a block of Haml code,
# gets rid of the excess indentation,
# and returns it as a string.
# For example, after the following,
#
# .foo
# - foo = capture_haml(13) do |a|
# %p= a
#
# the local variable `foo` would be assigned to `"13
\n"`.
#
# @param args [Array] Arguments to pass into the block
# @yield [args] A block of Haml code that will be converted to a string
# @yieldparam args [Array] `args`
def capture_haml(*args, &block)
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
with_haml_buffer(buffer) do
position = haml_buffer.buffer.length
haml_buffer.capture_position = position
value = block.call(*args)
captured = haml_buffer.buffer.slice!(position..-1)
if captured == '' and value != haml_buffer.buffer
captured = (value.is_a?(String) ? value : nil)
end
return nil if captured.nil?
return (haml_buffer.options[:ugly] ? captured : prettify(captured))
end
ensure
haml_buffer.capture_position = nil
end
# Outputs text directly to the Haml buffer, with the proper indentation.
#
# @param text [#to_s] The text to output
def haml_concat(text = "")
unless haml_buffer.options[:ugly] || haml_indent == 0
haml_buffer.buffer << haml_indent <<
text.to_s.gsub("\n", "\n" + haml_indent) << "\n"
else
haml_buffer.buffer << text.to_s << "\n"
end
ErrorReturn.new("haml_concat")
end
# @return [String] The indentation string for the current line
def haml_indent
' ' * haml_buffer.tabulation
end
# Creates an HTML tag with the given name and optionally text and attributes.
# Can take a block that will run between the opening and closing tags.
# If the block is a Haml block or outputs text using \{#haml\_concat},
# the text will be properly indented.
#
# `name` can be a string using the standard Haml class/id shorthand
# (e.g. "span#foo.bar", "#foo").
# Just like standard Haml tags, these class and id values
# will be merged with manually-specified attributes.
#
# `flags` is a list of symbol flags
# like those that can be put at the end of a Haml tag
# (`:/`, `:<`, and `:>`).
# Currently, only `:/` and `:<` are supported.
#
# `haml_tag` outputs directly to the buffer;
# its return value should not be used.
# If you need to get the results as a string,
# use \{#capture\_haml\}.
#
# For example,
#
# haml_tag :table do
# haml_tag :tr do
# haml_tag 'td.cell' do
# haml_tag :strong, "strong!"
# haml_concat "data"
# end
# haml_tag :td do
# haml_concat "more_data"
# end
# end
# end
#
# outputs
#
#
#
#
#
# strong!
#
# data
#
#
# more_data
#
#
#
#
# @param name [#to_s] The name of the tag
#
# @overload haml_tag(name, *rest, attributes = {})
# @yield The block of Haml code within the tag
# @overload haml_tag(name, text, *flags, attributes = {})
# @param text [#to_s] The text within the tag
# @param flags [Array] Haml end-of-tag flags
def haml_tag(name, *rest, &block)
ret = ErrorReturn.new("haml_tag")
text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
flags = []
flags << rest.shift while rest.first.is_a? Symbol
attrs = (rest.shift || {})
attrs.keys.each {|key| attrs[key.to_s] = attrs.delete(key)} unless attrs.empty?
name, attrs = merge_name_and_attributes(name.to_s, attrs)
attributes = Haml::Compiler.build_attributes(haml_buffer.html?,
haml_buffer.options[:attr_wrapper],
haml_buffer.options[:escape_attrs],
haml_buffer.options[:hyphenate_data_attrs],
attrs)
if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
haml_concat "<#{name}#{attributes} />"
return ret
end
if flags.include?(:/)
raise Error.new(Error.message(:self_closing_content)) if text
raise Error.new(Error.message(:illegal_nesting_self_closing)) if block
end
tag = "<#{name}#{attributes}>"
if block.nil?
text = text.to_s
if text.include?("\n")
haml_concat tag
tab_up
haml_concat text
tab_down
haml_concat "#{name}>"
else
tag << text << "#{name}>"
haml_concat tag
end
return ret
end
if text
raise Error.new(Error.message(:illegal_nesting_line, name))
end
if flags.include?(:<)
tag << capture_haml(&block).strip << "#{name}>"
haml_concat tag
return ret
end
haml_concat tag
tab_up
block.call
tab_down
haml_concat "#{name}>"
ret
end
# Characters that need to be escaped to HTML entities from user input
HTML_ESCAPE = { '&'=>'&', '<'=>'<', '>'=>'>', '"'=>'"', "'"=>''', }
HTML_ESCAPE_REGEX = /[\"><&]/
if RUBY_VERSION >= '1.9'
# Include docs here so they are picked up by Yard
# Returns a copy of `text` with ampersands, angle brackets and quotes
# escaped into HTML entities.
#
# Note that if ActionView is loaded and XSS protection is enabled
# (as is the default for Rails 3.0+, and optional for version 2.3.5+),
# this won't escape text declared as "safe".
#
# @param text [String] The string to sanitize
# @return [String] The sanitized string
def html_escape(text)
text = text.to_s
text.gsub(HTML_ESCAPE_REGEX, HTML_ESCAPE)
end
else
def html_escape(text)
text = text.to_s
text.gsub(HTML_ESCAPE_REGEX) {|s| HTML_ESCAPE[s]}
end
end
HTML_ESCAPE_ONCE_REGEX = /[\"><]|&(?!(?:[a-zA-Z]+|(#\d+));)/
if RUBY_VERSION >= '1.9'
# Include docs here so they are picked up by Yard
# Escapes HTML entities in `text`, but without escaping an ampersand
# that is already part of an escaped entity.
#
# @param text [String] The string to sanitize
# @return [String] The sanitized string
def escape_once(text)
text = text.to_s
text.gsub(HTML_ESCAPE_ONCE_REGEX, HTML_ESCAPE)
end
else
def escape_once(text)
text = text.to_s
text.gsub(HTML_ESCAPE_ONCE_REGEX){|s| HTML_ESCAPE[s]}
end
end
# Returns whether or not the current template is a Haml template.
#
# This function, unlike other {Haml::Helpers} functions,
# also works in other `ActionView` templates,
# where it will always return false.
#
# @return [Boolean] Whether or not the current template is a Haml template
def is_haml?
!@haml_buffer.nil? && @haml_buffer.active?
end
# Returns whether or not `block` is defined directly in a Haml template.
#
# @param block [Proc] A Ruby block
# @return [Boolean] Whether or not `block` is defined directly in a Haml template
def block_is_haml?(block)
eval('!!defined?(_hamlout)', block.binding)
end
private
# Parses the tag name used for \{#haml\_tag}
# and merges it with the Ruby attributes hash.
def merge_name_and_attributes(name, attributes_hash = {})
# skip merging if no ids or classes found in name
return name, attributes_hash unless name =~ /^(.+?)?([\.#].*)$/
return $1 || "div", Buffer.merge_attrs(
Haml::Parser.parse_class_and_id($2), attributes_hash)
end
# Runs a block of code with the given buffer as the currently active buffer.
#
# @param buffer [Haml::Buffer] The Haml buffer to use temporarily
# @yield A block in which the given buffer should be used
def with_haml_buffer(buffer)
@haml_buffer, old_buffer = buffer, @haml_buffer
old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer
@haml_buffer.active, was_active = true, @haml_buffer.active?
yield
ensure
@haml_buffer.active = was_active
old_buffer.active = old_was_active if old_buffer
@haml_buffer = old_buffer
end
# The current {Haml::Buffer} object.
#
# @return [Haml::Buffer]
def haml_buffer
@haml_buffer if defined? @haml_buffer
end
# Gives a proc the same local `_hamlout` and `_erbout` variables
# that the current template has.
#
# @param proc [#call] The proc to bind
# @return [Proc] A new proc with the new variables bound
def haml_bind_proc(&proc)
_hamlout = haml_buffer
#double assignment is to avoid warnings
_erbout = _erbout = _hamlout.buffer
proc { |*args| proc.call(*args) }
end
def prettify(text)
text = text.split(/^/)
text.delete('')
min_tabs = nil
text.each do |line|
tabs = line.index(/[^ ]/) || line.length
min_tabs ||= tabs
min_tabs = min_tabs > tabs ? tabs : min_tabs
end
text.map do |line|
line.slice(min_tabs, line.length)
end.join
end
end
end
# @private
class Object
# Haml overrides various `ActionView` helpers,
# which call an \{#is\_haml?} method
# to determine whether or not the current context object
# is a proper Haml context.
# Because `ActionView` helpers may be included in non-`ActionView::Base` classes,
# it's a good idea to define \{#is\_haml?} for all objects.
def is_haml?
false
end
end
haml-4.0.7/lib/haml/version.rb 0000644 0000041 0000041 00000000044 12564177327 016210 0 ustar www-data www-data module Haml
VERSION = '4.0.7'
end
haml-4.0.7/lib/haml/compiler.rb 0000755 0000041 0000041 00000044661 12564177327 016355 0 ustar www-data www-data require 'cgi'
module Haml
class Compiler
include Haml::Util
attr_accessor :options
def initialize(options)
@options = options
@output_tabs = 0
@to_merge = []
@precompiled = ''
end
def compile(node)
parent = instance_variable_defined?('@node') ? @node : nil
@node = node
if node.children.empty?
send(:"compile_#{node.type}")
else
send(:"compile_#{node.type}") {node.children.each {|c| compile c}}
end
ensure
@node = parent
end
if RUBY_VERSION < "1.9"
# The source code that is evaluated to produce the Haml document.
#
# In Ruby 1.9, this is automatically converted to the correct encoding
# (see {file:REFERENCE.md#encodings the `:encoding` option}).
#
# @return [String]
def precompiled
@precompiled
end
else
def precompiled
encoding = Encoding.find(@options[:encoding])
return @precompiled.force_encoding(encoding) if encoding == Encoding::BINARY
return @precompiled.encode(encoding)
end
end
def precompiled_with_return_value
precompiled + ";" + precompiled_method_return_value
end
# Returns the precompiled string with the preamble and postamble.
#
# Initializes to ActionView::OutputBuffer when available; this is necessary
# to avoid ordering issues with partial layouts in Rails. If not available,
# initializes to nil.
def precompiled_with_ambles(local_names)
preamble = < @node.value[:preserve],
:escape_html => @node.value[:escape_html],
:nuke_inner_whitespace => nuke_inner_whitespace?(@node),
&block)
end
def compile_silent_script
return if @options[:suppress_eval]
push_silent(@node.value[:text])
keyword = @node.value[:keyword]
if block_given?
# Store these values because for conditional statements,
# we want to restore them for each branch
@node.value[:dont_indent_next_line] = @dont_indent_next_line
@node.value[:dont_tab_up_next_text] = @dont_tab_up_next_text
yield
push_silent("end", :can_suppress) unless @node.value[:dont_push_end]
elsif keyword == "end"
if @node.parent.children.last.equal?(@node)
# Since this "end" is ending the block,
# we don't need to generate an additional one
@node.parent.value[:dont_push_end] = true
end
# Don't restore dont_* for end because it isn't a conditional branch.
elsif Parser::MID_BLOCK_KEYWORDS.include?(keyword)
# Restore dont_* for this conditional branch
@dont_indent_next_line = @node.parent.value[:dont_indent_next_line]
@dont_tab_up_next_text = @node.parent.value[:dont_tab_up_next_text]
end
end
def compile_haml_comment; end
def compile_tag
t = @node.value
# Get rid of whitespace outside of the tag if we need to
rstrip_buffer! if t[:nuke_outer_whitespace]
dont_indent_next_line =
(t[:nuke_outer_whitespace] && !block_given?) ||
(t[:nuke_inner_whitespace] && block_given?)
if @options[:suppress_eval]
object_ref = "nil"
parse = false
value = t[:parse] ? nil : t[:value]
attributes_hashes = {}
preserve_script = false
else
object_ref = t[:object_ref]
parse = t[:parse]
value = t[:value]
attributes_hashes = t[:attributes_hashes]
preserve_script = t[:preserve_script]
end
# Check if we can render the tag directly to text and not process it in the buffer
if object_ref == "nil" && attributes_hashes.empty? && !preserve_script
tag_closed = !block_given? && !t[:self_closing] && !parse
open_tag = prerender_tag(t[:name], t[:self_closing], t[:attributes])
if tag_closed
open_tag << "#{value}#{t[:name]}>"
open_tag << "\n" unless t[:nuke_outer_whitespace]
elsif !(parse || t[:nuke_inner_whitespace] ||
(t[:self_closing] && t[:nuke_outer_whitespace]))
open_tag << "\n"
end
push_merged_text(open_tag,
tag_closed || t[:self_closing] || t[:nuke_inner_whitespace] ? 0 : 1,
!t[:nuke_outer_whitespace])
@dont_indent_next_line = dont_indent_next_line
return if tag_closed
else
if attributes_hashes.empty?
attributes_hashes = ''
elsif attributes_hashes.size == 1
attributes_hashes = ", #{attributes_hashes.first}"
else
attributes_hashes = ", (#{attributes_hashes.join(").merge(")})"
end
push_merged_text "<#{t[:name]}", 0, !t[:nuke_outer_whitespace]
push_generated_script(
"_hamlout.attributes(#{inspect_obj(t[:attributes])}, #{object_ref}#{attributes_hashes})")
concat_merged_text(
if t[:self_closing] && @options.xhtml?
" />" + (t[:nuke_outer_whitespace] ? "" : "\n")
else
">" + ((if t[:self_closing] && @options.html?
t[:nuke_outer_whitespace]
else
!block_given? || t[:preserve_tag] || t[:nuke_inner_whitespace]
end) ? "" : "\n")
end)
if value && !parse
concat_merged_text("#{value}#{t[:name]}>#{t[:nuke_outer_whitespace] ? "" : "\n"}")
elsif !t[:nuke_inner_whitespace] && !t[:self_closing]
@to_merge << [:text, '', 1]
end
@dont_indent_next_line = dont_indent_next_line
end
return if t[:self_closing]
if value.nil?
@output_tabs += 1 unless t[:nuke_inner_whitespace]
yield if block_given?
@output_tabs -= 1 unless t[:nuke_inner_whitespace]
rstrip_buffer! if t[:nuke_inner_whitespace]
push_merged_text("#{t[:name]}>" + (t[:nuke_outer_whitespace] ? "" : "\n"),
t[:nuke_inner_whitespace] ? 0 : -1, !t[:nuke_inner_whitespace])
@dont_indent_next_line = t[:nuke_outer_whitespace]
return
end
if parse
push_script(value, t.merge(:in_tag => true))
concat_merged_text("#{t[:name]}>" + (t[:nuke_outer_whitespace] ? "" : "\n"))
end
end
def compile_comment
open = "" : "-->"}")
return
end
push_text(open, 1)
@output_tabs += 1
yield if block_given?
@output_tabs -= 1
push_text(@node.value[:conditional] ? "" : "-->", -1)
end
def compile_doctype
doctype = text_for_doctype
push_text doctype if doctype
end
def compile_filter
unless filter = Filters.defined[@node.value[:name]]
name = @node.value[:name]
if ["maruku", "textile"].include?(name)
raise Error.new(Error.message(:install_haml_contrib, name), @node.line - 1)
else
raise Error.new(Error.message(:filter_not_defined, name), @node.line - 1)
end
end
filter.internal_compile(self, @node.value[:text])
end
def text_for_doctype
if @node.value[:type] == "xml"
return nil if @options.html?
wrapper = @options[:attr_wrapper]
return ""
end
if @options.html5?
''
else
if @options.xhtml?
if @node.value[:version] == "1.1"
''
elsif @node.value[:version] == "5"
''
else
case @node.value[:type]
when "strict"; ''
when "frameset"; ''
when "mobile"; ''
when "rdfa"; ''
when "basic"; ''
else ''
end
end
elsif @options.html4?
case @node.value[:type]
when "strict"; ''
when "frameset"; ''
else ''
end
end
end
end
# Evaluates `text` in the context of the scope object, but
# does not output the result.
def push_silent(text, can_suppress = false)
flush_merged_text
return if can_suppress && @options.suppress_eval?
newline = (text == "end") ? ";" : "\n"
@precompiled << "#{resolve_newlines}#{text}#{newline}"
@output_line += (text + newline).count("\n")
end
# Adds `text` to `@buffer` with appropriate tabulation
# without parsing it.
def push_merged_text(text, tab_change = 0, indent = true)
text = !indent || @dont_indent_next_line || @options[:ugly] ? text : "#{' ' * @output_tabs}#{text}"
@to_merge << [:text, text, tab_change]
@dont_indent_next_line = false
end
# Concatenate `text` to `@buffer` without tabulation.
def concat_merged_text(text)
@to_merge << [:text, text, 0]
end
def push_text(text, tab_change = 0)
push_merged_text("#{text}\n", tab_change)
end
def flush_merged_text
return if @to_merge.empty?
str = ""
mtabs = 0
@to_merge.each do |type, val, tabs|
case type
when :text
str << inspect_obj(val)[1...-1]
mtabs += tabs
when :script
if mtabs != 0 && !@options[:ugly]
val = "_hamlout.adjust_tabs(#{mtabs}); " + val
end
str << "\#{#{val}}"
mtabs = 0
else
raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.")
end
end
unless str.empty?
@precompiled <<
if @options[:ugly]
"_hamlout.buffer << \"#{str}\";"
else
"_hamlout.push_text(\"#{str}\", #{mtabs}, #{@dont_tab_up_next_text.inspect});"
end
end
@to_merge = []
@dont_tab_up_next_text = false
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`
def push_script(text, opts = {})
return if @options.suppress_eval?
args = %w[preserve_script in_tag preserve_tag escape_html nuke_inner_whitespace]
args.map! {|name| opts[name.to_sym]}
args << !block_given? << @options[:ugly]
no_format = @options[:ugly] &&
!(opts[:preserve_script] || opts[:preserve_tag] || opts[:escape_html])
output_expr = "(#{text}\n)"
static_method = "_hamlout.#{static_method_name(:format_script, *args)}"
# Prerender tabulation unless we're in a tag
push_merged_text '' unless opts[:in_tag]
unless block_given?
push_generated_script(no_format ? "#{text}\n" : "#{static_method}(#{output_expr});")
concat_merged_text("\n") unless opts[:in_tag] || opts[:nuke_inner_whitespace]
return
end
flush_merged_text
push_silent "haml_temp = #{text}"
yield
push_silent('end', :can_suppress) unless @node.value[:dont_push_end]
@precompiled << "_hamlout.buffer << #{no_format ? "haml_temp.to_s;" : "#{static_method}(haml_temp);"}"
concat_merged_text("\n") unless opts[:in_tag] || opts[:nuke_inner_whitespace] || @options[:ugly]
end
def push_generated_script(text)
@to_merge << [:script, resolve_newlines + text]
@output_line += text.count("\n")
end
# This is a class method so it can be accessed from Buffer.
def self.build_attributes(is_html, attr_wrapper, escape_attrs, hyphenate_data_attrs, attributes = {})
# @TODO this is an absolutely ridiculous amount of arguments. At least
# some of this needs to be moved into an instance method.
quote_escape = attr_wrapper == '"' ? """ : "'"
other_quote_char = attr_wrapper == '"' ? "'" : '"'
join_char = hyphenate_data_attrs ? '-' : '_'
attributes.each do |key, value|
if value.is_a?(Hash)
data_attributes = attributes.delete(key)
data_attributes = flatten_data_attributes(data_attributes, '', join_char)
data_attributes = build_data_keys(data_attributes, hyphenate_data_attrs, key)
attributes = data_attributes.merge(attributes)
end
end
result = attributes.collect do |attr, value|
next if value.nil?
value = filter_and_join(value, ' ') if attr == 'class'
value = filter_and_join(value, '_') if attr == 'id'
if value == true
next " #{attr}" if is_html
next " #{attr}=#{attr_wrapper}#{attr}#{attr_wrapper}"
elsif value == false
next
end
escaped =
if escape_attrs == :once
Haml::Helpers.escape_once(value.to_s)
elsif escape_attrs
Haml::Helpers.html_escape(value.to_s)
else
value.to_s
end
value = Haml::Helpers.preserve(escaped)
if escape_attrs
# We want to decide whether or not to escape quotes
value.gsub!(/"|"/, '"')
this_attr_wrapper = attr_wrapper
if value.include? attr_wrapper
if value.include? other_quote_char
value.gsub!(attr_wrapper, quote_escape)
else
this_attr_wrapper = other_quote_char
end
end
else
this_attr_wrapper = attr_wrapper
end
" #{attr}=#{this_attr_wrapper}#{value}#{this_attr_wrapper}"
end
result.compact.sort.join
end
def self.filter_and_join(value, separator)
return "" if value == ""
value = [value] unless value.is_a?(Array)
value = value.flatten.collect {|item| item ? item.to_s : nil}.compact.join(separator)
return !value.empty? && value
end
def self.build_data_keys(data_hash, hyphenate, attr_name="data")
Hash[data_hash.map do |name, value|
if name == nil
[attr_name, value]
elsif hyphenate
["#{attr_name}-#{name.to_s.gsub(/_/, '-')}", value]
else
["#{attr_name}-#{name}", value]
end
end]
end
def self.flatten_data_attributes(data, key, join_char, seen = [])
return {key => data} unless data.is_a?(Hash)
return {key => nil} if seen.include? data.object_id
seen << data.object_id
data.sort {|x, y| x[0].to_s <=> y[0].to_s}.inject({}) do |hash, array|
k, v = array
joined = key == '' ? k : [key, k].join(join_char)
hash.merge! flatten_data_attributes(v, joined, join_char, seen)
end
end
def prerender_tag(name, self_close, attributes)
# TODO: consider just passing in the damn options here
attributes_string = Compiler.build_attributes(
@options.html?, @options[:attr_wrapper], @options[:escape_attrs], @options[:hyphenate_data_attrs], attributes)
"<#{name}#{attributes_string}#{self_close && @options.xhtml? ? ' /' : ''}>"
end
def resolve_newlines
diff = @node.line - @output_line
return "" if diff <= 0
@output_line = @node.line
"\n" * [diff, 0].max
end
# Get rid of and whitespace at the end of the buffer
# or the merged text
def rstrip_buffer!(index = -1)
last = @to_merge[index]
if last.nil?
push_silent("_hamlout.rstrip!", false)
@dont_tab_up_next_text = true
return
end
case last.first
when :text
last[1].rstrip!
if last[1].empty?
@to_merge.slice! index
rstrip_buffer! index
end
when :script
last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);')
rstrip_buffer! index - 1
else
raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.")
end
end
end
end
haml-4.0.7/lib/haml/helpers/ 0000755 0000041 0000041 00000000000 12564177327 015642 5 ustar www-data www-data haml-4.0.7/lib/haml/helpers/safe_erubis_template.rb 0000644 0000041 0000041 00000001111 12564177327 022343 0 ustar www-data www-data module Haml
class ErubisTemplateHandler < ActionView::Template::Handlers::Erubis
def initialize(*args, &blk)
@newline_pending = 0
super
end
end
class SafeErubisTemplate < Tilt::ErubisTemplate
def initialize_engine
end
def prepare
@options.merge! :engine_class => Haml::ErubisTemplateHandler
super
end
def precompiled_preamble(locals)
[super, "@output_buffer = ActionView::OutputBuffer.new;"].join("\n")
end
def precompiled_postamble(locals)
[super, '@output_buffer.to_s'].join("\n")
end
end
end haml-4.0.7/lib/haml/helpers/xss_mods.rb 0000644 0000041 0000041 00000007227 12564177327 020036 0 ustar www-data www-data module Haml
module Helpers
# This module overrides Haml helpers to work properly
# in the context of ActionView.
# Currently it's only used for modifying the helpers
# to work with Rails' XSS protection methods.
module XssMods
def self.included(base)
%w[html_escape find_and_preserve preserve list_of surround
precede succeed capture_haml haml_concat haml_indent
haml_tag escape_once].each do |name|
base.send(:alias_method, "#{name}_without_haml_xss", name)
base.send(:alias_method, name, "#{name}_with_haml_xss")
end
end
# Don't escape text that's already safe,
# output is always HTML safe
def html_escape_with_haml_xss(text)
str = text.to_s
return text if str.html_safe?
Haml::Util.html_safe(html_escape_without_haml_xss(str))
end
# Output is always HTML safe
def find_and_preserve_with_haml_xss(*args, &block)
Haml::Util.html_safe(find_and_preserve_without_haml_xss(*args, &block))
end
# Output is always HTML safe
def preserve_with_haml_xss(*args, &block)
Haml::Util.html_safe(preserve_without_haml_xss(*args, &block))
end
# Output is always HTML safe
def list_of_with_haml_xss(*args, &block)
Haml::Util.html_safe(list_of_without_haml_xss(*args, &block))
end
# Input is escaped, output is always HTML safe
def surround_with_haml_xss(front, back = front, &block)
Haml::Util.html_safe(
surround_without_haml_xss(
haml_xss_html_escape(front),
haml_xss_html_escape(back),
&block))
end
# Input is escaped, output is always HTML safe
def precede_with_haml_xss(str, &block)
Haml::Util.html_safe(precede_without_haml_xss(haml_xss_html_escape(str), &block))
end
# Input is escaped, output is always HTML safe
def succeed_with_haml_xss(str, &block)
Haml::Util.html_safe(succeed_without_haml_xss(haml_xss_html_escape(str), &block))
end
# Output is always HTML safe
def capture_haml_with_haml_xss(*args, &block)
Haml::Util.html_safe(capture_haml_without_haml_xss(*args, &block))
end
# Input is escaped
def haml_concat_with_haml_xss(text = "")
raw = instance_variable_defined?('@_haml_concat_raw') ? @_haml_concat_raw : false
haml_concat_without_haml_xss(raw ? text : haml_xss_html_escape(text))
end
# Output is always HTML safe
def haml_indent_with_haml_xss
Haml::Util.html_safe(haml_indent_without_haml_xss)
end
# Input is escaped, haml_concat'ed output is always HTML safe
def haml_tag_with_haml_xss(name, *rest, &block)
name = haml_xss_html_escape(name.to_s)
rest.unshift(haml_xss_html_escape(rest.shift.to_s)) unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
with_raw_haml_concat {haml_tag_without_haml_xss(name, *rest, &block)}
end
# Output is always HTML safe
def escape_once_with_haml_xss(*args)
Haml::Util.html_safe(escape_once_without_haml_xss(*args))
end
private
# Escapes the HTML in the text if and only if
# Rails XSS protection is enabled *and* the `:escape_html` option is set.
def haml_xss_html_escape(text)
return text unless Haml::Util.rails_xss_safe? && haml_buffer.options[:escape_html]
html_escape(text)
end
end
class ErrorReturn
# Any attempt to treat ErrorReturn as a string should cause it to blow up.
alias_method :html_safe, :to_s
alias_method :html_safe?, :to_s
alias_method :html_safe!, :to_s
end
end
end
haml-4.0.7/lib/haml/helpers/action_view_mods.rb 0000644 0000041 0000041 00000011340 12564177327 021517 0 ustar www-data www-data module ActionView
class Base
def render_with_haml(*args, &block)
options = args.first
# If render :layout is used with a block, it concats rather than returning
# a string so we need it to keep thinking it's Haml until it hits the
# sub-render.
if is_haml? && !(options.is_a?(Hash) && options[:layout] && block_given?)
return non_haml { render_without_haml(*args, &block) }
end
render_without_haml(*args, &block)
end
alias_method :render_without_haml, :render
alias_method :render, :render_with_haml
def output_buffer_with_haml
return haml_buffer.buffer if is_haml?
output_buffer_without_haml
end
alias_method :output_buffer_without_haml, :output_buffer
alias_method :output_buffer, :output_buffer_with_haml
def set_output_buffer_with_haml(new_buffer)
if is_haml?
if Haml::Util.rails_xss_safe? && new_buffer.is_a?(ActiveSupport::SafeBuffer)
new_buffer = String.new(new_buffer)
end
haml_buffer.buffer = new_buffer
else
set_output_buffer_without_haml new_buffer
end
end
alias_method :set_output_buffer_without_haml, :output_buffer=
alias_method :output_buffer=, :set_output_buffer_with_haml
end
module Helpers
module CaptureHelper
def capture_with_haml(*args, &block)
if Haml::Helpers.block_is_haml?(block)
#double assignment is to avoid warnings
_hamlout = _hamlout = eval('_hamlout', block.binding) # Necessary since capture_haml checks _hamlout
str = capture_haml(*args, &block)
# NonCattingString is present in Rails less than 3.1.0. When support
# for 3.0 is dropped, this can be removed.
return ActionView::NonConcattingString.new(str) if str && defined?(ActionView::NonConcattingString)
return str
else
capture_without_haml(*args, &block)
end
end
alias_method :capture_without_haml, :capture
alias_method :capture, :capture_with_haml
end
module TagHelper
def content_tag_with_haml(name, *args, &block)
return content_tag_without_haml(name, *args, &block) unless is_haml?
preserve = haml_buffer.options[:preserve].include?(name.to_s)
if block_given? && block_is_haml?(block) && preserve
return content_tag_without_haml(name, *args) {preserve(&block)}
end
content = content_tag_without_haml(name, *args, &block)
content = Haml::Helpers.preserve(content) if preserve && content
content
end
alias_method :content_tag_without_haml, :content_tag
alias_method :content_tag, :content_tag_with_haml
end
module HamlSupport
include Haml::Helpers
def haml_buffer
@template_object.send :haml_buffer
end
def is_haml?
@template_object.send :is_haml?
end
end
if ActionPack::VERSION::MAJOR == 4
module Tags
class TextArea
include HamlSupport
end
end
end
class InstanceTag
include HamlSupport
def content_tag(*args, &block)
html_tag = content_tag_with_haml(*args, &block)
return html_tag unless respond_to?(:error_wrapping)
return error_wrapping(html_tag) if method(:error_wrapping).arity == 1
return html_tag unless object.respond_to?(:errors) && object.errors.respond_to?(:on)
return error_wrapping(html_tag, object.errors.on(@method_name))
end
end
module FormTagHelper
def form_tag_with_haml(url_for_options = {}, options = {}, *parameters_for_url, &proc)
if is_haml?
wrap_block = block_given? && block_is_haml?(proc)
if wrap_block
oldproc = proc
proc = haml_bind_proc do |*args|
concat "\n"
with_tabs(1) {oldproc.call(*args)}
end
end
res = form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc) + "\n"
res << "\n" if wrap_block
res
else
form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc)
end
end
alias_method :form_tag_without_haml, :form_tag
alias_method :form_tag, :form_tag_with_haml
end
module FormHelper
def form_for_with_haml(object_name, *args, &proc)
wrap_block = block_given? && is_haml? && block_is_haml?(proc)
if wrap_block
oldproc = proc
proc = proc {|*subargs| with_tabs(1) {oldproc.call(*subargs)}}
end
res = form_for_without_haml(object_name, *args, &proc)
res << "\n" if wrap_block
res
end
alias_method :form_for_without_haml, :form_for
alias_method :form_for, :form_for_with_haml
end
end
end haml-4.0.7/lib/haml/helpers/action_view_extensions.rb 0000644 0000041 0000041 00000003674 12564177327 022767 0 ustar www-data www-data module Haml
module Helpers
@@action_view_defined = true
# This module contains various useful helper methods
# that either tie into ActionView or the rest of the ActionPack stack,
# or are only useful in that context.
# Thus, the methods defined here are only available
# if ActionView is installed.
module ActionViewExtensions
# Returns a value for the "class" attribute
# unique to this controller/action pair.
# This can be used to target styles specifically at this action or controller.
# For example, if the current action were `EntryController#show`,
#
# %div{:class => page_class} My Div
#
# would become
#
# My Div
#
# Then, in a stylesheet (shown here as [Sass](http://sass-lang.com)),
# you could refer to this specific action:
#
# .entry.show
# font-weight: bold
#
# or to all actions in the entry controller:
#
# .entry
# color: #00f
#
# @return [String] The class name for the current page
def page_class
controller.controller_name + " " + controller.action_name
end
alias_method :generate_content_class_names, :page_class
# Treats all input to \{Haml::Helpers#haml\_concat} within the block
# as being HTML safe for Rails' XSS protection.
# This is useful for wrapping blocks of code that concatenate HTML en masse.
#
# This has no effect if Rails' XSS protection isn't enabled.
#
# @yield A block in which all input to `#haml_concat` is treated as raw.
# @see Haml::Util#rails_xss_safe?
def with_raw_haml_concat
old = instance_variable_defined?('@_haml_concat_raw') ? @_haml_concat_raw : false
@_haml_concat_raw = true
yield
ensure
@_haml_concat_raw = old
end
end
include ActionViewExtensions
end
end
haml-4.0.7/lib/haml/helpers/action_view_xss_mods.rb 0000644 0000041 0000041 00000003446 12564177327 022424 0 ustar www-data www-data module ActionView
module Helpers
module CaptureHelper
def with_output_buffer_with_haml_xss(*args, &block)
res = with_output_buffer_without_haml_xss(*args, &block)
case res
when Array; res.map {|s| Haml::Util.html_safe(s)}
when String; Haml::Util.html_safe(res)
else; res
end
end
alias_method :with_output_buffer_without_haml_xss, :with_output_buffer
alias_method :with_output_buffer, :with_output_buffer_with_haml_xss
end
module FormTagHelper
def form_tag_with_haml_xss(*args, &block)
res = form_tag_without_haml_xss(*args, &block)
res = Haml::Util.html_safe(res) unless block_given?
res
end
alias_method :form_tag_without_haml_xss, :form_tag
alias_method :form_tag, :form_tag_with_haml_xss
end
module FormHelper
def form_for_with_haml_xss(*args, &block)
res = form_for_without_haml_xss(*args, &block)
return Haml::Util.html_safe(res) if res.is_a?(String)
return res
end
alias_method :form_for_without_haml_xss, :form_for
alias_method :form_for, :form_for_with_haml_xss
end
module TextHelper
def concat_with_haml_xss(string)
if is_haml?
haml_buffer.buffer.concat(haml_xss_html_escape(string))
else
concat_without_haml_xss(string)
end
end
alias_method :concat_without_haml_xss, :concat
alias_method :concat, :concat_with_haml_xss
def safe_concat_with_haml_xss(string)
if is_haml?
haml_buffer.buffer.concat(string)
else
safe_concat_without_haml_xss(string)
end
end
alias_method :safe_concat_without_haml_xss, :safe_concat
alias_method :safe_concat, :safe_concat_with_haml_xss
end
end
end
haml-4.0.7/lib/haml/error.rb 0000644 0000041 0000041 00000006064 12564177327 015664 0 ustar www-data www-data module Haml
# An exception raised by Haml code.
class Error < StandardError
MESSAGES = {
:bad_script_indent => '"%s" is indented at wrong level: expected %d, but was at %d.',
:cant_run_filter => 'Can\'t run "%s" filter; you must require its dependencies first',
:cant_use_tabs_and_spaces => "Indentation can't use both tabs and spaces.",
:deeper_indenting => "The line was indented %d levels deeper than the previous line.",
:filter_not_defined => 'Filter "%s" is not defined.',
:gem_install_filter_deps => '"%s" filter\'s %s dependency missing: try installing it or adding it to your Gemfile',
:illegal_element => "Illegal element: classes and ids must have values.",
:illegal_nesting_content => "Illegal nesting: nesting within a tag that already has content is illegal.",
:illegal_nesting_header => "Illegal nesting: nesting within a header command is illegal.",
:illegal_nesting_line => "Illegal nesting: content can't be both given on the same line as %%%s and nested within it.",
:illegal_nesting_plain => "Illegal nesting: nesting within plain text is illegal.",
:illegal_nesting_self_closing => "Illegal nesting: nesting within a self-closing tag is illegal.",
:inconsistent_indentation => "Inconsistent indentation: %s used for indentation, but the rest of the document was indented using %s.",
:indenting_at_start => "Indenting at the beginning of the document is illegal.",
:install_haml_contrib => 'To use the "%s" filter, please install the haml-contrib gem.',
:invalid_attribute_list => 'Invalid attribute list: %s.',
:invalid_filter_name => 'Invalid filter name ":%s".',
:invalid_tag => 'Invalid tag: "%s".',
:missing_if => 'Got "%s" with no preceding "if"',
:no_ruby_code => "There's no Ruby code for %s to evaluate.",
:self_closing_content => "Self-closing tags can't have content.",
:unbalanced_brackets => 'Unbalanced brackets.',
:no_end => <<-END
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
END
}
def self.message(key, *args)
string = MESSAGES[key] or raise "[HAML BUG] No error messages for #{key}"
(args.empty? ? string : string % args).rstrip
end
# The line of the template on which the error occurred.
#
# @return [Fixnum]
attr_reader :line
# @param message [String] The error message
# @param line [Fixnum] See \{#line}
def initialize(message = nil, line = nil)
super(message)
@line = line
end
end
# SyntaxError is the type of exception raised when Haml encounters an
# ill-formatted document.
# It's not particularly interesting,
# except in that it's a subclass of {Haml::Error}.
class SyntaxError < Error; end
end
haml-4.0.7/lib/haml/util.rb 0000755 0000041 0000041 00000032744 12564177327 015517 0 ustar www-data www-data begin
require 'erubis/tiny'
rescue LoadError
require 'erb'
end
require 'set'
require 'stringio'
require 'strscan'
module Haml
# A module containing various useful functions.
module Util
extend self
# Computes the powerset of the given array.
# This is the set of all subsets of the array.
#
# @example
# powerset([1, 2, 3]) #=>
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
# @param arr [Enumerable]
# @return [Set] The subsets of `arr`
def powerset(arr)
arr.inject([Set.new].to_set) do |powerset, el|
new_powerset = Set.new
powerset.each do |subset|
new_powerset << subset
new_powerset << subset + [el]
end
new_powerset
end
end
# Returns information about the caller of the previous method.
#
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
# @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
# The method name may be nil
def caller_info(entry = caller[1])
info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
info[1] = info[1].to_i
# This is added by Rubinius to designate a block, but we don't care about it.
info[2].sub!(/ \{\}\Z/, '') if info[2]
info
end
# Silence all output to STDERR within a block.
#
# @yield A block in which no output will be printed to STDERR
def silence_warnings
the_real_stderr, $stderr = $stderr, StringIO.new
yield
ensure
$stderr = the_real_stderr
end
# Returns an ActionView::Template* class.
# In pre-3.0 versions of Rails, most of these classes
# were of the form `ActionView::TemplateFoo`,
# while afterwards they were of the form `ActionView;:Template::Foo`.
#
# @param name [#to_s] The name of the class to get.
# For example, `:Error` will return `ActionView::TemplateError`
# or `ActionView::Template::Error`.
def av_template_class(name)
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
return ActionView::Template.const_get(name.to_s)
end
## Rails XSS Safety
# Whether or not ActionView's XSS protection is available and enabled,
# as is the default for Rails 3.0+, and optional for version 2.3.5+.
# Overridden in haml/template.rb if this is the case.
#
# @return [Boolean]
def rails_xss_safe?
false
end
# Returns the given text, marked as being HTML-safe.
# With older versions of the Rails XSS-safety mechanism,
# this destructively modifies the HTML-safety of `text`.
#
# @param text [String, nil]
# @return [String, nil] `text`, marked as HTML-safe
def html_safe(text)
return unless text
text.html_safe
end
# Checks that the encoding of a string is valid in Ruby 1.9
# and cleans up potential encoding gotchas like the UTF-8 BOM.
# If it's not, yields an error string describing the invalid character
# and the line on which it occurrs.
#
# @param str [String] The string of which to check the encoding
# @yield [msg] A block in which an encoding error can be raised.
# Only yields if there is an encoding error
# @yieldparam msg [String] The error message to be raised
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
if RUBY_VERSION < "1.9"
def check_encoding(str)
str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
end
else
def check_encoding(str)
if str.valid_encoding?
# Get rid of the Unicode BOM if possible
if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
else
return str
end
end
encoding = str.encoding
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
str.force_encoding("binary").split(newlines).each_with_index do |line, i|
begin
line.encode(encoding)
rescue Encoding::UndefinedConversionError => e
yield <
# return foo + bar
# <% elsif baz || bang %>
# return foo - bar
# <% else %>
# return 17
# <% end %>
# RUBY
#
# \{#static\_method\_name} can be used to call static methods.
#
# @overload def_static_method(klass, name, args, *vars, erb)
# @param klass [Module] The class on which to define the static method
# @param name [#to_s] The (base) name of the static method
# @param args [Array] The names of the arguments to the defined methods
# (**not** to the ERB template)
# @param vars [Array] The names of the static boolean variables
# to be made available to the ERB template
def def_static_method(klass, name, args, *vars)
erb = vars.pop
info = caller_info
powerset(vars).each do |set|
context = StaticConditionalContext.new(set).instance_eval {binding}
method_content = (defined?(Erubis::TinyEruby) && Erubis::TinyEruby || ERB).new(erb).result(context)
klass.class_eval(<] The static variable assignment
# @return [String] The real name of the static method
def static_method_name(name, *vars)
:"#{name}_#{vars.map {|v| !!v}.join('_')}"
end
# Scans through a string looking for the interoplation-opening `#{`
# and, when it's found, yields the scanner to the calling code
# so it can handle it properly.
#
# The scanner will have any backslashes immediately in front of the `#{`
# as the second capture group (`scan[2]`),
# and the text prior to that as the first (`scan[1]`).
#
# @yieldparam scan [StringScanner] The scanner scanning through the string
# @return [String] The text remaining in the scanner after all `#{`s have been processed
def handle_interpolation(str)
scan = StringScanner.new(str)
yield scan while scan.scan(/(.*?)(\\*)\#\{/)
scan.rest
end
# Moves a scanner through a balanced pair of characters.
# For example:
#
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
# ^ ^
# from to
#
# @param scanner [StringScanner] The string scanner to move
# @param start [Character] The character opening the balanced pair.
# A `Fixnum` in 1.8, a `String` in 1.9
# @param finish [Character] The character closing the balanced pair.
# A `Fixnum` in 1.8, a `String` in 1.9
# @param count [Fixnum] The number of opening characters matched
# before calling this method
# @return [(String, String)] The string matched within the balanced pair
# and the rest of the string.
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
def balance(scanner, start, finish, count = 0)
str = ''
scanner = StringScanner.new(scanner) unless scanner.is_a? StringScanner
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
while scanner.scan(regexp)
str << scanner.matched
count += 1 if scanner.matched[-1] == start
count -= 1 if scanner.matched[-1] == finish
return [str.strip, scanner.rest] if count == 0
end
end
# Formats a string for use in error messages about indentation.
#
# @param indentation [String] The string used for indentation
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
def human_indentation(indentation)
if !indentation.include?(?\t)
noun = 'space'
elsif !indentation.include?(?\s)
noun = 'tab'
else
return indentation.inspect
end
singular = indentation.length == 1
"#{indentation.length} #{noun}#{'s' unless singular}"
end
def contains_interpolation?(str)
str.include?('#{')
end
def unescape_interpolation(str, escape_html = nil)
res = ''
rest = Haml::Util.handle_interpolation str.dump do |scan|
escapes = (scan[2].size - 1) / 2
res << scan.matched[0...-3 - escapes]
if escapes % 2 == 1
res << '#{'
else
content = eval('"' + balance(scan, ?{, ?}, 1)[0][0...-1] + '"')
content = "Haml::Helpers.html_escape((#{content}))" if escape_html
res << '#{' + content + "}"# Use eval to get rid of string escapes
end
end
res + rest
end
private
# Parses a magic comment at the beginning of a Haml file.
# The parsing rules are basically the same as Ruby's.
#
# @return [(Boolean, String or nil)]
# Whether the document begins with a UTF-8 BOM,
# and the declared encoding of the document (or nil if none is declared)
def parse_haml_magic_comment(str)
scanner = StringScanner.new(str.dup.force_encoding("BINARY"))
bom = scanner.scan(/\xEF\xBB\xBF/n)
return bom unless scanner.scan(/-\s*#\s*/n)
if coding = try_parse_haml_emacs_magic_comment(scanner)
return bom, coding
end
return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
return bom, scanner[1]
end
def try_parse_haml_emacs_magic_comment(scanner)
pos = scanner.pos
return unless scanner.scan(/.*?-\*-\s*/n)
# From Ruby's parse.y
return unless scanner.scan(/([^\s'":;]+)\s*:\s*("(?:\\.|[^"])*"|[^"\s;]+?)[\s;]*-\*-/n)
name, val = scanner[1], scanner[2]
return unless name =~ /(en)?coding/in
val = $1 if val =~ /^"(.*)"$/n
return val
ensure
scanner.pos = pos
end
end
end
haml-4.0.7/lib/haml/railtie.rb 0000644 0000041 0000041 00000001056 12564177327 016160 0 ustar www-data www-data if defined?(ActiveSupport)
require 'haml/template/options'
ActiveSupport.on_load(:before_initialize) do
ActiveSupport.on_load(:action_view) do
require "haml/template"
end
end
end
module Haml
class Railtie < ::Rails::Railtie
initializer :haml do |app|
require "haml/template"
if defined?(::Sass::Rails::SassTemplate) && app.config.assets.enabled
require "haml/sass_rails_filter"
end
end
end
end
require "haml/helpers/safe_erubis_template"
Haml::Filters::Erb.template_class = Haml::SafeErubisTemplate haml-4.0.7/lib/haml/template.rb 0000644 0000041 0000041 00000001643 12564177327 016344 0 ustar www-data www-data require 'haml/template/options'
require 'haml/engine'
require 'haml/helpers/action_view_mods'
require 'haml/helpers/action_view_extensions'
require 'haml/helpers/xss_mods'
require 'haml/helpers/action_view_xss_mods'
module Haml
class Compiler
def precompiled_method_return_value_with_haml_xss
"::Haml::Util.html_safe(#{precompiled_method_return_value_without_haml_xss})"
end
alias_method :precompiled_method_return_value_without_haml_xss, :precompiled_method_return_value
alias_method :precompiled_method_return_value, :precompiled_method_return_value_with_haml_xss
end
module Helpers
include Haml::Helpers::XssMods
end
module Util
undef :rails_xss_safe? if defined? rails_xss_safe?
def rails_xss_safe?; true; end
end
end
Haml::Template.options[:ugly] = defined?(Rails) ? !Rails.env.development? : true
Haml::Template.options[:escape_html] = true
require 'haml/template/plugin'
haml-4.0.7/REFERENCE.md 0000644 0000041 0000041 00000110051 12564177327 014327 0 ustar www-data www-data # Haml (HTML Abstraction Markup Language)
Haml is a markup language that's used to cleanly and simply describe the HTML of
any web document, without the use of inline code. Haml functions as a
replacement for inline page templating systems such as PHP, ERB, and ASP.
However, Haml avoids the need for explicitly coding HTML into the template,
because it is actually an abstract description of the HTML, with some code to
generate dynamic content.
## Features
* Whitespace active
* Well-formatted markup
* DRY
* Follows CSS conventions
* Integrates Ruby code
* Implements Rails templates with the .haml extension
## Using Haml
Haml can be used in three ways:
* as a command-line tool,
* as a plugin for Ruby on Rails,
* and as a standalone Ruby module.
The first step for all of these is to install the Haml gem:
gem install haml
To run Haml from the command line, just use
haml input.haml output.html
Use `haml --help` for full documentation.
To use Haml with Rails, add the following line to the Gemfile:
gem "haml"
Once it's installed, all view files with the `".html.haml"` extension will be
compiled using Haml.
You can access instance variables in Haml templates the same way you do in ERB
templates. Helper methods are also available in Haml templates. For example:
# file: app/controllers/movies_controller.rb
class MoviesController < ApplicationController
def index
@title = "Teen Wolf"
end
end
-# file: app/views/movies/index.html.haml
#content
.title
%h1= @title
= link_to 'Home', home_url
may be compiled to:
### Rails XSS Protection
Haml supports Rails' XSS protection scheme, which was introduced in Rails 2.3.5+
and is enabled by default in 3.0.0+. If it's enabled, Haml's
{Haml::Options#escape_html `:escape_html`} option is set to `true` by default -
like in ERB, all strings printed to a Haml template are escaped by default. Also
like ERB, strings marked as HTML safe are not escaped. Haml also has [its own
syntax for printing a raw string to the template](#unescaping_html).
If the `:escape_html` option is set to false when XSS protection is enabled,
Haml doesn't escape Ruby strings by default. However, if a string marked
HTML-safe is passed to [Haml's escaping syntax](#escaping_html), it won't be
escaped.
Finally, all the {Haml::Helpers Haml helpers} that return strings that are known
to be HTML safe are marked as such. In addition, string input is escaped unless
it's HTML safe.
### Ruby Module
Haml can also be used completely separately from Rails and ActionView. To do
this, install the gem with RubyGems:
gem install haml
You can then use it by including the "haml" gem in Ruby code, and using
{Haml::Engine} like so:
engine = Haml::Engine.new("%p Haml code!")
engine.render #=> "Haml code!
\n"
### Options
Haml understands various configuration options that affect its performance and
output.
In Rails, options can be set by setting the {Haml::Template#options Haml::Template.options}
hash in an initializer:
# config/initializers/haml.rb
Haml::Template.options[:format] = :html5
Outside Rails, you can set them by configuring them globally in
Haml::Options.defaults:
Haml::Options.defaults[:format] = :html5
Finally, you can also set them by passing an options hash to
{Haml::Engine#initialize}. For the complete list of available options, please
see {Haml::Options}.
### Encodings
When using Ruby 1.9 or later, Haml supports the same sorts of
encoding-declaration comments that Ruby does. Although both Ruby and Haml
support several different styles, the easiest it just to add `-# coding:
encoding-name` at the beginning of the Haml template (it must come before all
other lines). This will tell Haml that the template is encoded using the named
encoding.
By default, the HTML generated by Haml has the same encoding as the Haml
template. However, if `Encoding.default_internal` is set, Haml will attempt to
use that instead. In addition, the {Haml::Options#encoding `:encoding` option}
can be used to specify an output encoding manually.
Note that, like Ruby, Haml does not support templates encoded in UTF-16 or
UTF-32, since these encodings are not compatible with ASCII. It is possible to
use these as the output encoding, though.
## Plain Text
A substantial portion of any HTML document is its content, which is plain old
text. Any Haml line that's not interpreted as something else is taken to be
plain text, and passed through unmodified. For example:
%gee
%whiz
Wow this is cool!
is compiled to:
Wow this is cool!
Note that HTML tags are passed through unmodified as well. If you have some HTML
you don't want to convert to Haml, or you're converting a file line-by-line, you
can just include it as-is. For example:
%p
Blah!
is compiled to:
Blah!
### Escaping: `\`
The backslash character escapes the first character of a line, allowing use of
otherwise interpreted characters as plain text. For example:
%title
= @title
\= @title
is compiled to:
MyPage
= @title
## HTML Elements
### Element Name: `%`
The percent character is placed at the beginning of a line. It's followed
immediately by the name of an element, then optionally by modifiers (see below),
a space, and text to be rendered inside the element. It creates an element in
the form of ` `. For example:
%one
%two
%three Hey there
is compiled to:
Hey there
Any string is a valid element name; Haml will automatically generate opening and
closing tags for any element.
### Attributes: `{}` or `()` {#attributes}
Brackets represent a Ruby hash that is used for specifying the attributes of an
element. It is literally evaluated as a Ruby hash, so logic will work in it and
local variables may be used. Quote characters within the attribute will be
replaced by appropriate escape sequences. The hash is placed after the tag is
defined. For example:
%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}
is compiled to:
Attribute hashes can also be stretched out over multiple lines to accommodate
many attributes. However, newlines may only be placed immediately after commas.
For example:
%script{:type => "text/javascript",
:src => "javascripts/script_#{2 + 7}"}
is compiled to:
#### `:class` and `:id` Attributes
{#class-and-id-attributes}
The `:class` and `:id` attributes can also be specified as a Ruby array whose
elements will be joined together. A `:class` array is joined with `" "` and an
`:id` array is joined with `"_"`. For example:
%div{:id => [@item.type, @item.number], :class => [@item.type, @item.urgency]}
is equivalent to:
%div{:id => "#{@item.type}_#{@item.number}", :class => "#{@item.type} #{@item.urgency}"}
The array will first be flattened and any elements that do not test as true will
be removed. The remaining elements will be converted to strings. For example:
%div{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] } Contents
could render as any of:
Contents
Contents
Contents
Contents
depending on whether `@item.type` is `"numeric"` or `nil`, whether `@item == @sortcol`,
and whether `@sortdir` is `"ascending"` or `"descending"`.
If a single value is specified and it evaluates to false it is ignored;
otherwise it gets converted to a string. For example:
.item{:class => @item.is_empty? && "empty"}
could render as either of:
class="item"
class="item empty"
#### HTML-style Attributes: `()`
Haml also supports a terser, less Ruby-specific attribute syntax based on HTML's
attributes. These are used with parentheses instead of brackets, like so:
%html(xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en")
Ruby variables can be used by omitting the quotes. Local variables or instance
variables can be used. For example:
%a(title=@title href=href) Stuff
This is the same as:
%a{:title => @title, :href => href} Stuff
Because there are no commas separating attributes, though, more complicated
expressions aren't allowed. For those you'll have to use the `{}` syntax. You
can, however, use both syntaxes together:
%a(title=@title){:href => @link.href} Stuff
You can also use `#{}` interpolation to insert complicated expressions in a
HTML-style attribute:
%span(class="widget_#{@widget.number}")
HTML-style attributes can be stretched across multiple lines just like
hash-style attributes:
%script(type="text/javascript"
src="javascripts/script_#{2 + 7}")
#### Ruby 1.9-style Hashes
On Ruby 1.9, Haml also supports Ruby's new hash syntax:
%a{title: @title, href: href} Stuff
#### Attribute Methods
A Ruby method call that returns a hash can be substituted for the hash contents.
For example, {Haml::Helpers} defines the following method:
def html_attrs(lang = 'en-US')
{:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
end
This can then be used in Haml, like so:
%html{html_attrs('fr-fr')}
This is compiled to:
You can use as many such attribute methods as you want by separating them with
commas, like a Ruby argument list. All the hashes will be merged together, from
left to right. For example, if you defined
def hash1
{:bread => 'white', :filling => 'peanut butter and jelly'}
end
def hash2
{:bread => 'whole wheat'}
end
then
%sandwich{hash1, hash2, :delicious => 'true'}/
would compile to:
Note that the Haml attributes list has the same syntax as a Ruby method call.
This means that any attribute methods must come before the hash literal.
Attribute methods aren't supported for HTML-style attributes.
#### Boolean Attributes
Some attributes, such as "checked" for `input` tags or "selected" for `option`
tags, are "boolean" in the sense that their values don't matter - it only
matters whether or not they're present. In HTML (but not XHTML), these
attributes can be written as
To do this in Haml using hash-style attributes, just assign a Ruby `true` value
to the attribute:
%input{:selected => true}
In XHTML, the only valid value for these attributes is the name of the
attribute. Thus this will render in XHTML as
To set these attributes to false, simply assign them to a Ruby false value. In
both XHTML and HTML,
%input{:selected => false}
will just render as:
HTML-style boolean attributes can be written just like HTML:
%input(selected)
or using `true` and `false`:
%input(selected=true)
#### HTML5 Custom Data Attributes
HTML5 allows for adding [custom non-visible data
attributes](http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data)
to elements using attribute names beginning with `data-`. Custom data attributes
can be used in Haml by using the key `:data` with a Hash value in an attribute
hash. Each of the key/value pairs in the Hash will be transformed into a custom
data attribute. For example:
%a{:href=>"/posts", :data => {:author_id => 123}} Posts By Author
will render as:
Posts By Author
Notice that the underscore in `author_id` was replaced by a hyphen. If you wish
to suppress this behavior, you can set Haml's
{Haml::Options#hyphenate_data_attrs `:hyphenate_data_attrs` option} to `false`,
and the output will be rendered as:
Posts By Author
### Class and ID: `.` and `#`
The period and pound sign are borrowed from CSS. They are used as shortcuts to
specify the `class` and `id` attributes of an element, respectively. Multiple
class names can be specified in a similar way to CSS, by chaining the class
names together with periods. They are placed immediately after the tag and
before an attributes hash. For example:
%div#things
%span#rice Chicken Fried
%p.beans{ :food => 'true' } The magical fruit
%h1.class.otherclass#id La La La
is compiled to:
Chicken Fried
The magical fruit
La La La
And,
%div#content
%div.articles
%div.article.title Doogie Howser Comes Out
%div.article.date 2006-11-05
%div.article.entry
Neil Patrick Harris would like to dispel any rumors that he is straight
is compiled to:
Doogie Howser Comes Out
2006-11-05
Neil Patrick Harris would like to dispel any rumors that he is straight
These shortcuts can be combined with long-hand attributes; the two values will
be merged together as though they were all placed in an array (see [the
documentation on `:class` and `:id` attributes](#class-and-id-attributes)). For
example:
%div#Article.article.entry{:id => @article.number, :class => @article.visibility}
is equivalent to
%div{:id => ['Article', @article.number], :class => ['article', 'entry', @article.visibility]} Gabba Hey
and could compile to:
Gabba Hey
#### Implicit Div Elements
Because divs are used so often, they're the default elements. If you only define
a class and/or id using `.` or `#`, a div is automatically used. For example:
#collection
.item
.description What a cool item!
is the same as:
%div#collection
%div.item
%div.description What a cool item!
and is compiled to:
### Empty (void) Tags: `/`
The forward slash character, when placed at the end of a tag definition, causes
Haml to treat it as being an empty (or void) element. Depending on the format,
the tag will be rendered either without a closing tag (`:html4` or `:html5`), or
as a self-closing tag (`:xhtml`). For example:
%br/
%meta{'http-equiv' => 'Content-Type', :content => 'text/html'}/
is compiled to:
when the format is `:html4` or `:html5`, and to
when the format is `:xhtml`.
Some tags are automatically treated as being empty, as long as they have no
content in the Haml source. `meta`, `img`, `link`, `br`, `hr`, `input`,
`area`, `param`, `col` and `base` tags are treated as empty by default. This
list can be customized by setting the {Haml::Options#autoclose `:autoclose`}
option.
### Whitespace Removal: `>` and `<`
`>` and `<` give you more control over the whitespace near a tag. `>` will
remove all whitespace surrounding a tag, while `<` will remove all whitespace
immediately within a tag. You can think of them as alligators eating the
whitespace: `>` faces out of the tag and eats the whitespace on the outside, and
`<` faces into the tag and eats the whitespace on the inside. They're placed at
the end of a tag definition, after class, id, and attribute declarations but
before `/` or `=`. For example:
%blockquote<
%div
Foo!
is compiled to:
Foo!
And:
%img
%img>
%img
is compiled to:
And:
%p<= "Foo\nBar"
is compiled to:
Foo
Bar
And finally:
%img
%pre><
foo
bar
%img
is compiled to:
foo
bar
### Object Reference: `[]`
Square brackets follow a tag definition and contain a Ruby object that is used
to set the class and id of that tag. The class is set to the object's class
(transformed to use underlines rather than camel case) and the id is set to the
object's class, followed by the value of its `#to_key` or `#id` method (in that
order). This is most useful for elements that represent instances of Active
Model models. Additionally, the second argument (if present) will be used as a
prefix for both the id and class attributes. For example:
# file: app/controllers/users_controller.rb
def show
@user = CrazyUser.find(15)
end
-# file: app/views/users/show.haml
%div[@user, :greeting]
%bar[290]/
Hello!
is compiled to:
Hello!
If you require that the class be something other than the underscored object's
class, you can implement the `haml_object_ref` method on the object.
# file: app/models/crazy_user.rb
class CrazyUser < ActiveRecord::Base
def haml_object_ref
"a_crazy_user"
end
end
-# file: app/views/users/show.haml
%div[@user]
Hello!
is compiled to:
Hello!
The `:class` attribute may be used in conjunction with an object
reference. The compiled element will have the union of all classes.
- user = User.find(1)
%p[user]{:class => 'alpha bravo'}
## Doctype: `!!!`
When describing HTML documents with Haml, you can have a document type or XML
prolog generated automatically by including the characters `!!!`. For example:
!!! XML
!!!
%html
%head
%title Myspace
%body
%h1 I am the international space station
%p Sign my guestbook
is compiled to:
Myspace
I am the international space station
Sign my guestbook
You can also specify the specific doctype after the `!!!` When the
{Haml::Options#format `:format`} is set to `:xhtml`. The following doctypes are
supported:
`!!!`
: XHTML 1.0 Transitional
``
`!!! Strict`
: XHTML 1.0 Strict
``
`!!! Frameset`
: XHTML 1.0 Frameset
``
`!!! 5`
: XHTML 5
``
`!!! 1.1`
: XHTML 1.1
``
`!!! Basic`
: XHTML Basic 1.1
` `
`!!! Mobile`
: XHTML Mobile 1.2
``
`!!! RDFa`
: XHTML+RDFa 1.0
``
When the {Haml::Options#format `:format`} option is set to `:html4`, the following
doctypes are supported:
`!!!`
: HTML 4.01 Transitional
``
`!!! Strict`
: HTML 4.01 Strict
``
`!!! Frameset`
: HTML 4.01 Frameset
``
When the {Haml::Options#format `:format`} option is set to `:html5`,
`!!!` is always ``.
If you're not using the UTF-8 character set for your document, you can specify
which encoding should appear in the XML prolog in a similar way. For example:
!!! XML iso-8859-1
is compiled to:
If the mime_type of the template being rendered is `text/xml` then a format of
`:xhtml` will be used even if the global output format is set to `:html4` or
`:html5`.
## Comments
Haml supports two sorts of comments: those that show up in the HTML output and
those that don't.
### HTML Comments: `/`
The forward slash character, when placed at the beginning of a line, wraps all
text after it in an HTML comment. For example:
%peanutbutterjelly
/ This is the peanutbutterjelly element
I like sandwiches!
is compiled to:
I like sandwiches!
The forward slash can also wrap indented sections of code. For example:
/
%p This doesn't render...
%div
%h1 Because it's commented out!
is compiled to:
#### Conditional Comments: `/[]`
You can also use [Internet Explorer conditional
comments](http://www.quirksmode.org/css/condcom.html) by enclosing the condition
in square brackets after the `/`. For example:
/[if IE]
%a{ :href => 'http://www.mozilla.com/en-US/firefox/' }
%h1 Get Firefox
is compiled to:
### Haml Comments: `-#`
The hyphen followed immediately by the pound sign signifies a silent comment.
Any text following this isn't rendered in the resulting document at all.
For example:
%p foo
-# This is a comment
%p bar
is compiled to:
foo
bar
You can also nest text beneath a silent comment. None of this text will be
rendered. For example:
%p foo
-#
This won't be displayed
Nor will this
Nor will this.
%p bar
is compiled to:
foo
bar
## Ruby Evaluation
### Inserting Ruby: `=`
The equals character is followed by Ruby code. This code is evaluated and the
output is inserted into the document. For example:
%p
= ['hi', 'there', 'reader!'].join " "
= "yo"
is compiled to:
hi there reader!
yo
If the {Haml::Options#escape_html `:escape_html`} option is set, `=` will sanitize
any HTML-sensitive characters generated by the script. For example:
= ''
would be compiled to
<script>alert("I'm evil!");</script>
`=` can also be used at the end of a tag to insert Ruby code within that tag.
For example:
%p= "hello"
would be compiled to:
hello
A line of Ruby code can be stretched over multiple lines as long as each line
but the last ends with a comma. For example:
= link_to_remote "Add to cart",
:url => { :action => "add", :id => product.id },
:update => { :success => "cart", :failure => "error" }
Note that it's illegal to nest code within a tag that ends with `=`.
### Running Ruby: `-`
The hyphen character is also followed by Ruby code. This code is evaluated but
*not* inserted into the document.
**It is not recommended that you use this widely; almost all processing code and
logic should be restricted to Controllers, Helpers, or partials.**
For example:
- foo = "hello"
- foo << " there"
- foo << " you!"
%p= foo
is compiled to:
hello there you!
A line of Ruby code can be stretched over multiple lines as long as each line
but the last ends with a comma. For example:
- links = {:home => "/",
:docs => "/docs",
:about => "/about"}
#### Ruby Blocks
Ruby blocks, like XHTML tags, don't need to be explicitly closed in Haml.
Rather, they're automatically closed, based on indentation. A block begins
whenever the indentation is increased after a Ruby evaluation command. It ends
when the indentation decreases (as long as it's not an `else` clause or
something similar). For example:
- (42...47).each do |i|
%p= i
%p See, I can count!
is compiled to:
42
43
44
45
46
See, I can count!
Another example:
%p
- case 2
- when 1
= "1!"
- when 2
= "2?"
- when 3
= "3."
is compiled to:
2?
### Whitespace Preservation: `~` {#tilde}
`~` works just like `=`, except that it runs {Haml::Helpers#find\_and\_preserve}
on its input. For example,
~ "Foo\nBar\nBaz "
is the same as:
= find_and_preserve("Foo\nBar\nBaz ")
and is compiled to:
Foo
Bar
Baz
See also [Whitespace Preservation](#whitespace_preservation).
### Ruby Interpolation: `#{}`
Ruby code can also be interpolated within plain text using `#{}`, similarly to
Ruby string interpolation. For example,
%p This is #{h quality} cake!
is the same as
%p= "This is #{h quality} cake!"
and might compile to:
This is scrumptious cake!
Backslashes can be used to escape `#{}` strings, but they don't act as escapes
anywhere else in the string. For example:
%p
Look at \\#{h word} lack of backslash: \#{foo}
And yon presence thereof: \{foo}
might compile to:
Look at \yon lack of backslash: #{foo}
And yon presence thereof: \{foo}
Interpolation can also be used within [filters](#filters). For example:
:javascript
$(document).ready(function() {
alert(#{@message.to_json});
});
might compile to:
### Escaping HTML: `&=` {#escaping_html}
An ampersand followed by one or two equals characters evaluates Ruby code just
like the equals without the ampersand, but sanitizes any HTML-sensitive
characters in the result of the code. For example:
&= "I like cheese & crackers"
compiles to
I like cheese & crackers
If the {Haml::Options#escape_html `:escape_html`} option is set, `&=` behaves
identically to `=`.
`&` can also be used on its own so that `#{}` interpolation is escaped. For
example,
& I like #{"cheese & crackers"}
compiles to:
I like cheese & crackers
### Unescaping HTML: `!=` {#unescaping_html}
An exclamation mark followed by one or two equals characters evaluates Ruby code
just like the equals would, but never sanitizes the HTML.
By default, the single equals doesn't sanitize HTML either. However, if the
{Haml::Options#escape_html `:escape_html`} option is set, `=` will sanitize the
HTML, but `!=` still won't. For example, if `:escape_html` is set:
= "I feel !"
!= "I feel !"
compiles to
I feel <strong>!
I feel !
`!` can also be used on its own so that `#{}` interpolation is unescaped.
For example,
! I feel #{""}!
compiles to
I feel !
## Filters {#filters}
The colon character designates a filter. This allows you to pass an indented
block of text as input to another filtering program and add the result to the
output of Haml. The syntax is simply a colon followed by the name of the filter.
For example:
%p
:markdown
# Greetings
Hello, *World*
is compiled to:
Greetings
Hello, World
Filters can have Ruby code interpolated with `#{}`. For example:
- flavor = "raspberry"
#content
:textile
I *really* prefer _#{flavor}_ jam.
is compiled to
I really prefer raspberry jam.
Currently, filters ignore the {Haml::Options#escape_html `:escape_html`} option.
This means that `#{}` interpolation within filters is never HTML-escaped.
The functionality of some filters such as Markdown can be provided by many
different libraries. Usually you don't have to worry about this - you can just
load the gem of your choice and Haml will automatically use it.
However in some cases you may want to make Haml explicitly use a specific gem to
be used by a filter. In these cases you can do this via Tilt, the library Haml
uses to implement many of its filters:
Tilt.prefer Tilt::RedCarpetTemplate
See the [Tilt documentation](https://github.com/rtomayko/tilt#fallback-mode) for
more info.
Haml comes with the following filters defined:
{#cdata-filter}
### `:cdata`
Surrounds the filtered text with CDATA tags.
{#coffee-filter}
### `:coffee`
Compiles the filtered text to Javascript using Cofeescript. You can also
reference this filter as `:coffeescript`. This filter is implemented using
Tilt.
{#css-filter}
### `:css`
Surrounds the filtered text with `\n
",
"config" : {
"format" : "xhtml"
}
},
"content in a 'javascript' filter (XHTML)" : {
"haml" : ":javascript\n a();\n%p",
"html" : "\n
",
"config" : {
"format" : "xhtml"
}
},
"content in a 'css' filter (HTML)" : {
"haml" : ":css\n hello\n\n%p",
"html" : "\n
",
"config" : {
"format" : "html5"
}
},
"content in a 'javascript' filter (HTML)" : {
"haml" : ":javascript\n a();\n%p",
"html" : "\n
",
"config" : {
"format" : "html5"
}
}
},
"Ruby-style interpolation": {
"interpolation inside inline content" : {
"haml" : "%p #{var}",
"html" : "value
",
"optional" : true,
"locals" : {
"var" : "value"
}
},
"no interpolation when escaped" : {
"haml" : "%p \\#{var}",
"html" : "#{var}
",
"optional" : true,
"locals" : {
"var" : "value"
}
},
"interpolation when the escape character is escaped" : {
"haml" : "%p \\\\#{var}",
"html" : "\\value
",
"optional" : true,
"locals" : {
"var" : "value"
}
},
"interpolation inside filtered content" : {
"haml" : ":plain\n #{var} interpolated: #{var}",
"html" : "value interpolated: value",
"optional" : true,
"locals" : {
"var" : "value"
}
}
},
"HTML escaping" : {
"code following '&='" : {
"haml" : "&= '<\"&>'",
"html" : "<"&>"
},
"code following '=' when escape_haml is set to true" : {
"haml" : "= '<\"&>'",
"html" : "<"&>",
"config" : {
"escape_html" : "true"
}
},
"code following '!=' when escape_haml is set to true" : {
"haml" : "!= '<\"&>'",
"html" : "<\"&>",
"config" : {
"escape_html" : "true"
}
}
},
"boolean attributes" : {
"boolean attribute with XHTML" : {
"haml" : "%input(checked=true)",
"html" : " ",
"config" : {
"format" : "xhtml"
}
},
"boolean attribute with HTML" : {
"haml" : "%input(checked=true)",
"html" : " ",
"config" : {
"format" : "html5"
}
}
},
"whitespace preservation" : {
"following the '~' operator" : {
"haml" : "~ \"Foo\\nBar\\nBaz \"",
"html" : "Foo\nBar
Baz ",
"optional" : true
},
"inside a textarea tag" : {
"haml" : "%textarea\n hello\n hello",
"html" : ""
},
"inside a pre tag" : {
"haml" : "%pre\n hello\n hello",
"html" : "hello\nhello "
}
},
"whitespace removal" : {
"a tag with '>' appended and inline content" : {
"haml" : "%li hello\n%li> world\n%li again",
"html" : "hello world again "
},
"a tag with '>' appended and nested content" : {
"haml" : "%li hello\n%li>\n world\n%li again",
"html" : "hello \n world\n again "
},
"a tag with '<' appended" : {
"haml" : "%p<\n hello\n world",
"html" : "hello\nworld
"
}
}
}
haml-4.0.7/test/haml-spec/ruby_haml_test.rb 0000644 0000041 0000041 00000001477 12564177327 020720 0 ustar www-data www-data require "rubygems"
require "minitest/autorun"
require "json"
require "haml"
class HamlTest < MiniTest::Unit::TestCase
contexts = JSON.parse(File.read(File.dirname(__FILE__) + "/tests.json"))
contexts.each do |context|
context[1].each do |name, test|
define_method("test_spec: #{name} (#{context[0]})") do
html = test["html"]
haml = test["haml"]
locals = Hash[(test["locals"] || {}).map {|x, y| [x.to_sym, y]}]
options = Hash[(test["config"] || {}).map {|x, y| [x.to_sym, y]}]
options[:format] = options[:format].to_sym if options.key?(:format)
engine = Haml::Engine.new(haml, options)
result = engine.render(Object.new, locals)
assert_equal html, result.strip
end
end
end
end
haml-4.0.7/test/haml-spec/LICENSE 0000644 0000041 0000041 00000000744 12564177327 016353 0 ustar www-data www-data DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
haml-4.0.7/test/haml-spec/lua_haml_spec.lua 0000644 0000041 0000041 00000002110 12564177327 020632 0 ustar www-data www-data local dir = require 'pl.dir'
local haml = require 'haml'
local json = require 'json'
local path = require 'pl.path'
local telescope = require 'telescope'
local assert = assert
local describe = telescope.describe
local getinfo = debug.getinfo
local it = telescope.it
local open = io.open
local pairs = pairs
module('hamlspec')
local function get_tests(filename)
local me = path.abspath(getinfo(1).source:match("@(.*)$"))
return path.join(path.dirname(me), filename)
end
local json_file = get_tests("tests.json")
local file = assert(open(json_file))
local input = file:read '*a'
file:close()
local contexts = json.decode(input)
describe("LuaHaml", function()
for context, expectations in pairs(contexts) do
describe("When handling " .. context, function()
for name, exp in pairs(expectations) do
it(("should correctly render %s"):format(name), function()
local engine = haml.new(exp.config)
assert_equal(engine:render(exp.haml, exp.locals), exp.html)
end)
end
end)
end
end) haml-4.0.7/test/haml-spec/README.md 0000644 0000041 0000041 00000010223 12564177327 016616 0 ustar www-data www-data # Haml Spec #
Haml Spec provides a basic suite of tests for Haml interpreters.
It is intented for developers who are creating or maintaining an implementation
of the [Haml](http://haml-lang.com) markup language.
At the moment, there are test runners for the [original
Haml](http://github.com/nex3/haml) in Ruby, [Lua
Haml](http://github.com/norman/lua-haml) and the
[Text::Haml](http://github.com/vti/text-haml) Perl port. Support for other
versions of Haml will be added if their developers/maintainers are interested in
using it.
## The Tests ##
The tests are kept in JSON format for portability across languages. Each test
is a JSON object with expected input, output, local variables and configuration
parameters (see below). The test suite only provides tests for features which
are portable, therefore no tests for script are provided, nor for external
filters such as :markdown or :textile.
The one major exception to this are the tests for interpolation, which you may
need to modify with a regular expression to run under PHP or Perl, which
require a sigil before variable names. These tests are included despite being
less than 100% portable because interpolation is an important part of Haml and
can be tricky to implement. These tests are flagged as "optional" so that you
can avoid running them if your implementation of Haml will not support this
feature.
## Running the Tests ##
### Ruby ###
The Ruby test runner uses minitest, the same as the Ruby Haml implementation.
To run the tests you probably only need to install `haml`, `minitest` and
possibly `ruby` if your platform doesn't come with it by default. If you're
using Ruby 1.8.x, you'll also need to install `json`:
sudo gem install haml
sudo gem install minitest
# for Ruby 1.8.x; check using "ruby --version" if unsure
sudo gem install json
Then, running the Ruby test suite is easy:
ruby ruby_haml_test.rb
At the moment, running the tests with Ruby 1.8.7 fails because of issues with
the JSON library. Please use 1.9.2 until this is resolved.
### Lua ###
The Lua test depends on
[Penlight](http://stevedonovan.github.com/Penlight/),
[Telescope](http://github.com/norman/telescope),
[jason4lua](http://json.luaforge.net/), and
[Lua Haml](http://github.com/norman/lua-haml). Install and run `tsc
lua_haml_spec.lua`.
### Getting it ###
You can access the [Git repository](http://github.com/norman/haml-spec) at:
git://github.com/norman/haml-spec.git
Patches are *very* welcome, as are test runners for your Haml implementation.
As long as any test you add run against Ruby Haml and are not redundant, I'll
be very happy to add them.
### Test JSON format ###
"test name" : {
"haml" : "haml input",
"html" : "expected html output",
"result" : "expected test result",
"locals" : "local vars",
"config" : "config params",
"optional" : true|false
}
* test name: This should be a *very* brief description of what's being tested. It can
be used by the test runners to name test methods, or to exclude certain tests from being
run.
* haml: The Haml code to be evaluated. Always required.
* html: The HTML output that should be generated. Required unless "result" is "error".
* result: Can be "pass" or "error". If it's absent, then "pass" is assumed. If it's "error",
then the goal of the test is to make sure that malformed Haml code generates an error.
* locals: An object containing local variables needed for the test.
* config: An object containing configuration parameters used to run the test.
The configuration parameters should be usable directly by Ruby's Haml with no
modification. If your implementation uses config parameters with different
names, you may need to process them to make them match your implementation.
If your implementation has options that do not exist in Ruby's Haml, then you
should add tests for this in your implementation's test rather than here.
* optional: whether or not the test is optional
## License ##
This project is released under the [WTFPL](http://sam.zoy.org/wtfpl/) in order
to be as usable as possible in any project, commercial or free.
## Author ##
[Norman Clarke](mailto:norman@njclarke.com)
haml-4.0.7/test/engine_test.rb 0000644 0000041 0000041 00000173434 12564177327 016335 0 ustar www-data www-data # -*- coding: utf-8 -*-
require 'test_helper'
class EngineTest < MiniTest::Unit::TestCase
# A map of erroneous Haml documents to the error messages they should produce.
# The error messages may be arrays;
# if so, the second element should be the line number that should be reported for the error.
# If this isn't provided, the tests will assume the line number should be the last line of the document.
EXCEPTION_MAP = {
"!!!\n a" => error(:illegal_nesting_header),
"a\n b" => error(:illegal_nesting_plain),
"/ a\n b" => error(:illegal_nesting_content),
"% a" => error(:invalid_tag, '% a'),
"%p a\n b" => error(:illegal_nesting_line, 'p'),
"%p=" => error(:no_ruby_code, '='),
"%p~" => error(:no_ruby_code, '~'),
"~" => error(:no_ruby_code, '~'),
"=" => error(:no_ruby_code, '='),
"%p/\n a" => error(:illegal_nesting_self_closing),
":a\n b" => [error(:filter_not_defined, 'a'), 1],
":a= b" => error(:invalid_filter_name, 'a= b'),
"." => error(:illegal_element),
".#" => error(:illegal_element),
".{} a" => error(:illegal_element),
".() a" => error(:illegal_element),
".= a" => error(:illegal_element),
"%p..a" => error(:illegal_element),
"%a/ b" => error(:self_closing_content),
" %p foo" => error(:indenting_at_start),
" %p foo" => error(:indenting_at_start),
"- end" => error(:no_end),
"%p{:a => 'b',\n:c => 'd'}/ e" => [error(:self_closing_content), 2],
"%p{:a => 'b',\n:c => 'd'}=" => [error(:no_ruby_code, '='), 2],
"%p.{:a => 'b',\n:c => 'd'} e" => [error(:illegal_element), 1],
"%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n%p/ a" => [error(:self_closing_content), 4],
"%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n- raise 'foo'" => ["foo", 4],
"%p{:a => 'b',\n:c => raise('foo'),\n:e => 'f'}" => ["foo", 2],
"%p{:a => 'b',\n:c => 'd',\n:e => raise('foo')}" => ["foo", 3],
" \n\t\n %p foo" => [error(:indenting_at_start), 3],
"\n\n %p foo" => [error(:indenting_at_start), 3],
"%p\n foo\n foo" => [error(:inconsistent_indentation, "1 space", "2 spaces"), 3],
"%p\n foo\n%p\n foo" => [error(:inconsistent_indentation, "1 space", "2 spaces"), 4],
"%p\n\t\tfoo\n\tfoo" => [error(:inconsistent_indentation, "1 tab", "2 tabs"), 3],
"%p\n foo\n foo" => [error(:inconsistent_indentation, "3 spaces", "2 spaces"), 3],
"%p\n foo\n %p\n bar" => [error(:inconsistent_indentation, "3 spaces", "2 spaces"), 4],
"%p\n :plain\n bar\n \t baz" => [error(:inconsistent_indentation, '" \t "', "2 spaces"), 4],
"%p\n foo\n%p\n bar" => [error(:deeper_indenting, 2), 4],
"%p\n foo\n %p\n bar" => [error(:deeper_indenting, 3), 4],
"%p\n \tfoo" => [error(:cant_use_tabs_and_spaces), 2],
"%p(" => error(:invalid_attribute_list, '"("'),
"%p(foo=)" => error(:invalid_attribute_list, '"(foo=)"'),
"%p(foo 'bar')" => error(:invalid_attribute_list, '"(foo \'bar\')"'),
"%p(foo=\nbar)" => [error(:invalid_attribute_list, '"(foo="'), 1],
"%p(foo 'bar'\nbaz='bang')" => [error(:invalid_attribute_list, '"(foo \'bar\'"'), 1],
"%p(foo='bar'\nbaz 'bang'\nbip='bop')" => [error(:invalid_attribute_list, '"(foo=\'bar\' baz \'bang\'"'), 2],
"%p{'foo' => 'bar' 'bar' => 'baz'}" => :compile,
"%p{:foo => }" => :compile,
"%p{=> 'bar'}" => :compile,
"%p{'foo => 'bar'}" => :compile,
"%p{:foo => 'bar}" => :compile,
"%p{:foo => 'bar\"}" => :compile,
# Regression tests
"foo\n\n\n bar" => [error(:illegal_nesting_plain), 4],
"%p/\n\n bar" => [error(:illegal_nesting_self_closing), 3],
"%p foo\n\n bar" => [error(:illegal_nesting_line, 'p'), 3],
"/ foo\n\n bar" => [error(:illegal_nesting_content), 3],
"!!!\n\n bar" => [error(:illegal_nesting_header), 3],
"- raise 'foo'\n\n\n\nbar" => ["foo", 1],
"= 'foo'\n-raise 'foo'" => ["foo", 2],
"\n\n\n- raise 'foo'" => ["foo", 4],
"%p foo |\n bar |\n baz |\nbop\n- raise 'foo'" => ["foo", 5],
"foo\n:ruby\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6],
"foo\n:erb\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6],
"foo\n:plain\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6],
"foo\n:plain\n 1\n 2\n 3\n4\n- raise 'foo'" => ["foo", 7],
"foo\n:plain\n 1\n 2\n 3\#{''}\n- raise 'foo'" => ["foo", 6],
"foo\n:plain\n 1\n 2\n 3\#{''}\n4\n- raise 'foo'" => ["foo", 7],
"foo\n:plain\n 1\n 2\n \#{raise 'foo'}" => ["foo", 5],
"= raise 'foo'\nfoo\nbar\nbaz\nbang" => ["foo", 1],
"- case 1\n\n- when 1\n - raise 'foo'" => ["foo", 4],
}
User = Struct.new('User', :id)
class CustomHamlClass < Struct.new(:id)
def haml_object_ref
"my_thing"
end
end
CpkRecord = Struct.new('CpkRecord', :id) do
def to_key
[*self.id] unless id.nil?
end
end
def use_test_tracing(options)
unless options[:filename]
# use caller method name as fake filename. useful for debugging
i = -1
caller[i+=1] =~ /`(.+?)'/ until $1 and $1.index('test_') == 0
options[:filename] = "(#{$1})"
end
options
end
def render(text, options = {}, &block)
options = use_test_tracing(options)
super
end
def engine(text, options = {})
options = use_test_tracing(options)
Haml::Engine.new(text, options)
end
def setup
return if RUBY_VERSION < "1.9"
@old_default_internal = Encoding.default_internal
silence_warnings{Encoding.default_internal = nil}
end
def teardown
return if RUBY_VERSION < "1.9"
silence_warnings{Encoding.default_internal = @old_default_internal}
end
def test_empty_render
assert_equal "", render("")
end
def test_flexible_tabulation
assert_equal("\n foo\n
\n\n bar\n \n baz\n \n \n",
render("%p\n foo\n%q\n bar\n %a\n baz"))
assert_equal("\n foo\n
\n\n bar\n \n baz\n \n \n",
render("%p\n\tfoo\n%q\n\tbar\n\t%a\n\t\tbaz"))
assert_equal("\n \t \t bar\n baz\n
\n",
render("%p\n :plain\n \t \t bar\n baz"))
end
def test_empty_render_should_remain_empty
assert_equal('', render(''))
end
def test_attributes_should_render_correctly
assert_equal("
", render(".atlantis{:style => 'ugly'}").chomp)
end
def test_css_id_as_attribute_should_be_appended_with_underscore
assert_equal("
", render("#my_id{:id => '1'}").chomp)
assert_equal("
", render("#my_id{:id => 1}").chomp)
end
def test_ruby_code_should_work_inside_attributes
assert_equal("foo
", render("%p{:class => 1+2} foo").chomp)
end
def test_class_attr_with_array
assert_equal("foo
\n", render("%p{:class => %w[a b]} foo")) # basic
assert_equal("foo
\n", render("%p.css{:class => %w[a b]} foo")) # merge with css
assert_equal("foo
\n", render("%p.css{:class => %w[css b]} foo")) # merge uniquely
assert_equal("foo
\n", render("%p{:class => [%w[a b], %w[c d]]} foo")) # flatten
assert_equal("foo
\n", render("%p{:class => [:a, :b] } foo")) # stringify
assert_equal("foo
\n", render("%p{:class => [nil, false] } foo")) # strip falsey
assert_equal("foo
\n", render("%p{:class => :a} foo")) # single stringify
assert_equal("foo
\n", render("%p{:class => false} foo")) # single falsey
assert_equal("foo
\n", render("%p(class='html'){:class => %w[a b]} foo")) # html attrs
end
def test_id_attr_with_array
assert_equal("foo
\n", render("%p{:id => %w[a b]} foo")) # basic
assert_equal("foo
\n", render("%p#css{:id => %w[a b]} foo")) # merge with css
assert_equal("foo
\n", render("%p{:id => [%w[a b], %w[c d]]} foo")) # flatten
assert_equal("foo
\n", render("%p{:id => [:a, :b] } foo")) # stringify
assert_equal("foo
\n", render("%p{:id => [nil, false] } foo")) # strip falsey
assert_equal("foo
\n", render("%p{:id => :a} foo")) # single stringify
assert_equal("foo
\n", render("%p{:id => false} foo")) # single falsey
assert_equal("foo
\n", render("%p(id='html'){:id => %w[a b]} foo")) # html attrs
end
def test_colon_in_class_attr
assert_equal("\n", render("%p.foo:bar/"))
end
def test_colon_in_id_attr
assert_equal("
\n", render("%p#foo:bar/"))
end
def test_dynamic_attributes_with_no_content
assert_equal(<
HTML
%p
%a{:href => "http://" + "haml.info"}
HAML
end
def test_attributes_with_to_s
assert_equal(<
HTML
%p#foo{:id => 1+1}
%p.foo{:class => 1+1}
%p{:blaz => 1+1}
%p{(1+1) => 1+1}
HAML
end
def test_nil_should_render_empty_tag
assert_equal("
",
render(".no_attributes{:nil => nil}").chomp)
end
def test_strings_should_get_stripped_inside_tags
assert_equal("This should have no spaces in front of it
",
render(".stripped This should have no spaces in front of it").chomp)
end
def test_one_liner_should_be_one_line
assert_equal("Hello
", render('%p Hello').chomp)
end
def test_one_liner_with_newline_shouldnt_be_one_line
assert_equal("\n foo\n bar\n
", render('%p= "foo\nbar"').chomp)
end
def test_multi_render
engine = engine("%strong Hi there!")
assert_equal("Hi there! \n", engine.to_html)
assert_equal("Hi there! \n", engine.to_html)
assert_equal("Hi there! \n", engine.to_html)
end
def test_interpolation
assert_equal("Hello World
\n", render('%p Hello #{who}', :locals => {:who => 'World'}))
assert_equal("\n Hello World\n
\n", render("%p\n Hello \#{who}", :locals => {:who => 'World'}))
end
def test_interpolation_in_the_middle_of_a_string
assert_equal("\"title 'Title'. \"\n",
render("\"title '\#{\"Title\"}'. \""))
end
def test_interpolation_at_the_beginning_of_a_line
assert_equal("2
\n", render('%p #{1 + 1}'))
assert_equal("\n 2\n
\n", render("%p\n \#{1 + 1}"))
end
def test_escaped_interpolation
assert_equal("Foo & Bar & Baz
\n", render('%p& Foo #{"&"} Bar & Baz'))
end
def test_nil_tag_value_should_render_as_empty
assert_equal("
\n", render("%p= nil"))
end
def test_tag_with_failed_if_should_render_as_empty
assert_equal("
\n", render("%p= 'Hello' if false"))
end
def test_static_attributes_with_empty_attr
assert_equal(" \n", render("%img{:src => '/foo.png', :alt => ''}"))
end
def test_dynamic_attributes_with_empty_attr
assert_equal(" \n", render("%img{:width => nil, :src => '/foo.png', :alt => String.new}"))
end
def test_attribute_hash_with_newlines
assert_equal("foop
\n", render("%p{:a => 'b',\n :c => 'd'} foop"))
assert_equal("\n foop\n
\n", render("%p{:a => 'b',\n :c => 'd'}\n foop"))
assert_equal("\n", render("%p{:a => 'b',\n :c => 'd'}/"))
assert_equal("
\n", render("%p{:a => 'b',\n :c => 'd',\n :e => 'f'}"))
end
def test_attr_hashes_not_modified
hash = {:color => 'red'}
assert_equal(< {:hash => hash}))
HTML
%div{hash}
.special{hash}
%div{hash}
HAML
assert_equal(hash, {:color => 'red'})
end
def test_ugly_semi_prerendered_tags
assert_equal(< true))
foo
foo
foo
bar
foo
bar
foo
HTML
%p{:a => 1 + 1}
%p{:a => 1 + 1} foo
%p{:a => 1 + 1}/
%p{:a => 1 + 1}= "foo"
%p{:a => 1 + 1}= "foo\\nbar"
%p{:a => 1 + 1}~ "foo\\nbar"
%p{:a => 1 + 1}
foo
HAML
end
def test_end_of_file_multiline
assert_equal("0
\n1
\n2
\n", render("- for i in (0...3)\n %p= |\n i |"))
end
def test_cr_newline
assert_equal("foo
\nbar
\nbaz
\nboom
\n", render("%p foo\r%p bar\r\n%p baz\n\r%p boom"))
end
def test_textareas
assert_equal("\n",
render('%textarea= "Foo\n bar\n baz"'))
assert_equal("Foo
bar
baz \n",
render('%pre= "Foo\n bar\n baz"'))
assert_equal("\n",
render("%textarea #{'a' * 100}"))
assert_equal("\n \n
\n", render(<Foo
bar
baz
HTML
%pre
%code
:preserve
Foo
bar
baz
HAML
end
def test_boolean_attributes
assert_equal("
\n",
render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :html4))
assert_equal("
\n",
render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :xhtml))
assert_equal("
\n",
render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :html4))
assert_equal("
\n",
render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :xhtml))
end
def test_nuke_inner_whitespace_in_loops
assert_equal(<foobarbaz
HTML
%ul<
- for str in %w[foo bar baz]
= str
HAML
end
def test_both_whitespace_nukes_work_together
assert_equal(<Foo
Bar
RESULT
%p
%q><= "Foo\\nBar"
SOURCE
end
def test_nil_option
assert_equal("
\n", render('%p{:foo => "bar"}', :attr_wrapper => nil))
end
def test_comment_with_crazy_nesting
assert_equal(<
foo
bar
HTML
%html
%body
%img{:src => 'te'+'st'}
= "foo\\nbar"
HAML
end
end
def test_whitespace_nuke_with_both_newlines
assert_equal("foo
\n", render('%p<= "\nfoo\n"'))
assert_equal(<
foo
HTML
%p
%p<= "\\nfoo\\n"
HAML
end
def test_whitespace_nuke_with_tags_and_else
assert_equal(<
foo
HTML
%a
%b<
- if false
= "foo"
- else
foo
HAML
assert_equal(<
foo
HTML
%a
%b
- if false
= "foo"
- else
foo
HAML
end
def test_outer_whitespace_nuke_with_empty_script
assert_equal(<
foo
HTML
%p
foo
= " "
%a>
HAML
end
def test_both_case_indentation_work_with_deeply_nested_code
result = <
other
RESULT
assert_equal(result, render(< true))
= capture_haml do
foo
HAML
end
def test_plain_equals_with_ugly
assert_equal("foo\nbar\n", render(< true))
= "foo"
bar
HAML
end
def test_inline_if
assert_equal(<One
Three
HTML
- for name in ["One", "Two", "Three"]
%p= name unless name == "Two"
HAML
end
def test_end_with_method_call
assert_equal(<
2|3|4
b-a-r
HTML
%p
= [1, 2, 3].map do |i|
- i + 1
- end.join("|")
= "bar".gsub(/./) do |s|
- s + "-"
- end.gsub(/-$/) do |s|
- ''
HAML
end
def test_silent_end_with_stuff
assert_equal(<hi!
HTML
- if true
%p hi!
- end if "foo".gsub(/f/) do
- "z"
- end + "bar"
HAML
end
def test_multiline_with_colon_after_filter
assert_equal(< "Bar", |
:b => "Baz" }[:a] |
HAML
assert_equal(< "Bar", |
:b => "Baz" }[:a] |
HAML
end
def test_multiline_in_filter
assert_equal(< false))
bar
HTML
#foo{:class => ''}
bar
HAML
end
def test_escape_attrs_always
assert_equal(< :always))
bar
HTML
#foo{:class => '"<>&"'}
bar
HAML
end
def test_escape_html
html = < true))
&= "&"
!= "&"
= "&"
HAML
assert_equal(html, render(< true))
&~ "&"
!~ "&"
~ "&"
HAML
assert_equal(html, render(< true))
& \#{"&"}
! \#{"&"}
\#{"&"}
HAML
assert_equal(html, render(< true))
&== \#{"&"}
!== \#{"&"}
== \#{"&"}
HAML
tag_html = <&
&
&
HTML
assert_equal(tag_html, render(< true))
%p&= "&"
%p!= "&"
%p= "&"
HAML
assert_equal(tag_html, render(< true))
%p&~ "&"
%p!~ "&"
%p~ "&"
HAML
assert_equal(tag_html, render(< true))
%p& \#{"&"}
%p! \#{"&"}
%p \#{"&"}
HAML
assert_equal(tag_html, render(< true))
%p&== \#{"&"}
%p!== \#{"&"}
%p== \#{"&"}
HAML
end
def test_new_attrs_with_hash
assert_equal(" \n", render('%a(href="#")'))
end
def test_silent_script_with_hyphen_case
assert_equal("", render("- a = 'foo-case-bar-case'"))
end
def test_silent_script_with_hyphen_end
assert_equal("", render("- a = 'foo-end-bar-end'"))
end
def test_silent_script_with_hyphen_end_and_block
silence_warnings do
assert_equal(<foo-end
bar-end
HTML
- ("foo-end-bar-end".gsub(/\\w+-end/) do |s|
%p= s
- end; nil)
HAML
end
end
def test_if_without_content_and_else
assert_equal(<Foo\n",
render('%a(href="#" rel="top") Foo'))
assert_equal("Foo \n",
render('%a(href="#") #{"Foo"}'))
assert_equal(" \n", render('%a(href="#\\"")'))
end
def test_case_assigned_to_var
assert_equal(< true))
foo,
HTML
foo\#{"," if true}
HAML
end
# HTML escaping tests
def test_ampersand_equals_should_escape
assert_equal("\n foo & bar\n
\n", render("%p\n &= 'foo & bar'", :escape_html => false))
end
def test_ampersand_equals_inline_should_escape
assert_equal("foo & bar
\n", render("%p&= 'foo & bar'", :escape_html => false))
end
def test_ampersand_equals_should_escape_before_preserve
assert_equal("\n", render('%textarea&= "foo\nbar"', :escape_html => false))
end
def test_bang_equals_should_not_escape
assert_equal("\n foo & bar\n
\n", render("%p\n != 'foo & bar'", :escape_html => true))
end
def test_bang_equals_inline_should_not_escape
assert_equal("foo & bar
\n", render("%p!= 'foo & bar'", :escape_html => true))
end
def test_static_attributes_should_be_escaped
assert_equal(" \n",
render("%img.atlantis{:style => 'ugly&stupid'}"))
assert_equal("foo
\n",
render(".atlantis{:style => 'ugly&stupid'} foo"))
assert_equal("foo
\n",
render("%p.atlantis{:style => 'ugly&stupid'}= 'foo'"))
assert_equal("
\n",
render("%p.atlantis{:style => \"ugly\\nstupid\"}"))
end
def test_dynamic_attributes_should_be_escaped
assert_equal(" \n",
render("%img{:width => nil, :src => '&foo.png', :alt => String.new}"))
assert_equal("foo
\n",
render("%p{:width => nil, :src => '&foo.png', :alt => String.new} foo"))
assert_equal("foo
\n",
render("%div{:width => nil, :src => '&foo.png', :alt => String.new}= 'foo'"))
assert_equal(" \n",
render("%img{:width => nil, :src => \"foo\\n.png\", :alt => String.new}"))
end
def test_string_double_equals_should_be_esaped
assert_equal("4&<
\n", render("%p== \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p== \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_escaped_inline_string_double_equals
assert_equal("4&<
\n", render("%p&== \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p&== \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_unescaped_inline_string_double_equals
assert_equal("4&<
\n", render("%p!== \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p!== \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_escaped_string_double_equals
assert_equal("\n 4&<\n
\n", render("%p\n &== \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("\n 4&<\n
\n", render("%p\n &== \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_unescaped_string_double_equals
assert_equal("\n 4&<\n
\n", render("%p\n !== \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("\n 4&<\n
\n", render("%p\n !== \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_string_interpolation_should_be_esaped
assert_equal("4&<
\n", render("%p \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_escaped_inline_string_interpolation
assert_equal("4&<
\n", render("%p& \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p& \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_unescaped_inline_string_interpolation
assert_equal("4&<
\n", render("%p! \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("4&<
\n", render("%p! \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_escaped_string_interpolation
assert_equal("\n 4&<\n
\n", render("%p\n & \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("\n 4&<\n
\n", render("%p\n & \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_unescaped_string_interpolation
assert_equal("\n 4&<\n
\n", render("%p\n ! \#{2+2}&\#{'<'}", :escape_html => true))
assert_equal("\n 4&<\n
\n", render("%p\n ! \#{2+2}&\#{'<'}", :escape_html => false))
end
def test_scripts_should_respect_escape_html_option
assert_equal("\n foo & bar\n
\n", render("%p\n = 'foo & bar'", :escape_html => true))
assert_equal("\n foo & bar\n
\n", render("%p\n = 'foo & bar'", :escape_html => false))
end
def test_inline_scripts_should_respect_escape_html_option
assert_equal("foo & bar
\n", render("%p= 'foo & bar'", :escape_html => true))
assert_equal("foo & bar
\n", render("%p= 'foo & bar'", :escape_html => false))
end
def test_script_ending_in_comment_should_render_when_html_is_escaped
assert_equal("foo&bar\n", render("= 'foo&bar' #comment", :escape_html => true))
end
def test_script_with_if_shouldnt_output
assert_equal(<foo
HTML
%p= "foo"
%p= "bar" if false
HAML
end
# Options tests
def test_filename_and_line
begin
render("\n\n = abc", :filename => 'test', :line => 2)
rescue Exception => e
assert_kind_of Haml::SyntaxError, e
assert_match(/test:4/, e.backtrace.first)
end
begin
render("\n\n= 123\n\n= nil[]", :filename => 'test', :line => 2)
rescue Exception => e
assert_kind_of NoMethodError, e
backtrace = e.backtrace
backtrace.shift if rubinius?
assert_match(/test:6/, backtrace.first)
end
end
def test_stop_eval
assert_equal("", render("= 'Hello'", :suppress_eval => true))
assert_equal("", render("- haml_concat 'foo'", :suppress_eval => true))
assert_equal("\n", render("#foo{:yes => 'no'}/", :suppress_eval => true))
assert_equal("
\n", render("#foo{:yes => 'no', :call => a_function() }/", :suppress_eval => true))
assert_equal("
HTML
\xEF\xBB\xBF.foo
%p baz
HAML
end
unless RUBY_VERSION < "1.9"
def test_default_encoding
assert_equal(Encoding.find("utf-8"), render(<
"ascii-8bit"))
bâr
föö
HTML
%p bâr
%p föö
HAML
end
def test_convert_template_render_proc
assert_converts_template_properly {|e| e.render_proc.call}
end
def test_convert_template_render
assert_converts_template_properly {|e| e.render}
end
def test_convert_template_def_method
assert_converts_template_properly do |e|
o = Object.new
e.def_method(o, :render)
o.render
end
end
def test_encoding_error
render("foo\nbar\nb\xFEaz".force_encoding("utf-8"))
assert(false, "Expected exception")
rescue Haml::Error => e
assert_equal(3, e.line)
assert_match(/Invalid .* character/, e.message)
end
def test_ascii_incompatible_encoding_error
template = "foo\nbar\nb_z".encode("utf-16le")
template[9] = "\xFE".force_encoding("utf-16le")
render(template)
assert(false, "Expected exception")
rescue Haml::Error => e
assert_equal(3, e.line)
assert_match(/Invalid .* character/, e.message)
end
def test_same_coding_comment_as_encoding
assert_renders_encoded(<bâr
föö
HTML
-# coding: utf-8
%p bâr
%p föö
HAML
end
def test_coding_comments
assert_valid_encoding_comment("-# coding: ibm866")
assert_valid_encoding_comment("-# CodINg: IbM866")
assert_valid_encoding_comment("-#coding:ibm866")
assert_valid_encoding_comment("-# CodINg= ibm866")
assert_valid_encoding_comment("-# foo BAR FAOJcoding: ibm866")
assert_valid_encoding_comment("-# coding: ibm866 ASFJ (&(!$")
assert_valid_encoding_comment("-# -*- coding: ibm866")
assert_valid_encoding_comment("-# coding: ibm866 -*- coding: blah")
assert_valid_encoding_comment("-# -*- coding: ibm866 -*-")
assert_valid_encoding_comment("-# -*- encoding: ibm866 -*-")
assert_valid_encoding_comment('-# -*- coding: "ibm866" -*-')
assert_valid_encoding_comment("-#-*-coding:ibm866-*-")
assert_valid_encoding_comment("-#-*-coding:ibm866-*-")
assert_valid_encoding_comment("-# -*- foo: bar; coding: ibm866; baz: bang -*-")
assert_valid_encoding_comment("-# foo bar coding: baz -*- coding: ibm866 -*-")
assert_valid_encoding_comment("-# -*- coding: ibm866 -*- foo bar coding: baz")
end
def test_different_coding_than_system
assert_renders_encoded(<тАЬ
HTML
%p тАЬ
HAML
end
end
def test_block_spacing
begin
assert render(<<-HAML)
- foo = ["bar", "baz", "kni"]
- foo.each do | item |
= item
HAML
rescue ::SyntaxError
flunk("Should not have raised syntax error")
end
end
private
def assert_valid_encoding_comment(comment)
assert_renders_encoded(<ЖЛЫ
тАЬ
HTML
#{comment}
%p ЖЛЫ
%p тАЬ
HAML
end
def assert_converts_template_properly
engine = Haml::Engine.new(< "macRoman")
%p bâr
%p föö
HAML
assert_encoded_equal(<bâr
föö
HTML
end
def assert_renders_encoded(html, haml)
result = render(haml)
assert_encoded_equal html, result
end
def assert_encoded_equal(expected, actual)
assert_equal expected.encoding, actual.encoding
assert_equal expected, actual
end
end
haml-4.0.7/test/template_test.rb 0000644 0000041 0000041 00000023040 12564177327 016666 0 ustar www-data www-data require 'test_helper'
require 'mocks/article'
require 'action_pack/version'
module Haml::Filters::Test
include Haml::Filters::Base
def render(text)
"TESTING HAHAHAHA!"
end
end
module Haml::Helpers
def test_partial(name, locals = {})
Haml::Engine.new(File.read(File.join(TemplateTest::TEMPLATE_PATH, "_#{name}.haml"))).render(self, locals)
end
end
class Egocentic
def method_missing(*args)
self
end
end
class DummyController
attr_accessor :logger
def initialize
@logger = Egocentic.new
end
def self.controller_path
''
end
def controller_path
''
end
end
class TemplateTest < MiniTest::Unit::TestCase
TEMPLATE_PATH = File.join(File.dirname(__FILE__), "templates")
TEMPLATES = %w{ very_basic standard helpers
whitespace_handling original_engine list helpful
silent_script tag_parsing just_stuff partials
nuke_outer_whitespace nuke_inner_whitespace
render_layout partial_layout partial_layout_erb}
def setup
@base = create_base
# filters template uses :sass
# Sass::Plugin.options.update(:line_comments => true, :style => :compact)
end
def create_base
vars = { 'article' => Article.new, 'foo' => 'value one' }
base = ActionView::Base.new(TEMPLATE_PATH, vars)
# This is needed by RJS in (at least) Rails 3
base.instance_variable_set('@template', base)
# This is used by form_for.
# It's usually provided by ActionController::Base.
def base.protect_against_forgery?; false; end
base
end
def render(text, options = {})
return @base.render(:inline => text, :type => :haml) if options == :action_view
options = options.merge(:format => :xhtml)
super(text, options, @base)
end
def load_result(name)
@result = ''
File.new(File.dirname(__FILE__) + "/results/#{name}.xhtml").each_line { |l| @result += l }
@result
end
def assert_renders_correctly(name, &render_method)
old_options = Haml::Template.options.dup
Haml::Template.options[:escape_html] = false
if ActionPack::VERSION::MAJOR < 2 ||
(ActionPack::VERSION::MAJOR == 2 && ActionPack::VERSION::MINOR < 2)
render_method ||= proc { |n| @base.render(n) }
else
render_method ||= proc { |n| @base.render(:file => n) }
end
silence_warnings do
load_result(name).split("\n").zip(render_method[name].split("\n")).each_with_index do |pair, line|
message = "template: #{name}\nline: #{line}"
assert_equal(pair.first, pair.last, message)
end
end
rescue Haml::Util.av_template_class(:Error) => e
if e.message =~ /Can't run [\w:]+ filter; required (one of|file) ((?:'\w+'(?: or )?)+)(, but none were found| not found)/
puts "\nCouldn't require #{$2}; skipping a test."
else
raise e
end
ensure
Haml::Template.options = old_options
end
def test_empty_render_should_remain_empty
assert_equal('', render(''))
end
TEMPLATES.each do |template|
define_method "test_template_should_render_correctly [template: #{template}]" do
assert_renders_correctly template
end
end
def test_render_method_returning_null_with_ugly
@base.instance_eval do
def empty
nil
end
def render_something(&block)
capture(self, &block)
end
end
content_to_render = "%h1 This is part of the broken view.\n= render_something do |thing|\n = thing.empty do\n = 'test'"
result = render(content_to_render, :ugly => true)
expected_result = "This is part of the broken view. \n"
assert_equal(expected_result, result)
end
def test_simple_rendering_with_ugly
content_to_render = "%p test\n= capture { 'foo' }"
result = render(content_to_render, :ugly => true)
expected_result = "test
\nfoo\n"
assert_equal(expected_result, result)
end
def test_templates_should_render_correctly_with_render_proc
assert_renders_correctly("standard") do |name|
engine = Haml::Engine.new(File.read(File.dirname(__FILE__) + "/templates/#{name}.haml"), :format => :xhtml)
engine.render_proc(@base).call
end
end
def test_templates_should_render_correctly_with_def_method
assert_renders_correctly("standard") do |name|
engine = Haml::Engine.new(File.read(File.dirname(__FILE__) + "/templates/#{name}.haml"), :format => :xhtml)
engine.def_method(@base, "render_standard")
@base.render_standard
end
end
def test_instance_variables_should_work_inside_templates
@base.instance_variable_set("@content_for_layout", 'something')
assert_equal("something
", render("%p= @content_for_layout").chomp)
@base.instance_eval("@author = 'Hampton Catlin'")
assert_equal("Hampton Catlin
", render(".author= @author").chomp)
@base.instance_eval("@author = 'Hampton'")
assert_equal("Hampton", render("= @author").chomp)
@base.instance_eval("@author = 'Catlin'")
assert_equal("Catlin", render("= @author").chomp)
end
def test_instance_variables_should_work_inside_attributes
@base.instance_eval("@author = 'hcatlin'")
assert_equal("foo
", render("%p{:class => @author} foo").chomp)
end
def test_template_renders_should_eval
assert_equal("2\n", render("= 1+1"))
end
def test_haml_options
old_options = Haml::Template.options.dup
Haml::Template.options[:suppress_eval] = true
old_base, @base = @base, create_base
assert_renders_correctly("eval_suppressed")
ensure
@base = old_base
Haml::Template.options = old_options
end
def test_with_output_buffer_with_ugly
assert_equal(< true))
foo
baz
HTML
%p
foo
-# Parenthesis required due to Rails 3.0 deprecation of block helpers
-# that return strings.
- (with_output_buffer do
bar
= "foo".gsub(/./) do |s|
- "flup"
- end)
baz
HAML
end
def test_exceptions_should_work_correctly
begin
render("- raise 'oops!'")
rescue Exception => e
assert_equal("oops!", e.message)
assert_match(/^\(haml\):1/, e.backtrace[0])
else
assert false
end
template = < e
assert_match(/^\(haml\):5/, e.backtrace[0])
else
assert false
end
end
def test_form_builder_label_with_block
output = render(< :article, :html => {:class => nil, :id => nil}, :url => '' do |f|
= f.label :title do
Block content
HAML
fragment = Nokogiri::HTML.fragment output
assert_equal "Block content", fragment.css('form label').first.content.strip
end
## XSS Protection Tests
def test_escape_html_option_set
assert Haml::Template.options[:escape_html]
end
def test_xss_protection
assert_equal("Foo & Bar\n", render('= "Foo & Bar"', :action_view))
end
def test_xss_protection_with_safe_strings
assert_equal("Foo & Bar\n", render('= Haml::Util.html_safe("Foo & Bar")', :action_view))
end
def test_xss_protection_with_bang
assert_equal("Foo & Bar\n", render('!= "Foo & Bar"', :action_view))
end
def test_xss_protection_in_interpolation
assert_equal("Foo & Bar\n", render('Foo #{"&"} Bar', :action_view))
end
def test_xss_protection_in_attributes
assert_equal("
\n", render('%div{ "data-html" => "bar " }', :action_view))
end
def test_xss_protection_in_attributes_with_safe_strings
assert_equal("
\n", render('%div{ "data-html" => "bar ".html_safe }', :action_view))
end
def test_xss_protection_with_bang_in_interpolation
assert_equal("Foo & Bar\n", render('! Foo #{"&"} Bar', :action_view))
end
def test_xss_protection_with_safe_strings_in_interpolation
assert_equal("Foo & Bar\n", render('Foo #{Haml::Util.html_safe("&")} Bar', :action_view))
end
def test_xss_protection_with_mixed_strings_in_interpolation
assert_equal("Foo & Bar & Baz\n", render('Foo #{Haml::Util.html_safe("&")} Bar #{"&"} Baz', :action_view))
end
def test_rendered_string_is_html_safe
assert(render("Foo").html_safe?)
end
def test_rendered_string_is_html_safe_with_action_view
assert(render("Foo", :action_view).html_safe?)
end
def test_xss_html_escaping_with_non_strings
assert_equal("4\n", render("= html_escape(4)"))
end
def test_xss_protection_with_concat
assert_equal("Foo & Bar", render('- concat "Foo & Bar"', :action_view))
end
def test_xss_protection_with_concat_with_safe_string
assert_equal("Foo & Bar", render('- concat(Haml::Util.html_safe("Foo & Bar"))', :action_view))
end
def test_xss_protection_with_safe_concat
assert_equal("Foo & Bar", render('- safe_concat "Foo & Bar"', :action_view))
end
## Regression
def test_xss_protection_with_nested_haml_tag
assert_equal(<
HTML
- haml_tag :div do
- haml_tag :ul do
- haml_tag :li, "Content!"
HAML
end
if defined?(ActionView::Helpers::PrototypeHelper)
def test_rjs
assert_equal(<