haml-4.0.7/0000755000004100000410000000000012564177327012511 5ustar www-datawww-datahaml-4.0.7/FAQ.md0000644000004100000410000001147412564177327013451 0ustar www-datawww-data# Frequently Asked Questions ## Haml ### Why is my markup indented properly in development mode, but not in production? {#q-indentation-in-production} To improve performance, Haml defaults to {Haml::Options#ugly "ugly" mode} in Rails apps running in production. ### How do I put a punctuation mark after an element, like "`I like cake!`"? {#q-punctuation} Expressing the structure of a document and expressing inline formatting are two very different problems. Haml is mostly designed for structure, so the best way to deal with formatting is to leave it to other languages that are designed for it. You could use Textile: %p :textile I like *cake*! or Markdown: %p :markdown I like **cake**! or plain old XHTML: %p I like cake! If you're inserting something that's generated by a helper, like a link, then it's even easier: %p== I like #{link_to 'chocolate', 'http://franschocolates.com'}! ### How do I stop Haml from indenting the contents of my `pre` and `textarea` tags? {#q-preserve} Because Haml automatically indents the HTML source code, the contents of whitespace-sensitive tags like `pre` and `textarea` can get screwed up. The solution is to replace the newlines inside these tags with HTML newline entities (` `), which Haml does using the {Haml::Helpers#preserve} and {Haml::Helpers#find_and_preserve} helpers. Normally, Haml will do this for you automatically when you're using a tag that needs it (this can be customized using the {Haml::Options#preserve `:preserve`} option). For example, %p %textarea= "Foo\nBar" will be compiled to

However, if a helper is generating the tag, Haml can't detect that and so you'll have to call {Haml::Helpers#find_and_preserve} yourself. You can also use `~`, which is the same as `=` except that it automatically runs `find_and_preserve` on its input. For example: %p= find_and_preserve "" is the same as %p~ "" and renders

### How do I make my long lines of Ruby code look nicer in my Haml document? {#q-multiline} Put them in a helper or your model. Haml purposefully makes it annoying to put lots of Ruby code into your templates, because lots of code doesn't belong in the view. If you take that huge `link_to_remote` call and move it to a `update_sidebar_link` helper, it'll make your view both easier to read and more semantic. If you absolutely must put lots of code in your template, Haml offers a somewhat awkward multiline-continuation tool. Put a `|` (pipe character) at the end of each line you want to be merged into one (including the last line!). For example: %p= @this.is(way.too.much). | code("and I should"). | really_move.it.into( | :a => @helper) | Note that sometimes it is valid to include lots of Ruby in a template when that Ruby is a helper call that passes in a lot of template information. Thus when a function has lots of arguments, it's possible to wrap it across multiple lines as long as each line ends in a comma. For example: = link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } ### `form_for` is printing the form tag twice! Make sure you're calling it with `-`, not `=`. Just like in ERB, you have to do <% form_for stuff do %> ... <% end %> in Haml, you have to do - form_for stuff do ... ### I have Haml installed. Why is Rails (only looking for `.html.erb` files | rendering Haml files as plain text | rendering Haml files as blank pages)? {#q-blank-page} There are several reasons these things might be happening. First of all, make sure that Haml really is installed; either you've loaded the gem (via `config.gem` in Rails 2.3 or in the Gemfile in Rails 3), or `vendor/plugins/haml` exists and contains files. Then try restarting Mongrel or WEBrick or whatever you might be using. Finally, if none of these work, chances are you've got some localization plugin like Globalize installed. Such plugins often don't play nicely with Haml. Luckily, there's usually an easy fix. For Globalize, just edit `globalize/lib/globalize/rails/action_view.rb` and change @@re_extension = /\.(rjs|rhtml|rxml)$/ to @@re_extension = /\.(rjs|rhtml|rxml|erb|builder|haml)$/ For other plugins, a little searching will probably turn up a way to fix them as well. ## You still haven't answered my question! Sorry! Try looking at the [Haml](http://haml.info/docs/yardoc/file.REFERENCE.html) reference, If you can't find an answer there, feel free to ask in `#haml` on irc.freenode.net or send an email to the [mailing list](http://groups.google.com/group/haml). haml-4.0.7/Rakefile0000644000004100000410000000654712564177327014172 0ustar www-datawww-datarequire "rake/clean" require "rake/testtask" require "rubygems/package_task" task :default => :test CLEAN.replace %w(pkg doc coverage .yardoc test/haml vendor) def silence_warnings the_real_stderr, $stderr = $stderr, StringIO.new yield ensure $stderr = the_real_stderr end desc "Benchmark Haml against ERb. TIMES=n sets the number of runs, default is 1000." task :benchmark do sh "ruby benchmark.rb #{ENV['TIMES']}" end Rake::TestTask.new do |t| t.libs << 'lib' << 'test' # haml-spec tests are explicitly added after other tests so they don't # interfere with the Haml loading process which can cause test failures files = Dir["test/*_test.rb"] files.concat(Dir['test/haml-spec/*_test.rb']) t.test_files = files t.verbose = true end task :set_coverage_env do ENV["COVERAGE"] = "true" end desc "Run Simplecov (only works on 1.9)" task :coverage => [:set_coverage_env, :test] gemspec = File.expand_path("../haml.gemspec", __FILE__) if File.exist? gemspec Gem::PackageTask.new(eval(File.read(gemspec))) { |pkg| } end task :submodules do if File.exist?(File.dirname(__FILE__) + "/.git") sh %{git submodule sync} sh %{git submodule update --init --recursive} end end begin silence_warnings do require 'yard' end namespace :doc do desc "List all undocumented methods and classes." task :undocumented do command = 'yard --list --query ' command << '"object.docstring.blank? && ' command << '!(object.type == :method && object.is_alias?)"' sh command end end desc "Generate documentation" task(:doc) {sh "yard"} desc "Generate documentation incrementally" task(:redoc) {sh "yard -c"} rescue LoadError end desc < true).def_method(obj, :render) result = RubyProf.profile { times.times { obj.render } } RubyProf.const_get("#{(ENV['OUTPUT'] || 'Flat').capitalize}Printer").new(result).print end def gemfiles @gemfiles ||= begin Dir[File.dirname(__FILE__) + '/test/gemfiles/Gemfile.*']. reject {|f| f =~ /\.lock$/}. reject {|f| RUBY_VERSION < '1.9.3' && f =~ /Gemfile.rails-(\d+).\d+.x/ && $1.to_i > 3} end end def with_each_gemfile old_env = ENV['BUNDLE_GEMFILE'] gemfiles.each do |gemfile| puts "Using gemfile: #{gemfile}" ENV['BUNDLE_GEMFILE'] = gemfile yield end ensure ENV['BUNDLE_GEMFILE'] = old_env end namespace :test do namespace :bundles do desc "Install all dependencies necessary to test Haml." task :install do with_each_gemfile {sh "bundle"} end desc "Update all dependencies for testing Haml." task :update do with_each_gemfile {sh "bundle update"} end end desc "Test all supported versions of rails. This takes a while." task :rails_compatibility => 'test:bundles:install' do with_each_gemfile {sh "bundle exec rake test"} end task :rc => :rails_compatibility end haml-4.0.7/bin/0000755000004100000410000000000012564177327013261 5ustar www-datawww-datahaml-4.0.7/bin/haml0000755000004100000410000000027512564177327014134 0ustar www-datawww-data#!/usr/bin/env ruby # The command line Haml parser. $LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib' require 'haml' require 'haml/exec' opts = Haml::Exec::Haml.new(ARGV) opts.parse! haml-4.0.7/MIT-LICENSE0000644000004100000410000000207412564177327014150 0ustar www-datawww-dataCopyright (c) 2006-2009 Hampton Catlin and Nathan Weizenbaum Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.haml-4.0.7/lib/0000755000004100000410000000000012564177327013257 5ustar www-datawww-datahaml-4.0.7/lib/haml.rb0000644000004100000410000000123112564177327014522 0ustar www-datawww-datarequire 'haml/version' # The module that contains everything Haml-related: # # * {Haml::Parser} is Haml's parser. # * {Haml::Compiler} is Haml's compiler. # * {Haml::Engine} is the class used to render Haml within Ruby code. # * {Haml::Options} is where Haml's runtime options are defined. # * {Haml::Error} is raised when Haml encounters an error. # # Also see the {file:REFERENCE.md full Haml reference}. module Haml def self.init_rails(*args) # Maintain this as a no-op for any libraries that may be depending on the # previous definition here. end end require 'haml/util' require 'haml/engine' require 'haml/railtie' if defined?(Rails::Railtie) haml-4.0.7/lib/haml/0000755000004100000410000000000012564177327014200 5ustar www-datawww-datahaml-4.0.7/lib/haml/buffer.rb0000644000004100000410000002615712564177327016011 0ustar www-datawww-datamodule Haml # This class is used only internally. It holds the buffer of HTML that # is eventually output as the resulting document. # It's called from within the precompiled code, # and helps reduce the amount of processing done within `instance_eval`ed code. class Buffer include Haml::Helpers include Haml::Util # The string that holds the compiled HTML. This is aliased as # `_erbout` for compatibility with ERB-specific code. # # @return [String] attr_accessor :buffer # The options hash passed in from {Haml::Engine}. # # @return [{String => Object}] # @see Haml::Options#for_buffer attr_accessor :options # The {Buffer} for the enclosing Haml document. # This is set for partials and similar sorts of nested templates. # It's `nil` at the top level (see \{#toplevel?}). # # @return [Buffer] attr_accessor :upper # nil if there's no capture_haml block running, # and the position at which it's beginning the capture if there is one. # # @return [Fixnum, nil] attr_accessor :capture_position # @return [Boolean] # @see #active? attr_writer :active # @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? @options[:format] == :html4 end # @return [Boolean] Whether or not the format is HTML5. def html5? @options[:format] == :html5 end # @return [Boolean] Whether or not this buffer is a top-level template, # as opposed to a nested partial def toplevel? upper.nil? end # Whether or not this buffer is currently being used to render a Haml template. # Returns `false` if a subtemplate is being rendered, # even if it's a subtemplate of this buffer's template. # # @return [Boolean] def active? @active end # @return [Fixnum] The current indentation level of the document def tabulation @real_tabs + @tabulation end # Sets the current tabulation of the document. # # @param val [Fixnum] The new tabulation def tabulation=(val) val = val - @real_tabs @tabulation = val > -1 ? val : 0 end # @param upper [Buffer] The parent buffer # @param options [{Symbol => Object}] An options hash. # See {Haml::Engine#options\_for\_buffer} def initialize(upper = nil, options = {}) @active = true @upper = upper @options = options @buffer = new_encoded_string @tabulation = 0 # The number of tabs that Engine thinks we should have # @real_tabs + @tabulation is the number of tabs actually output @real_tabs = 0 end # Appends text to the buffer, properly tabulated. # Also modifies the document's indentation. # # @param text [String] The text to append # @param tab_change [Fixnum] The number of tabs by which to increase # or decrease the document's indentation # @param dont_tab_up [Boolean] If true, don't indent the first line of `text` def push_text(text, tab_change, dont_tab_up) if @tabulation > 0 # Have to push every line in by the extra user set tabulation. # Don't push lines with just whitespace, though, # because that screws up precompiled indentation. text.gsub!(/^(?!\s+$)/m, tabs) text.sub!(tabs, '') if dont_tab_up end @buffer << text @real_tabs += tab_change end # Modifies the indentation of the document. # # @param tab_change [Fixnum] The number of tabs by which to increase # or decrease the document's indentation def adjust_tabs(tab_change) @real_tabs += tab_change end Haml::Util.def_static_method(self, :format_script, [:result], :preserve_script, :in_tag, :preserve_tag, :escape_html, :nuke_inner_whitespace, :interpolated, :ugly, < <% unless ugly %> # If we're interpolated, # then the custom tabulation is handled in #push_text. # The easiest way to avoid it here is to reset @tabulation. <% if interpolated %> old_tabulation = @tabulation @tabulation = 0 <% end %> <% if !(in_tag && preserve_tag && !nuke_inner_whitespace) %> tabulation = @real_tabs <% end %> result = <%= result_name %>.<% if nuke_inner_whitespace %>strip<% else %>rstrip<% end %> <% else %> result = <%= result_name %><% if nuke_inner_whitespace %>.strip<% end %> <% end %> <% if preserve_tag %> result = Haml::Helpers.preserve(result) <% elsif preserve_script %> result = Haml::Helpers.find_and_preserve(result, options[:preserve]) <% end %> <% if ugly %> fix_textareas!(result) if toplevel? && result.include?(' <% if !(in_tag && preserve_tag && !nuke_inner_whitespace) %> has_newline = result.include?("\\n") <% end %> <% if in_tag && !nuke_inner_whitespace %> <% unless preserve_tag %> if !has_newline <% end %> @real_tabs -= 1 <% if interpolated %> @tabulation = old_tabulation <% end %> return result <% unless preserve_tag %> end <% end %> <% end %> <% if !(in_tag && preserve_tag && !nuke_inner_whitespace) %> # Precompiled tabulation may be wrong <% if !interpolated && !in_tag %> result = tabs + result if @tabulation > 0 <% end %> if has_newline result = result.gsub "\\n", "\\n" + tabs(tabulation) # Add tabulation if it wasn't precompiled <% if in_tag && !nuke_inner_whitespace %> result = tabs(tabulation) + result <% end %> end fix_textareas!(result) if toplevel? && result.include?(' result = "\\n\#{result}\\n\#{tabs(tabulation-1)}" @real_tabs -= 1 <% end %> <% if interpolated %> @tabulation = old_tabulation <% end %> result <% end %> <% end %> RUBY def attributes(class_id, obj_ref, *attributes_hashes) attributes = class_id attributes_hashes.each do |old| self.class.merge_attrs(attributes, Hash[old.map {|k, v| [k.to_s, v]}]) end self.class.merge_attrs(attributes, parse_object_ref(obj_ref)) if obj_ref Compiler.build_attributes( html?, @options[:attr_wrapper], @options[:escape_attrs], @options[:hyphenate_data_attrs], attributes) end # Remove the whitespace from the right side of the buffer string. # Doesn't do anything if we're at the beginning of a capture_haml block. def rstrip! if capture_position.nil? buffer.rstrip! return end buffer << buffer.slice!(capture_position..-1).rstrip end # Merges two attribute hashes. # This is the same as `to.merge!(from)`, # except that it merges id, class, and data attributes. # # ids are concatenated with `"_"`, # and classes are concatenated with `" "`. # data hashes are simply merged. # # Destructively modifies both `to` and `from`. # # @param to [{String => String}] The attribute hash to merge into # @param from [{String => #to_s}] The attribute hash to merge from # @return [{String => String}] `to`, after being merged def self.merge_attrs(to, from) from['id'] = Compiler.filter_and_join(from['id'], '_') if from['id'] if to['id'] && from['id'] to['id'] << '_' << from.delete('id').to_s elsif to['id'] || from['id'] from['id'] ||= to['id'] end from['class'] = Compiler.filter_and_join(from['class'], ' ') if from['class'] if to['class'] && from['class'] # Make sure we don't duplicate class names from['class'] = (from['class'].to_s.split(' ') | to['class'].split(' ')).sort.join(' ') elsif to['class'] || from['class'] from['class'] ||= to['class'] end from_data = from.delete('data') || {} to_data = to.delete('data') || {} # forces to_data & from_data into a hash from_data = { nil => from_data } unless from_data.is_a?(Hash) to_data = { nil => to_data } unless to_data.is_a?(Hash) merged_data = to_data.merge(from_data) to['data'] = merged_data unless merged_data.empty? to.merge!(from) end private # Works like #{find_and_preserve}, but allows the first newline after a # preserved opening tag to remain unencoded, and then outdents the content. # This change was motivated primarily by the change in Rails 3.2.3 to emit # a newline after textarea helpers. # # @param input [String] The text to process # @since Haml 4.0.1 # @private def fix_textareas!(input) pattern = /<(textarea)([^>]*)>(\n| )(.*?)<\/textarea>/im input.gsub!(pattern) do |s| match = pattern.match(s) content = match[4] if match[3] == ' ' content.sub!(/\A /, ' ') else content.sub!(/\A[ ]*/, '') end "<#{match[1]}#{match[2]}>\n#{content}" end end if RUBY_VERSION < "1.9" def new_encoded_string "" end else def new_encoded_string "".encode(Encoding.find(options[:encoding])) end end @@tab_cache = {} # Gets `count` tabs. Mostly for internal use. def tabs(count = 0) tabs = [count + @tabulation, 0].max @@tab_cache[tabs] ||= ' ' * tabs end # Takes an array of objects and uses the class and id of the first # one to create an attributes hash. # The second object, if present, is used as a prefix, # just like you can do with `dom_id()` and `dom_class()` in Rails def parse_object_ref(ref) prefix = ref[1] ref = ref[0] # Let's make sure the value isn't nil. If it is, return the default Hash. return {} if ref.nil? class_name = if ref.respond_to?(:haml_object_ref) ref.haml_object_ref else underscore(ref.class) end ref_id = if ref.respond_to?(:to_key) key = ref.to_key key.join('_') unless key.nil? else ref.id end id = "#{class_name}_#{ref_id || 'new'}" if prefix class_name = "#{ prefix }_#{ class_name}" id = "#{ prefix }_#{ id }" end {'id' => id, 'class' => class_name} end # Changes a word from camel case to underscores. # Based on the method of the same name in Rails' Inflector, # but copied here so it'll run properly without Rails. def underscore(camel_cased_word) camel_cased_word.to_s.gsub(/::/, '_'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end haml-4.0.7/lib/haml/filters.rb0000644000004100000410000003427612564177327016211 0ustar www-datawww-datarequire "tilt" module Haml # The module containing the default Haml filters, # as well as the base module, {Haml::Filters::Base}. # # @see Haml::Filters::Base module Filters extend self # @return [{String => Haml::Filters::Base}] a hash mapping filter names to # classes. attr_reader :defined @defined = {} # Loads an external template engine from # [Tilt](https://github.com/rtomayko/tilt) as a filter. This method is used # internally by Haml to set up filters for Sass, SCSS, Less, Coffeescript, # and others. It's left public to make it easy for developers to add their # own Tilt-based filters if they choose. # # @return [Module] The generated filter. # @param [Hash] options Options for generating the filter module. # @option options [Boolean] :precompiled Whether the filter should be # precompiled. Erb, Nokogiri and Builder use this, for example. # @option options [Class] :template_class The Tilt template class to use, # in the event it can't be inferred from an extension. # @option options [String] :extension The extension associated with the # content, for example "markdown". This lets Tilt choose the preferred # engine when there are more than one. # @option options [String,Array] :alias Any aliases for the filter. # For example, :coffee is also available as :coffeescript. # @option options [String] :extend The name of a module to extend when # defining the filter. Defaults to "Plain". This allows filters such as # Coffee to "inherit" from Javascript, wrapping its output in script tags. # @since 4.0 def register_tilt_filter(name, options = {}) if constants.map(&:to_s).include?(name.to_s) raise "#{name} filter already defined" end filter = const_set(name, Module.new) filter.extend const_get(options[:extend] || "Plain") filter.extend TiltFilter filter.extend PrecompiledTiltFilter if options.has_key? :precompiled if options.has_key? :template_class filter.template_class = options[:template_class] else filter.tilt_extension = options.fetch(:extension) { name.downcase } end # All ":coffeescript" as alias for ":coffee", etc. if options.has_key?(:alias) [options[:alias]].flatten.each {|x| Filters.defined[x.to_s] = filter} end filter end # Removes a filter from Haml. If the filter was removed, it returns # the that was remove Module upon success, or nil on failure. If you try # to redefine a filter, Haml will raise an error. Use this method first to # explicitly remove the filter before redefining it. # @return Module The filter module that has been removed # @since 4.0 def remove_filter(name) defined.delete name.to_s.downcase if constants.map(&:to_s).include?(name.to_s) remove_const name.to_sym end end # The base module for Haml filters. # User-defined filters should be modules including this module. # The name of the filter is taken by downcasing the module name. # For instance, if the module is named `FooBar`, the filter will be `:foobar`. # # A user-defined filter should override either \{#render} or {\#compile}. # \{#render} is the most common. # It takes a string, the filter source, # and returns another string, the result of the filter. # For example, the following will define a filter named `:sass`: # # module Haml::Filters::Sass # include Haml::Filters::Base # # def render(text) # ::Sass::Engine.new(text).render # end # end # # For details on overriding \{#compile}, see its documentation. # # Note that filters overriding \{#render} automatically support `#{}` # for interpolating Ruby code. # Those overriding \{#compile} will need to add such support manually # if it's desired. module Base # This method is automatically called when {Base} is included in a module. # It automatically defines a filter # with the downcased name of that module. # For example, if the module is named `FooBar`, the filter will be `:foobar`. # # @param base [Module, Class] The module that this is included in def self.included(base) Filters.defined[base.name.split("::").last.downcase] = base base.extend(base) end # Takes the source text that should be passed to the filter # and returns the result of running the filter on that string. # # This should be overridden in most individual filter modules # to render text with the given filter. # If \{#compile} is overridden, however, \{#render} doesn't need to be. # # @param text [String] The source text for the filter to process # @return [String] The filtered result # @raise [Haml::Error] if it's not overridden def render(text) raise Error.new("#{self.inspect}#render not defined!") end # Same as \{#render}, but takes a {Haml::Engine} options hash as well. # It's only safe to rely on options made available in {Haml::Engine#options\_for\_buffer}. # # @see #render # @param text [String] The source text for the filter to process # @return [String] The filtered result # @raise [Haml::Error] if it or \{#render} isn't overridden def render_with_options(text, options) render(text) end # Same as \{#compile}, but requires the necessary files first. # *This is used by {Haml::Engine} and is not intended to be overridden or used elsewhere.* # # @see #compile def internal_compile(*args) compile(*args) end # This should be overridden when a filter needs to have access to the Haml # evaluation context. Rather than applying a filter to a string at # compile-time, \{#compile} uses the {Haml::Compiler} instance to compile # the string to Ruby code that will be executed in the context of the # active Haml template. # # Warning: the {Haml::Compiler} interface is neither well-documented # nor guaranteed to be stable. # If you want to make use of it, you'll probably need to look at the # source code and should test your filter when upgrading to new Haml # versions. # # @param compiler [Haml::Compiler] The compiler instance # @param text [String] The text of the filter # @raise [Haml::Error] if none of \{#compile}, \{#render}, and # \{#render_with_options} are overridden def compile(compiler, text) filter = self compiler.instance_eval do if contains_interpolation?(text) return if options[:suppress_eval] text = unescape_interpolation(text).gsub(/(\\+)n/) do |s| escapes = $1.size next s if escapes % 2 == 0 ("\\" * (escapes - 1)) + "\n" end # We need to add a newline at the beginning to get the # filter lines to line up (since the Haml filter contains # a line that doesn't show up in the source, namely the # filter name). Then we need to escape the trailing # newline so that the whole filter block doesn't take up # too many. text = "\n" + text.sub(/\n"\Z/, "\\n\"") push_script < false find_and_preserve(#{filter.inspect}.render_with_options(#{text}, _hamlout.options)) RUBY return end rendered = Haml::Helpers::find_and_preserve(filter.render_with_options(text, compiler.options), compiler.options[:preserve]) if options[:ugly] push_text(rendered.rstrip) else push_text(rendered.rstrip.gsub("\n", "\n#{' ' * @output_tabs}")) end end end end # Does not parse the filtered text. # This is useful for large blocks of text without HTML tags, when you don't # want lines starting with `.` or `-` to be parsed. module Plain include Base # @see Base#render def render(text); text; end end # Surrounds the filtered text with `" str end end # Surrounds the filtered text with `" str end end # Surrounds the filtered text with CDATA tags. module Cdata include Base # @see Base#render def render(text) "" end end # Works the same as {Plain}, but HTML-escapes the text before placing it in # the document. module Escaped include Base # @see Base#render def render(text) Haml::Helpers.html_escape text end end # Parses the filtered text with the normal Ruby interpreter. Creates an IO # object named `haml_io`, anything written to it is output into the Haml # document. In previous version this filter redirected any output to `$stdout` # to the Haml document, this was not threadsafe and has been removed, you # should use `haml_io` instead. # # Not available if the {file:REFERENCE.md#suppress_eval-option `:suppress_eval`} # option is set to true. The Ruby code is evaluated in the same context as # the Haml template. module Ruby include Base require 'stringio' # @see Base#compile def compile(compiler, text) return if compiler.options[:suppress_eval] compiler.instance_eval do push_silent <<-FIRST.gsub("\n", ';') + text + <<-LAST.gsub("\n", ';') begin haml_io = StringIO.new(_hamlout.buffer, 'a') FIRST ensure haml_io.close haml_io = nil end LAST end end end # Inserts the filtered text into the template with whitespace preserved. # `preserve`d blocks of text aren't indented, and newlines are replaced with # the HTML escape code for newlines, to preserve nice-looking output. # # @see Haml::Helpers#preserve module Preserve include Base # @see Base#render def render(text) Haml::Helpers.preserve text end end # @private module TiltFilter extend self attr_accessor :tilt_extension, :options attr_writer :template_class def template_class (@template_class if defined? @template_class) or begin @template_class = Tilt["t.#{tilt_extension}"] or raise Error.new(Error.message(:cant_run_filter, tilt_extension)) rescue LoadError => e dep = e.message.split('--').last.strip raise Error.new(Error.message(:gem_install_filter_deps, tilt_extension, dep)) end end def self.extended(base) base.options = {} # There's a bug in 1.9.2 where the same parse tree cannot be shared # across several singleton classes -- this bug is fixed in 1.9.3. # We work around this by using a string eval instead of a block eval # so that a new parse tree is created for each singleton class. base.instance_eval %Q{ include Base def render_with_options(text, compiler_options) text = template_class.new(nil, 1, options) {text}.render super(text, compiler_options) end } end end # @private module PrecompiledTiltFilter def precompiled(text) template_class.new(nil, 1, options) { text }.send(:precompiled, {}).first end def compile(compiler, text) return if compiler.options[:suppress_eval] compiler.send(:push_script, precompiled(text)) end end # @!parse module Sass; end register_tilt_filter "Sass", :extend => "Css" # @!parse module Scss; end register_tilt_filter "Scss", :extend => "Css" # @!parse module Less; end register_tilt_filter "Less", :extend => "Css" # @!parse module Markdown; end register_tilt_filter "Markdown" # @!parse module Erb; end register_tilt_filter "Erb", :precompiled => true # @!parse module Coffee; end register_tilt_filter "Coffee", :alias => "coffeescript", :extend => "Javascript" # Parses the filtered text with ERB. # Not available if the {file:REFERENCE.md#suppress_eval-option # `:suppress_eval`} option is set to true. Embedded Ruby code is evaluated # in the same context as the Haml template. module Erb class << self def precompiled(text) #workaround for https://github.com/rtomayko/tilt/pull/183 require 'erubis' if (defined?(::Erubis) && !defined?(::Erubis::Eruby)) super.sub(/^#coding:.*?\n/, '') end end end end end # These filters have been demoted to Haml Contrib but are still included by # default in Haml 4.0. Still, we rescue from load error if for some reason # haml-contrib is not installed. begin require "haml/filters/maruku" require "haml/filters/textile" rescue LoadError end haml-4.0.7/lib/haml/parser.rb0000644000004100000410000006044412564177327016031 0ustar www-datawww-datarequire 'strscan' module Haml class Parser include Haml::Util attr_reader :root # Designates an XHTML/XML element. ELEMENT = ?% # Designates a `
` element with the given class. DIV_CLASS = ?. # Designates a `
` 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.rb0000644000004100000410000002341212564177327016222 0ustar www-datawww-datamodule 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.rb0000644000004100000410000002176212564177327016002 0ustar www-datawww-datarequire '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.rb0000644000004100000410000002441012564177327015452 0ustar www-datawww-datarequire '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 = <= 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.rb0000644000004100000410000000205512564177327020237 0ustar www-datawww-datamodule 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 endhaml-4.0.7/lib/haml/helpers.rb0000755000004100000410000005030112564177327016171 0ustar www-datawww-datamodule 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)}" 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: # # # # # # # `[[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 "" else tag << text << "" 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 << "" haml_concat tag return ret end haml_concat tag tab_up block.call tab_down haml_concat "" 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.rb0000644000004100000410000000004412564177327016210 0ustar www-datawww-datamodule Haml VERSION = '4.0.7' end haml-4.0.7/lib/haml/compiler.rb0000755000004100000410000004466112564177327016355 0ustar www-datawww-datarequire '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}" 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[: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[: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[: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/0000755000004100000410000000000012564177327015642 5ustar www-datawww-datahaml-4.0.7/lib/haml/helpers/safe_erubis_template.rb0000644000004100000410000000111112564177327022343 0ustar www-datawww-datamodule 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 endhaml-4.0.7/lib/haml/helpers/xss_mods.rb0000644000004100000410000000722712564177327020036 0ustar www-datawww-datamodule 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.rb0000644000004100000410000001134012564177327021517 0ustar www-datawww-datamodule 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 endhaml-4.0.7/lib/haml/helpers/action_view_extensions.rb0000644000004100000410000000367412564177327022767 0ustar www-datawww-datamodule 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.rb0000644000004100000410000000344612564177327022424 0ustar www-datawww-datamodule 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.rb0000644000004100000410000000606412564177327015664 0ustar www-datawww-datamodule 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.rb0000755000004100000410000003274412564177327015517 0ustar www-datawww-databegin 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.rb0000644000004100000410000000105612564177327016160 0ustar www-datawww-dataif 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::SafeErubisTemplatehaml-4.0.7/lib/haml/template.rb0000644000004100000410000000164312564177327016344 0ustar www-datawww-datarequire '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.md0000644000004100000410000011005112564177327014327 0ustar www-datawww-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:

    Teen Wolf

    Home
    ### 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:
    What a cool item!
    ### 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\n
    Bar\nBaz
    " is the same as: = find_and_preserve("Foo\n
    Bar\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\\n
    Bar\\nBaz
    \"", "html" : "Foo\n
    Bar
    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.rb0000644000004100000410000000147712564177327020720 0ustar www-datawww-datarequire "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/LICENSE0000644000004100000410000000074412564177327016353 0ustar www-datawww-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.lua0000644000004100000410000000211012564177327020632 0ustar www-datawww-datalocal 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.md0000644000004100000410000001022312564177327016616 0ustar www-datawww-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.rb0000644000004100000410000017343412564177327016335 0ustar www-datawww-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

    \n

    1

    \n

    2

    \n", render("- for i in (0...3)\n %p= |\n i |")) end def test_cr_newline assert_equal("

    foo

    \n

    bar

    \n

    baz

    \n

    boom

    \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("
    \n", render("%div[1]/", :suppress_eval => true)) assert_equal("", render(":ruby\n Kernel.puts 'hello'", :suppress_eval => true)) end def test_doctypes assert_equal('', render('!!!', :format => :html5).strip) assert_equal('', render('!!! 5').strip) assert_equal('', render('!!! strict', :format => :xhtml).strip) assert_equal('', render('!!! frameset', :format => :xhtml).strip) assert_equal('', render('!!! mobile', :format => :xhtml).strip) assert_equal('', render('!!! basic', :format => :xhtml).strip) assert_equal('', render('!!! transitional', :format => :xhtml).strip) assert_equal('', render('!!!', :format => :xhtml).strip) assert_equal('', render('!!! strict', :format => :html4).strip) assert_equal('', render('!!! frameset', :format => :html4).strip) assert_equal('', render('!!! transitional', :format => :html4).strip) assert_equal('', render('!!!', :format => :html4).strip) end def test_attr_wrapper assert_equal("

    \n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*')) assert_equal("

    \n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"')) assert_equal("

    \n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"')) assert_equal("

    \n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"')) assert_equal("\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml)) end def test_autoclose_option assert_equal("\n", render("%flaz{:foo => 'bar'}", :autoclose => ["flaz"])) assert_equal(< [/^flaz/])) HTML %flaz %flaznicate %flan HAML end def test_attrs_parsed_correctly assert_equal("

    biddly='bar => baz'>

    \n", render("%p{'boom=>biddly' => 'bar => baz'}")) assert_equal("

    \n", render("%p{'foo,bar' => 'baz, qux'}")) assert_equal("

    \n", render("%p{ :escaped => \"quo\\nte\"}")) assert_equal("

    \n", render("%p{ :escaped => \"quo\#{2 + 2}te\"}")) end def test_correct_parsing_with_brackets assert_equal("

    {tada} foo

    \n", render("%p{:class => 'foo'} {tada} foo")) assert_equal("

    deep {nested { things }}

    \n", render("%p{:class => 'foo'} deep {nested { things }}")) assert_equal("

    {a { d

    \n", render("%p{{:class => 'foo'}, :class => 'bar'} {a { d")) assert_equal("

    a}

    \n", render("%p{:foo => 'bar'} a}")) foo = [] foo[0] = Struct.new('Foo', :id).new assert_equal("

    New User]

    \n", render("%p[foo[0]] New User]", :locals => {:foo => foo})) assert_equal("

    New User]

    \n", render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo})) foo[0].id = 1 assert_equal("

    New User]

    \n", render("%p[foo[0]] New User]", :locals => {:foo => foo})) assert_equal("

    New User]

    \n", render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo})) end def test_empty_attrs assert_equal("

    empty

    \n", render("%p{ :attr => '' } empty")) assert_equal("

    empty

    \n", render("%p{ :attr => x } empty", :locals => {:x => ''})) end def test_nil_attrs assert_equal("

    nil

    \n", render("%p{ :attr => nil } nil")) assert_equal("

    nil

    \n", render("%p{ :attr => x } nil", :locals => {:x => nil})) end def test_nil_id_with_syntactic_id assert_equal("

    nil

    \n", render("%p#foo{:id => nil} nil")) assert_equal("

    nil

    \n", render("%p#foo{{:id => 'bar'}, :id => nil} nil")) assert_equal("

    nil

    \n", render("%p#foo{{:id => nil}, :id => 'bar'} nil")) end def test_nil_class_with_syntactic_class assert_equal("

    nil

    \n", render("%p.foo{:class => nil} nil")) assert_equal("

    nil

    \n", render("%p.bar.foo{:class => nil} nil")) assert_equal("

    nil

    \n", render("%p.foo{{:class => 'bar'}, :class => nil} nil")) assert_equal("

    nil

    \n", render("%p.foo{{:class => nil}, :class => 'bar'} nil")) end def test_locals assert_equal("

    Paragraph!

    \n", render("%p= text", :locals => { :text => "Paragraph!" })) end def test_dynamic_attrs_shouldnt_register_as_literal_values assert_equal("

    \n", render('%p{:a => "b#{1 + 1}c"}')) assert_equal("

    \n", render("%p{:a => 'b' + (1 + 1).to_s + 'c'}")) end def test_dynamic_attrs_with_self_closed_tag assert_equal("\nc\n", render("%a{'b' => 1 + 1}/\n= 'c'\n")) end EXCEPTION_MAP.each do |key, value| define_method("test_exception (#{key.inspect})") do begin silence_warnings do render(key, :filename => "(test_exception (#{key.inspect}))") end rescue Exception => err value = [value] unless value.is_a?(Array) expected_message, line_no = value line_no ||= key.split("\n").length if expected_message == :compile assert_match(/(compile error|syntax error|unterminated string|expecting)/, err.message, "Line: #{key}") else assert_equal(expected_message, err.message, "Line: #{key}") end else assert(false, "Exception not raised for\n#{key}") end end end def test_exception_line render("a\nb\n!!!\n c\nd") rescue Haml::SyntaxError => e assert_equal("(test_exception_line):4", e.backtrace[0]) else assert(false, '"a\nb\n!!!\n c\nd" doesn\'t produce an exception') end def test_exception render("%p\n hi\n %a= undefined\n= 12") rescue Exception => e backtrace = e.backtrace backtrace.shift if rubinius? assert_match("(test_exception):3", backtrace[0]) else # Test failed... should have raised an exception assert(false) end def test_compile_error render("a\nb\n- fee)\nc") rescue Exception => e assert_match(/\(test_compile_error\):3: (syntax error|expecting \$end)/i, e.message) else assert(false, '"a\nb\n- fee)\nc" doesn\'t produce an exception!') end def test_unbalanced_brackets render('foo #{1 + 5} foo #{6 + 7 bar #{8 + 9}') rescue Haml::SyntaxError => e assert_equal(Haml::Error.message(:unbalanced_brackets), e.message) end def test_balanced_conditional_comments assert_equal("\n", render("/[if !(IE 6)|(IE 7)] Bracket: ]")) end def test_local_assigns_dont_modify_class assert_equal("bar\n", render("= foo", :locals => {:foo => 'bar'})) assert_equal(nil, defined?(foo)) end def test_object_ref_with_nil_id user = User.new assert_equal("

    New User

    \n", render("%p[user] New User", :locals => {:user => user})) end def test_object_ref_before_attrs user = User.new 42 assert_equal("

    New User

    \n", render("%p[user]{:style => 'width: 100px;'} New User", :locals => {:user => user})) end def test_object_ref_with_custom_haml_class custom = CustomHamlClass.new 42 assert_equal("

    My Thing

    \n", render("%p[custom]{:style => 'width: 100px;'} My Thing", :locals => {:custom => custom})) end def test_object_ref_with_multiple_ids cpk_record = CpkRecord.new([42,6,9]) assert_equal("

    CPK Record

    \n", render("%p[cpk_record]{:style => 'width: 100px;'} CPK Record", :locals => {:cpk_record => cpk_record})) end def test_non_literal_attributes assert_equal("

    \n", render("%p{a2, a1, :a3 => 'baz'}", :locals => {:a1 => {:a1 => 'foo'}, :a2 => {:a2 => 'bar'}})) end def test_render_should_accept_a_binding_as_scope string = "This is a string!" string.instance_variable_set("@var", "Instance variable") b = string.instance_eval do var = "Local variable" # Silence unavoidable warning; Ruby doesn't know we're going to use this # later. nil if var binding end assert_equal("

    THIS IS A STRING!

    \n

    Instance variable

    \n

    Local variable

    \n", render("%p= upcase\n%p= @var\n%p= var", :scope => b)) end def test_yield_should_work_with_binding assert_equal("12\nFOO\n", render("= yield\n= upcase", :scope => "foo".instance_eval{binding}) { 12 }) end def test_yield_should_work_with_def_method s = "foo" engine("= yield\n= upcase").def_method(s, :render) assert_equal("12\nFOO\n", s.render { 12 }) end def test_def_method_with_module engine("= yield\n= upcase").def_method(String, :render_haml) assert_equal("12\nFOO\n", "foo".render_haml { 12 }) end def test_def_method_locals obj = Object.new engine("%p= foo\n.bar{:baz => baz}= boom").def_method(obj, :render, :foo, :baz, :boom) assert_equal("

    1

    \n
    3
    \n", obj.render(:foo => 1, :baz => 2, :boom => 3)) end def test_render_proc_locals proc = engine("%p= foo\n.bar{:baz => baz}= boom").render_proc(Object.new, :foo, :baz, :boom) assert_equal("

    1

    \n
    3
    \n", proc[:foo => 1, :baz => 2, :boom => 3]) end def test_render_proc_with_binding assert_equal("FOO\n", engine("= upcase").render_proc("foo".instance_eval{binding}).call) end def test_haml_buffer_gets_reset_even_with_exception scope = Object.new render("- raise Haml::Error", :scope => scope) assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_def_method_haml_buffer_gets_reset_even_with_exception scope = Object.new engine("- raise Haml::Error").def_method(scope, :render) scope.render assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_render_proc_haml_buffer_gets_reset_even_with_exception scope = Object.new proc = engine("- raise Haml::Error").render_proc(scope) proc.call assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_render_proc_should_raise_haml_syntax_error_not_ruby_syntax_error assert_raises(Haml::SyntaxError) do Haml::Engine.new("%p{:foo => !}").render_proc(Object.new, :foo).call end end def test_render_should_raise_haml_syntax_error_not_ruby_syntax_error assert_raises(Haml::SyntaxError) do Haml::Engine.new("%p{:foo => !}").render end end def test_ugly_true assert_equal("
    \n
    \n

    hello world

    \n
    \n
    \n", render("#outer\n #inner\n %p hello world", :ugly => true)) assert_equal("

    #{'s' * 75}

    \n", render("%p #{'s' * 75}", :ugly => true)) assert_equal("

    #{'s' * 75}

    \n", render("%p= 's' * 75", :ugly => true)) end def test_remove_whitespace_true assert_equal("

    hello world

    ", render("#outer\n #inner\n %p hello world", :remove_whitespace => true)) assert_equal("

    hello world

    foo   bar\nbaz

    ", render(< true)) %p hello world %pre foo bar baz HAML assert_equal("
    foo bar
    ", render('%div foo bar', :remove_whitespace => true)) end def test_auto_preserve_unless_ugly assert_equal("
    foo
    bar
    \n", render('%pre="foo\nbar"')) assert_equal("
    foo\nbar
    \n", render("%pre\n foo\n bar")) assert_equal("
    foo\nbar
    \n", render('%pre="foo\nbar"', :ugly => true)) assert_equal("
    foo\nbar
    \n", render("%pre\n foo\n bar", :ugly => true)) end def test_xhtml_output_option assert_equal "

    \n
    \n

    \n", render("%p\n %br", :format => :xhtml) assert_equal "
    \n", render("%a/", :format => :xhtml) end def test_arbitrary_output_option assert_raises_message(Haml::Error, "Invalid output format :html1") do engine("%br", :format => :html1) end end def test_static_hashes assert_equal("\n", render("%a{:b => 'a => b'}", :suppress_eval => true)) assert_equal("\n", render("%a{:b => 'a, b'}", :suppress_eval => true)) assert_equal("\n", render('%a{:b => "a\tb"}', :suppress_eval => true)) assert_equal("\n", render('%a{:b => "a\\#{foo}b"}', :suppress_eval => true)) assert_equal("\n", render("%a{:b => '#f00'}", :suppress_eval => true)) end def test_dynamic_hashes_with_suppress_eval assert_equal("\n", render('%a{:b => "a #{1 + 1} b", :c => "d"}', :suppress_eval => true)) end def test_interpolates_instance_vars_in_attribute_values scope = Object.new scope.instance_variable_set :@foo, 'bar' assert_equal("\n", render('%a{:b => "a #@foo b"}', :scope => scope)) end def test_interpolates_global_vars_in_attribute_values # make sure the value isn't just interpolated in during template compilation engine = Haml::Engine.new('%a{:b => "a #$global_var_for_testing b"}') $global_var_for_testing = 'bar' assert_equal("\n", engine.to_html) end def test_utf8_attrs assert_equal("\n", render("%a{:href => 'héllo'}")) assert_equal("\n", render("%a(href='héllo')")) end # HTML 4.0 def test_html_has_no_self_closing_tags assert_equal "

    \n
    \n

    \n", render("%p\n %br", :format => :html4) assert_equal "
    \n", render("%br/", :format => :html4) end def test_html_renders_empty_node_with_closing_tag assert_equal "
    \n", render(".foo", :format => :html4) end def test_html_doesnt_add_slash_to_self_closing_tags assert_equal "\n", render("%a/", :format => :html4) assert_equal "\n", render("%a{:foo => 1 + 1}/", :format => :html4) assert_equal "\n", render("%meta", :format => :html4) assert_equal "\n", render("%meta{:foo => 1 + 1}", :format => :html4) end def test_html_ignores_xml_prolog_declaration assert_equal "", render('!!! XML', :format => :html4) end def test_html_has_different_doctype assert_equal %{\n}, render('!!!', :format => :html4) end # because anything before the doctype triggers quirks mode in IE def test_xml_prolog_and_doctype_dont_result_in_a_leading_whitespace_in_html refute_match(/^\s+/, render("!!! xml\n!!!", :format => :html4)) end # HTML5 def test_html5_doctype assert_equal %{\n}, render('!!!', :format => :html5) end # HTML5 custom data attributes def test_html5_data_attributes_without_hyphenation assert_equal("
    \n", render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}", :hyphenate_data_attrs => false)) assert_equal("
    \n", render("%div{:data => {:one_plus_one => 1+1}}", :hyphenate_data_attrs => false)) assert_equal("
    \n", render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}}, :hyphenate_data_attrs => false)) #' end def test_html5_data_attributes_with_hyphens assert_equal("
    \n", render("%div{:data => {:foo_bar => 'blip'}}")) assert_equal("
    \n", render("%div{:data => {:foo_bar => 'blip', :baz => 'bang'}}")) end def test_html5_arbitrary_hash_valued_attributes_with assert_equal("
    \n", render("%div{:aria => {:foo => 'blip'}}")) assert_equal("
    \n", render("%div{:foo => {:baz => 'bang'}}")) end def test_html5_data_attributes_with_nested_hash assert_equal("
    \n", render(<<-HAML)) - hash = {:a => {:b => 'c'}} - hash[:d] = hash %div{:data => hash} HAML end def test_html5_data_attributes_with_nested_hash_and_without_hyphenation assert_equal("
    \n", render(<<-HAML, :hyphenate_data_attrs => false)) - hash = {:a => {:b => 'c'}} - hash[:d] = hash %div{:data => hash} HAML end def test_html5_data_attributes_with_multiple_defs # Should always use the more-explicit attribute assert_equal("
    \n", render("%div{:data => {:foo => 'first'}, 'data-foo' => 'second'}")) assert_equal("
    \n", render("%div{'data-foo' => 'first', :data => {:foo => 'second'}}")) end def test_html5_data_attributes_with_attr_method Haml::Helpers.module_eval do def data_hash {:data => {:foo => "bar", :baz => "bang"}} end def data_val {:data => "dat"} end end assert_equal("
    \n", render("%div{data_hash, :data => {:foo => 'blip', :brat => 'wurst'}}")) assert_equal("
    \n", render("%div{data_hash, 'data-foo' => 'blip'}")) assert_equal("
    \n", render("%div{data_hash, :data => 'dat'}")) assert_equal("
    \n", render("%div{data_val, :data => {:foo => 'blip', :brat => 'wurst'}}")) end def test_html5_data_attributes_with_identical_attribute_values assert_equal("
    \n", render("%div{:data => {:x => 50, :y => 50}}")) end def test_xml_doc_using_html5_format_and_mime_type assert_equal(< :html5, :mime_type => 'text/xml' }))
    XML !!! XML %root %element/ %hr HAML end def test_xml_doc_using_html4_format_and_mime_type assert_equal(< :html4, :mime_type => 'text/xml' }))
    XML !!! XML %root %element/ %hr HAML end # New attributes def test_basic_new_attributes assert_equal("
    bar\n", render("%a() bar")) assert_equal("bar\n", render("%a(href='foo') bar")) assert_equal("baz\n", render(%q{%a(b="c" c='d' d="e") baz})) end def test_new_attribute_ids assert_equal("
    \n", render("#foo(id='bar')")) assert_equal("
    \n", render("#foo{:id => 'bar'}(id='baz')")) assert_equal("
    \n", render("#foo(id='baz'){:id => 'bar'}")) foo = User.new(42) assert_equal("
    \n", render("#foo(id='baz'){:id => 'bar'}[foo]", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo(id='baz')[foo]{:id => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo[foo](id='baz'){:id => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo[foo]{:id => 'bar'}(id='baz')", :locals => {:foo => foo})) end def test_new_attribute_classes assert_equal("
    \n", render(".foo(class='bar')")) assert_equal("
    \n", render(".foo{:class => 'bar'}(class='baz')")) assert_equal("
    \n", render(".foo(class='baz'){:class => 'bar'}")) foo = User.new(42) assert_equal("
    \n", render(".foo(class='baz'){:class => 'bar'}[foo]", :locals => {:foo => foo})) assert_equal("
    \n", render(".foo[foo](class='baz'){:class => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render(".foo[foo]{:class => 'bar'}(class='baz')", :locals => {:foo => foo})) end def test_dynamic_new_attributes assert_equal("bar\n", render("%a(href=foo) bar", :locals => {:foo => 12})) assert_equal("bar\n", render("%a(b=b c='13' d=d) bar", :locals => {:b => 12, :d => 14})) end def test_new_attribute_interpolation assert_equal("bar\n", render('%a(href="1#{1 + 1}") bar')) assert_equal("bar\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3})) assert_equal(%Q{bar\n}, render('%a(href="1\#{1 + 1}") bar')) end def test_truthy_new_attributes assert_equal("bar\n", render("%a(href) bar", :format => :xhtml)) assert_equal("bar\n", render("%a(href bar='baz') bar", :format => :html5)) assert_equal("bar\n", render("%a(href=true) bar")) assert_equal("bar\n", render("%a(href=false) bar")) end def test_new_attribute_parsing assert_equal("bar\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'})) assert_equal(%Q{bar\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #' assert_equal(%Q{bar\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #' assert_equal(%Q{bar\n}, render(%q{%a(a='foo"bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo'bar") bar})) assert_equal("bar\n", render("%a(a:b='foo') bar")) assert_equal("bar\n", render("%a(a = 'foo' b = 'bar') bar")) assert_equal("bar\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'})) assert_equal("(b='bar')\n", render("%a(a='foo')(b='bar')")) assert_equal("baz\n", render("%a(a='foo)bar') baz")) assert_equal("baz\n", render("%a( a = 'foo' ) baz")) end def test_new_attribute_escaping assert_equal(%Q{bar\n}, render(%q{%a(a="foo \" bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\\" bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a='foo \' bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a='foo \\\\\' bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\ bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \#{1 + 1} bar") bar})) end def test_multiline_new_attribute assert_equal("bar\n", render("%a(a='b'\n c='d') bar")) assert_equal("bar\n", render("%a(a='b' b='c'\n c='d' d=e\n e='f' f='j') bar", :locals => {:e => 'e'})) end def test_new_and_old_attributes assert_equal("bar\n", render("%a(a='b'){:c => 'd'} bar")) assert_equal("bar\n", render("%a{:c => 'd'}(a='b') bar")) assert_equal("bar\n", render("%a(c='d'){:a => 'b'} bar")) assert_equal("bar\n", render("%a{:a => 'b'}(c='d') bar")) # Old-style always takes precedence over new-style, # because theoretically old-style could have arbitrary end-of-method-call syntax. assert_equal("bar\n", render("%a{:a => 'b'}(a='d') bar")) assert_equal("bar\n", render("%a(a='d'){:a => 'b'} bar")) assert_equal("bar\n", render("%a{:a => 'b',\n:b => 'c'}(c='d'\nd='e') bar")) locals = {:b => 'b', :d => 'd'} assert_equal("

    \n", render("%p{:a => b}(c=d)", :locals => locals)) assert_equal("

    \n", render("%p(a=b){:c => d}", :locals => locals)) end # Ruby Multiline def test_silent_ruby_multiline assert_equal(<foo

    HTML - foo = ["bar", "baz", "bang"] = foo.join(", ") %p foo HAML end def test_loud_ruby_multiline assert_equal(<foo

    bar

    HTML = ["bar", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_with_punctuated_methods_is_continuation assert_equal(<foo

    bar

    HTML = ["bar", " ".strip!, "".empty?, "bang"].join(", ") %p foo %p bar HAML end def test_ruby_character_literals_are_not_continuation html = if RUBY_VERSION < "1.9" "44\n44\n

    foo

    \n" else ",\n,\n

    foo

    \n" end assert_equal(html, render(<foo

    bar

    HTML &= ["bar<", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_unescaped_loud_ruby_multiline assert_equal(< true)) bar<, baz, bang

    foo

    bar

    HTML != ["bar<", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_flattened_loud_ruby_multiline assert_equal(<bar baz bang

    foo

    bar

    HTML ~ "
    " + ["bar",
                 "baz",
                 "bang"].join("\\n") + "
    " %p foo %p bar HAML end def test_loud_ruby_multiline_with_block assert_equal(<foo

    bar

    HTML = ["bar", "baz", "bang"].map do |str| - str.gsub("ba", "fa") %p foo %p bar HAML end def test_silent_ruby_multiline_with_block assert_equal(<foo

    bar

    HTML - ["bar", "baz", "bang"].map do |str| = str.gsub("ba", "fa") %p foo %p bar HAML end def test_ruby_multiline_in_tag assert_equal(<foo, bar, baz

    foo

    bar

    HTML %p= ["foo", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_escaped_ruby_multiline_in_tag assert_equal(<foo<, bar, baz

    foo

    bar

    HTML %p&= ["foo<", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_unescaped_ruby_multiline_in_tag assert_equal(< true))

    foo<, bar, baz

    foo

    bar

    HTML %p!= ["foo<", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_with_normal_multiline assert_equal(<foo

    bar

    HTML = "foo" + | "bar" + | ["bar", | "baz", "bang"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_after_filter assert_equal(<foo

    bar

    HTML :plain foo bar = ["bar", "baz", "bang"].join(", ") %p foo %p bar HAML end # Encodings def test_utf_8_bom assert_equal <

    baz

    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.rb0000644000004100000410000002304012564177327016666 0ustar www-datawww-datarequire '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(<
    • Content!
    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(< e assert_equal e.message, Haml::Error.message(:install_haml_contrib, "maruku") end end test "should raise informative error about Textile being moved to haml-contrib" do begin render(":textile\n h1. foo") flunk("Should have raised error with message about the haml-contrib gem.") rescue Haml::Error => e assert_equal e.message, Haml::Error.message(:install_haml_contrib, "textile") end end test "should respect escaped newlines and interpolation" do html = "\\n\n" haml = ":plain\n \\n\#{""}" assert_equal(html, render(haml)) end test "should process an filter with no content" do assert_equal("\n", render(':plain')) end test "should be compatible with ugly mode" do expectation = "foo\n" assert_equal(expectation, render(":plain\n foo", :ugly => true)) end test "should pass options to Tilt filters that precompile" do haml = ":erb\n <%= 'foo' %>" refute_match('TEST_VAR', Haml::Engine.new(haml).compiler.precompiled) Haml::Filters::Erb.options = {:outvar => 'TEST_VAR'} assert_match('TEST_VAR', Haml::Engine.new(haml).compiler.precompiled) end test "should pass options to Tilt filters that don't precompile" do begin filter = Class.new(Tilt::Template) do def self.name "Foo" end def prepare @engine = {:data => data, :options => options} end def evaluate(scope, locals, &block) @output = @engine[:options].to_a.join end end Haml::Filters.register_tilt_filter "Foo", :template_class => filter Haml::Filters::Foo.options[:foo] = "bar" haml = ":foo" assert_equal "foobar\n", render(haml) ensure Haml::Filters.remove_filter "Foo" end end end class ErbFilterTest < MiniTest::Unit::TestCase test "multiline expressions should work" do html = "foobarbaz\n" haml = %Q{:erb\n <%= "foo" +\n "bar" +\n "baz" %>} assert_equal(html, render(haml)) end test "should evaluate in the same context as Haml" do haml = ":erb\n <%= foo %>" html = "bar\n" scope = Object.new.instance_eval {foo = "bar"; nil if foo; binding} assert_equal(html, render(haml, :scope => scope)) end test "should use Rails's XSS safety features" do assert_equal("<img>\n", render(":erb\n <%= '' %>")) assert_equal("\n", render(":erb\n <%= ''.html_safe %>")) end end class JavascriptFilterTest < MiniTest::Unit::TestCase test "should interpolate" do scope = Object.new.instance_eval {foo = "bar"; nil if foo; binding} haml = ":javascript\n \#{foo}" html = render(haml, :scope => scope) assert_match(/bar/, html) end test "should never HTML-escape ampersands" do html = "\n" haml = %Q{:javascript\n & < > \#{"&"}} assert_equal(html, render(haml, :escape_html => true)) end test "should not include type in HTML 5 output" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5)) end test "should always include CDATA when format is xhtml" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :xhtml, :cdata => false)) end test "should omit CDATA when cdata option is false" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => false)) end test "should include CDATA when cdata option is true" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => true)) end test "should default to no CDATA when format is html5" do haml = ":javascript\n foo bar" out = render(haml, :format => :html5) refute_match('//', out) end end class CSSFilterTest < MiniTest::Unit::TestCase test "should wrap output in CDATA and a CSS tag when output is XHTML" do html = "\n" haml = ":css\n foo" assert_equal(html, render(haml, :format => :xhtml)) end test "should not include type in HTML 5 output" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5)) end test "should always include CDATA when format is xhtml" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :xhtml, :cdata => false)) end test "should omit CDATA when cdata option is false" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => false)) end test "should include CDATA when cdata option is true" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => true)) end test "should default to no CDATA when format is html5" do haml = ":css\n foo bar" out = render(haml, :format => :html5) refute_match('', out) end end class CDATAFilterTest < MiniTest::Unit::TestCase test "should wrap output in CDATA tag" do html = "\n" haml = ":cdata\n foo" assert_equal(html, render(haml)) end end class EscapedFilterTest < MiniTest::Unit::TestCase test "should escape ampersands" do html = "&\n" haml = ":escaped\n &" assert_equal(html, render(haml)) end end class RubyFilterTest < MiniTest::Unit::TestCase test "can write to haml_io" do haml = ":ruby\n haml_io.puts 'hello'\n" html = "hello\n" assert_equal(html, render(haml)) end test "haml_io appends to output" do haml = "hello\n:ruby\n haml_io.puts 'hello'\n" html = "hello\nhello\n" assert_equal(html, render(haml)) end test "can create local variables" do haml = ":ruby\n a = 7\n=a" html = "7\n" assert_equal(html, render(haml)) end endhaml-4.0.7/test/helper_test.rb0000644000004100000410000004347112564177327016344 0ustar www-datawww-datarequire 'test_helper' class ActionView::Base def nested_tag content_tag(:span) {content_tag(:div) {"something"}} end def wacky_form form_tag("/foo") {"bar"} end end module Haml::Helpers def something_that_uses_haml_concat haml_concat('foo').to_s end def render_something_with_haml_concat haml_concat "

    " end def render_something_with_haml_tag_and_concat haml_tag 'p' do haml_concat '' end end end class HelperTest < MiniTest::Unit::TestCase Post = Struct.new('Post', :body, :error_field, :errors) class PostErrors def on(name) return unless name == 'error_field' ["Really bad error"] end alias_method :full_messages, :on def [](name) on(name) || [] end end def setup @base = ActionView::Base.new @base.controller = ActionController::Base.new @base.view_paths << File.expand_path("../templates", __FILE__) if defined?(ActionController::Response) # This is needed for >=3.0.0 @base.controller.response = ActionController::Response.new end @base.instance_variable_set('@post', Post.new("Foo bar\nbaz", nil, PostErrors.new)) end def render(text, options = {}) return @base.render :inline => text, :type => :haml if options == :action_view super end def test_rendering_with_escapes output = render(<<-HAML, :action_view) - render_something_with_haml_concat - render_something_with_haml_tag_and_concat - render_something_with_haml_concat HAML assert_equal("<p>\n

    \n \n

    \n<p>\n", output) end def test_flatten assert_equal("FooBar", Haml::Helpers.flatten("FooBar")) assert_equal("FooBar", Haml::Helpers.flatten("Foo\rBar")) assert_equal("Foo Bar", Haml::Helpers.flatten("Foo\nBar")) assert_equal("Hello World! YOU ARE FLAT? OMGZ!", Haml::Helpers.flatten("Hello\nWorld!\nYOU ARE \rFLAT?\n\rOMGZ!")) end def test_list_of_should_render_correctly assert_equal("
  • 1
  • \n
  • 2
  • \n", render("= list_of([1, 2]) do |i|\n = i")) assert_equal("
  • [1]
  • \n", render("= list_of([[1]]) do |i|\n = i.inspect")) assert_equal("
  • \n

    Fee

    \n

    A word!

    \n
  • \n
  • \n

    Fi

    \n

    A word!

    \n
  • \n
  • \n

    Fo

    \n

    A word!

    \n
  • \n
  • \n

    Fum

    \n

    A word!

    \n
  • \n", render("= list_of(['Fee', 'Fi', 'Fo', 'Fum']) do |title|\n %h1= title\n %p A word!")) assert_equal("
  • 1
  • \n
  • 2
  • \n", render("= list_of([1, 2], {:c => 3}) do |i|\n = i")) assert_equal("
  • [1]
  • \n", render("= list_of([[1]], {:c => 3}) do |i|\n = i.inspect")) assert_equal("
  • \n

    Fee

    \n

    A word!

    \n
  • \n
  • \n

    Fi

    \n

    A word!

    \n
  • \n
  • \n

    Fo

    \n

    A word!

    \n
  • \n
  • \n

    Fum

    \n

    A word!

    \n
  • \n", render("= list_of(['Fee', 'Fi', 'Fo', 'Fum'], {:c => 3}) do |title|\n %h1= title\n %p A word!")) end def test_buffer_access assert(render("= buffer") =~ /#/) assert_equal(render("= (buffer == _hamlout)"), "true\n") end def test_tabs assert_equal("foo\n bar\nbaz\n", render("foo\n- tab_up\nbar\n- tab_down\nbaz")) assert_equal("

    tabbed

    \n", render("- buffer.tabulation=5\n%p tabbed")) end def test_with_tabs assert_equal(< "<%= flatten('Foo\\nBar') %>") rescue NoMethodError, Haml::Util.av_template_class(:Error) proper_behavior = true end assert(proper_behavior) begin ActionView::Base.new.render(:inline => "<%= concat('foo') %>") rescue ArgumentError, NameError proper_behavior = true end assert(proper_behavior) end def test_action_view_included assert(Haml::Helpers.action_view?) end def test_form_tag # This is usually provided by ActionController::Base. def @base.protect_against_forgery?; false; end rendered = render(<Foo bar baz\n), render('= content_tag "pre", "Foo bar\n baz"', :action_view)) end # Rails >= 3.2.3 adds a newline after opening textarea tags. def self.rails_text_area_helpers_emit_a_newline? major, minor, tiny = ActionPack::VERSION::MAJOR, ActionPack::VERSION::MINOR, ActionPack::VERSION::TINY major == 4 || ((major == 3) && (minor >= 2) && (tiny >= 3)) end def text_area_content_regex @text_area_content_regex ||= if self.class.rails_text_area_helpers_emit_a_newline? /<(textarea)[^>]*>\n(.*?)<\/\1>/im else /<(textarea)[^>]*>(.*?)<\/\1>/im end end def test_text_area_tag output = render('= text_area_tag "body", "Foo\nBar\n Baz\n Boom"', :action_view) match_data = output.match(text_area_content_regex) assert_equal "Foo Bar Baz Boom", match_data[2] end def test_text_area output = render('= text_area :post, :body', :action_view) match_data = output.match(text_area_content_regex) assert_equal "Foo bar baz", match_data[2] end def test_partials_should_not_cause_textareas_to_be_indented # non-indentation of textareas rendered inside partials @base.instance_variable_set('@post', Post.new("Foo", nil, PostErrors.new)) output = render(".foo\n .bar\n = render '/text_area_helper'", :action_view) match_data = output.match(text_area_content_regex) assert_equal 'Foo', match_data[2] end if rails_text_area_helpers_emit_a_newline? def test_textareas_should_prerve_leading_whitespace # leading whitespace preservation @base.instance_variable_set('@post', Post.new(" Foo", nil, PostErrors.new)) output = render(".foo\n = text_area :post, :body", :action_view) match_data = output.match(text_area_content_regex) assert_equal ' Foo', match_data[2] end def test_textareas_should_prerve_leading_whitespace_in_partials # leading whitespace in textareas rendered inside partials @base.instance_variable_set('@post', Post.new(" Foo", nil, PostErrors.new)) output = render(".foo\n .bar\n = render '/text_area_helper'", :action_view) match_data = output.match(text_area_content_regex) assert_equal ' Foo', match_data[2] end end def test_capture_haml assert_equal(<13

    \\n" HTML - (foo = capture_haml(13) do |a| %p= a - end) = foo.inspect HAML end def test_content_tag_block assert_equal(<

    bar

    bar
    HTML = content_tag :div do %p bar %strong bar HAML end def test_content_tag_error_wrapping def @base.protect_against_forgery?; false; end output = render(< :post, :html => {:class => nil, :id => nil}, :url => '' do |f| = f.label 'error_field' HAML fragment = Nokogiri::HTML.fragment(output) refute_nil fragment.css('form div.field_with_errors label[for=post_error_field]').first end def test_form_tag_in_helper_with_string_block def @base.protect_against_forgery?; false; end rendered = render('= wacky_form', :action_view) fragment = Nokogiri::HTML.fragment(rendered) assert_equal 'bar', fragment.text.strip assert_equal '/foo', fragment.css('form').first.attributes['action'].to_s end def test_haml_tag_name_attribute_with_id assert_equal("

    \n", render("- haml_tag 'p#some_id'")) end def test_haml_tag_name_attribute_with_colon_id assert_equal("

    \n", render("- haml_tag 'p#some:id'")) end def test_haml_tag_without_name_but_with_id assert_equal("
    \n", render("- haml_tag '#some_id'")) end def test_haml_tag_without_name_but_with_class assert_equal("
    \n", render("- haml_tag '.foo'")) end def test_haml_tag_without_name_but_with_colon_class assert_equal("
    \n", render("- haml_tag '.foo:bar'")) end def test_haml_tag_name_with_id_and_class assert_equal("

    \n", render("- haml_tag 'p#some_id.foo'")) end def test_haml_tag_name_with_class assert_equal("

    \n", render("- haml_tag 'p.foo'")) end def test_haml_tag_name_with_class_and_id assert_equal("

    \n", render("- haml_tag 'p.foo#some_id'")) end def test_haml_tag_name_with_id_and_multiple_classes assert_equal("

    \n", render("- haml_tag 'p#some_id.foo.bar'")) end def test_haml_tag_name_with_multiple_classes_and_id assert_equal("

    \n", render("- haml_tag 'p.foo.bar#some_id'")) end def test_haml_tag_name_and_attribute_classes_merging_with_id assert_equal("

    \n", render("- haml_tag 'p#some_id.foo', :class => 'bar'")) end def test_haml_tag_name_and_attribute_classes_merging assert_equal("

    \n", render("- haml_tag 'p.foo', :class => 'bar'")) end def test_haml_tag_name_merges_id_and_attribute_id assert_equal("

    \n", render("- haml_tag 'p#foo', :id => 'bar'")) end def test_haml_tag_attribute_html_escaping assert_equal("

    baz

    \n", render("%p{:id => 'foo&bar'} baz", :escape_html => true)) end def test_haml_tag_autoclosed_tags_are_closed assert_equal("
    \n", render("- haml_tag :br, :class => 'foo'")) end def test_haml_tag_with_class_array assert_equal("

    foo

    \n", render("- haml_tag :p, 'foo', :class => %w[a b]")) assert_equal("

    foo

    \n", render("- haml_tag 'p.c.d', 'foo', :class => %w[a b]")) end def test_haml_tag_with_id_array assert_equal("

    foo

    \n", render("- haml_tag :p, 'foo', :id => %w[a b]")) assert_equal("

    foo

    \n", render("- haml_tag 'p#c', 'foo', :id => %w[a b]")) end def test_haml_tag_with_data_hash assert_equal("

    foo

    \n", render("- haml_tag :p, 'foo', :data => {:foo => 'bar', :baz => true}")) end def test_haml_tag_non_autoclosed_tags_arent_closed assert_equal("

    \n", render("- haml_tag :p")) end def test_haml_tag_renders_text_on_a_single_line assert_equal("

    #{'a' * 100}

    \n", render("- haml_tag :p, 'a' * 100")) end def test_haml_tag_raises_error_for_multiple_content assert_raises(Haml::Error) { render("- haml_tag :p, 'foo' do\n bar") } end def test_haml_tag_flags assert_equal("

    \n", render("- haml_tag :p, :/")) assert_equal("

    kumquat

    \n", render("- haml_tag :p, :< do\n kumquat")) assert_raises(Haml::Error) { render("- haml_tag :p, 'foo', :/") } assert_raises(Haml::Error) { render("- haml_tag :p, :/ do\n foo") } end def test_haml_tag_error_return assert_raises(Haml::Error) { render("= haml_tag :p") } end def test_haml_tag_with_multiline_string assert_equal(< foo bar baz

    HTML - haml_tag :p, "foo\\nbar\\nbaz" HAML end def test_haml_concat_with_multiline_string assert_equal(< foo bar baz

    HTML %p - haml_concat "foo\\nbar\\nbaz" HAML end def test_haml_tag_with_ugly assert_equal(< true))

    Hi!

    HTML - haml_tag :p do - haml_tag :strong, "Hi!" HAML end def test_is_haml assert(!ActionView::Base.new.is_haml?) assert_equal("true\n", render("= is_haml?")) assert_equal("true\n", render("= is_haml?", :action_view)) assert_equal("false", @base.render(:inline => '<%= is_haml? %>')) assert_equal("false\n", render("= render :inline => '<%= is_haml? %>'", :action_view)) end def test_page_class controller = Struct.new(:controller_name, :action_name).new('troller', 'tion') scope = Struct.new(:controller).new(controller) result = render("%div{:class => page_class} MyDiv", :scope => scope) expected = "
    MyDiv
    \n" assert_equal expected, result end def test_indented_capture assert_equal(" Foo\n ", @base.render(:inline => " <% res = capture do %>\n Foo\n <% end %><%= res %>")) end def test_capture_deals_properly_with_collections Haml::Helpers.module_eval do def trc(collection, &block) collection.each do |record| haml_concat capture_haml(record, &block) end end end assert_equal("1\n\n2\n\n3\n\n", render("- trc([1, 2, 3]) do |i|\n = i.inspect")) end def test_capture_with_string_block assert_equal("foo\n", render("= capture { 'foo' }", :action_view)) end def test_capture_with_non_string_value_reurns_nil Haml::Helpers.module_eval do def check_capture_returns_nil(&block) contents = capture(&block) contents << "ERROR" if contents end end assert_equal("\n", render("= check_capture_returns_nil { 2 }", :action_view)) end def test_find_and_preserve_with_block assert_equal("
    Foo
    Bar
    \nFoo\nBar\n", render("= find_and_preserve do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_find_and_preserve_with_block_and_tags assert_equal("
    Foo\nBar
    \nFoo\nBar\n", render("= find_and_preserve([]) do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_preserve_with_block assert_equal("
    Foo
    Bar
    Foo Bar\n", render("= preserve do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_init_haml_helpers context = Object.new class << context include Haml::Helpers end context.init_haml_helpers result = context.capture_haml do context.haml_tag :p, :attr => "val" do context.haml_concat "Blah" end end assert_equal("

    \n Blah\n

    \n", result) end def test_non_haml assert_equal("false\n", render("= non_haml { is_haml? }")) end def test_content_tag_nested assert_equal "
    something
    ", render("= nested_tag", :action_view).strip end def test_error_return assert_raises(Haml::Error, < e assert_equal 2, e.backtrace[1].scan(/:(\d+)/).first.first.to_i end def test_error_return_line_in_helper render("- something_that_uses_haml_concat") assert false, "Expected Haml::Error" rescue Haml::Error => e assert_equal 15, e.backtrace[0].scan(/:(\d+)/).first.first.to_i end class ActsLikeTag # We want to be able to have people include monkeypatched ActionView helpers # without redefining is_haml?. # This is accomplished via Object#is_haml?, and this is a test for it. include ActionView::Helpers::TagHelper def to_s content_tag :p, 'some tag content' end end def test_random_class_includes_tag_helper assert_equal "

    some tag content

    ", ActsLikeTag.new.to_s end def test_capture_with_nuke_outer assert_equal "
    \n*
    hi there!
    \n", render(< hi there! HAML assert_equal "
    \n*
    hi there!
    \n", render(< hi there! HAML end def test_html_escape assert_equal ""><&", Haml::Helpers.html_escape('"><&') end def test_html_escape_should_work_on_frozen_strings begin assert Haml::Helpers.html_escape('foo'.freeze) rescue => e flunk e.message end end def test_html_escape_encoding old_stderr, $stderr = $stderr, StringIO.new string = "\"><&\u00e9" # if you're curious, u00e9 is "LATIN SMALL LETTER E WITH ACUTE" assert_equal ""><&\u00e9", Haml::Helpers.html_escape(string) assert $stderr.string == "", "html_escape shouldn't generate warnings with UTF-8 strings: #{$stderr.string}" ensure $stderr = old_stderr end def test_html_escape_non_string assert_equal('4.58', Haml::Helpers.html_escape(4.58)) assert_equal('4.58', Haml::Helpers.html_escape_without_haml_xss(4.58)) end def test_escape_once assert_equal ""><&", Haml::Helpers.escape_once('"><&') end def test_escape_once_leaves_entity_references assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') end def test_escape_once_leaves_numeric_references assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') #decimal #assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') #hexadecimal end def test_escape_once_encoding old_stderr, $stderr = $stderr, StringIO.new string = "\"><&\u00e9  " assert_equal ""><&\u00e9  ", Haml::Helpers.escape_once(string) assert $stderr.string == "", "html_escape shouldn't generate warnings with UTF-8 strings: #{$stderr.string}" ensure $stderr = old_stderr end def test_escape_once_should_work_on_frozen_strings begin Haml::Helpers.escape_once('foo'.freeze) rescue => e flunk e.message end end end haml-4.0.7/test/parser_test.rb0000644000004100000410000000612312564177327016352 0ustar www-datawww-datarequire 'test_helper' module Haml class ParserTest < MiniTest::Unit::TestCase test "should raise error for 'else' at wrong indent level" do begin parse("- if true\n #first\n text\n - else\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'else', 0, 1), e.message end end test "should raise error for 'elsif' at wrong indent level" do begin parse("- if true\n #first\n text\n - elsif false\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'elsif', 0, 1), e.message end end test "should raise error for 'else' at wrong indent level after unless" do begin parse("- unless true\n #first\n text\n - else\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'else', 0, 1), e.message end end test "should raise syntax error for else with no if" do begin parse("- else\n 'foo'") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:missing_if, 'else'), e.message end end test "should raise syntax error for nested else with no" do begin parse("#foo\n - else\n 'foo'") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:missing_if, 'else'), e.message end end test "else after if containing case is accepted" do # see issue 572 begin parse "- if true\n - case @foo\n - when 1\n bar\n- else\n bar" assert true rescue SyntaxError flunk 'else clause after if containing case should be accepted' end end test "else after if containing unless is accepted" do begin parse "- if true\n - unless @foo\n bar\n- else\n bar" assert true rescue SyntaxError flunk 'else clause after if containing unless should be accepted' end end test "loud script with else is accepted" do begin parse "= if true\n - 'A'\n-else\n - 'B'" assert true rescue SyntaxError flunk 'loud script (=) should allow else' end end test "else after nested loud script is accepted" do begin parse "-if true\n =if true\n - 'A'\n-else\n B" assert true rescue SyntaxError flunk 'else after nested loud script should be accepted' end end test "case with indented whens should allow else" do begin parse "- foo = 1\n-case foo\n -when 1\n A\n -else\n B" assert true rescue SyntaxError flunk 'case with indented whens should allow else' end end private def parse(haml, options = nil) options ||= Options.new parser = Parser.new(haml, options) parser.parse end end endhaml-4.0.7/.yardopts0000644000004100000410000000123212564177327014355 0ustar www-datawww-data--charset utf-8 --readme README.md --markup markdown --markup-provider maruku --template-path yard --default-return "" --title "Haml Documentation" --query 'object.type != :classvariable' --query 'object.type != :constant || @api && @api.text == "public"' --exclude lib/haml/template/patch.rb --exclude lib/haml/template/plugin.rb --exclude lib/haml/railtie.rb --exclude lib/haml/helpers/action_view_mods.rb --exclude lib/haml/helpers/xss_mods.rb --hide-void-return --protected --no-private --no-highlight - FAQ.md CHANGELOG.md REFERENCE.md MIT-LICENSE haml-4.0.7/CHANGELOG.md0000644000004100000410000012676412564177327014342 0ustar www-datawww-data# Haml Changelog ## 4.0.7 Released on August 10, 2015 ([diff](https://github.com/haml/haml/compare/4.0.6...4.0.7)). * Significantly improve performance of regexp used to fix whitespace handling in textareas (thanks [Stan Hu](https://github.com/stanhu)). ## 4.0.6 Released on Dec 1, 2014 ([diff](https://github.com/haml/haml/compare/4.0.5...4.0.6)). * Fix warning on Ruby 1.8.7 "regexp has invalid interval" (thanks [Elia Schito](https://github.com/elia)). ## 4.0.5 Released on Jan 7, 2014 ([diff](https://github.com/haml/haml/compare/4.0.4...4.0.5)). * Fix haml_concat appending unescaped HTML after a call to haml_tag. * Fix for bug whereby when HAML :ugly option is "true", ActionView::Helpers::CaptureHelper::capture returns the whole view buffer when passed a block that returns nothing (thanks [Mircea Moise](https://github.com/mmircea16)). ## 4.0.4 Released on November 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.3...4.0.4)). * Check for Rails::Railtie rather than Rails (thanks [Konstantin Shabanov](https://github.com/etehtsea)). * Parser fix to allow literal '#' with suppress_eval (Matt Wildig). * Helpers#escape_once works on frozen strings (as does ERB::Util.html_escape_once for which it acts as a replacement in Rails (thanks [Patrik Metzmacher](https://github.com/patrik)). * Minor test fix (thanks [Mircea Moise](https://github.com/mmircea16)). ## 4.0.3 Released May 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.2...4.0.3)). * Compatibility with newer versions of Rails's Erubis handler. * Fix Erubis handler for compatibility with Tilt 1.4.x, too. * Small performance optimization for html_escape. (thanks [Lachlan Sylvester](https://github.com/lsylvester)) * Documentation fixes. * Documented some helper methods that were left out of the reference. (thanks [Shane Riley](https://github.com/shaneriley)) ## 4.0.2 Released April 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.1...4.0.2)). * Explicitly require Erubis to work around bug in older versions of Tilt. * Fix :erb filter printing duplicate content in Rails views. (thanks [Jori Hardman](https://github.com/jorihardman)) * Replace range with slice to reduce objects created by `capture_haml`. (thanks [Tieg Zaharia](https://github.com/tiegz)) * Correct/improve some documentation. ## 4.0.1 Released March 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.0...4.0.1)). * Remove Rails 3.2.3+ textarea hack in favor of a more general solution. * Fix some performance regressions. * Fix support for Rails 4 `text_area` helper method. * Fix data attribute flattening with singleton objects. (thanks [Alisdair McDiarmid](https://github.com/alisdair)) * Fix support for sass-rails 4.0 beta. (thanks [Ryunosuke SATO](https://github.com/tricknotes)) * Load "haml/template" in Railtie in order to prevent user options set in a Rails initializer from being overwritten * Don't depend on Rails in haml/template to allow using Haml with ActionView but without Rails itself. (thanks [Hunter Haydel](https://github.com/wedgex)) ## 4.0.0 * The Haml exectutable now accepts an `--autoclose` option. You can now specify a list of tags that should be autoclosed * The `:ruby` filter no longer redirects $stdout to the Haml document, as this is not thread safe. Instead it provides a `haml_io` local variable, which is an IO object that writes to the document. * HTML5 is now the default output format rather than XHTML. This was already the default on Rails 3+, so many users will notice no difference. * The :sass filter now wraps its output in a style tag, as do the new :less and :scss filters. The :coffee filter wraps its output in a script tag. * Haml now supports only Rails 3 and above, and Ruby 1.8.7 and above. If you still need support for Rails 2 and Ruby 1.8.6, please use Haml 3.1.x which will continue to be maintained for bug fixes. * The :javascript and :css filters no longer add CDATA tags when the format is html4 or html5. This can be overridden by setting the `cdata` option to `true`. CDATA tags are always added when the format is xhtml. * HTML2Haml has been extracted to a separate gem, creatively named "html2haml". * The `:erb` filter now uses Rails's safe output buffer to provide XSS safety. * Haml's internals have been refactored to move the parser, compiler and options handling into independent classes, rather than including them all in the Engine module. You can also specify your own custom Haml parser or compiler class in Haml::Options in order to extend or modify Haml reasonably easily. * Add an {file:REFERENCE.md#hyphenate_data_attrs-option `:hyphenate_data_attrs` option} that converts underscores to hyphens in your HTML5 data keys. This is a language change from 3.1 and is enabled by default. (thanks to [Andrew Smith](https://github.com/fullsailor)) * All Hash attribute values are now treated as HTML5 data, regardless of key. Previously only the "data" key was treated this way. Allowing arbitrary keys means you can now easily use this feauture for Aria attributes, among other uses. (thanks to [Elvin Efendi](https://github.com/ElvinEfendi)) * Added `remove_whitespace` option to always remove all whitespace around Haml tags. (thanks to [Tim van der Horst](https://github.com/vdh)) * Haml now flattens deeply nested data attribute hashes. For example: `.foo{:data => {:a => "b", :c => {:d => "e", :f => "g"}}}` would render to: `
    ` (thanks to [Péter Pál Koszta](https://github.com/koszta)) * Filters that rely on third-party template engines are now implemented using [Tilt](http://github.com/rtomayko/tilt). Several new filters have been added, namely SCSS (:scss), LessCSS, (:less), and Coffeescript (:coffee/:coffeescript). Though the list of "official" filters is kept intentionally small, Haml comes with a helper method that makes adding support for other Tilt-based template engines trivial. As of 4.0, Haml will also ship with a "haml-contrib" gem that includes useful but less-frequently used filters and helpers. This includes several additional filters such as Nokogiri, Yajl, Markaby, and others. * Generate object references based on `#to_key` if it exists in preference to `#id`. * Performance improvements. (thanks to [Chris Heald](https://github.com/cheald)) * Helper `list_of` takes an extra argument that is rendered into list item attributes. (thanks [Iain Barnett](http://iainbarnett.me.uk/)) * Fix parser to allow lines ending with `some_method?` to be a Ruby multinline. (thanks to [Brad Ediger](https://github.com/bradediger)) * Always use :xhtml format when the mime_type of the rendered template is 'text/xml'. (thanks to [Stephen Bannasch](https://github.com/stepheneb)) * html2haml now includes an `--html-attributes` option. (thanks [Stefan Natchev](https://github.com/snatchev)) * Fix for inner whitespace removal in loops. (thanks [Richard Michael](https://github.com/richardkmichael)) * Use numeric character references rather than HTML entities when escaping double quotes and apostrophes in attributes. This works around some bugs in Internet Explorer earlier than version 9. (thanks [Doug Mayer](https://github.com/doxavore)) * Fix multiline silent comments: Haml previously did not allow free indentation inside multline silent comments. * Fix ordering bug with partial layouts on Rails. (thanks [Sam Pohlenz](https://github.com/spohlenz)) * Add command-line option to suppress script evaluation. * It's now possible to use Rails's asset helpers inside the Sass and SCSS filters. Note that to do so, you must make sure sass-rails is loaded in production, usually by moving it out of the assets gem group. * The Haml project now uses [semantic versioning](http://semver.org/). ## 3.2.0 The Haml 3.2 series was released only as far as 3.2.0.rc.4, but then was renamed to Haml 4.0 when the project adopted semantic versioning. ## 3.1.8 * Fix for line numbers reported from exceptions in nested blocks (thanks to Grant Hutchins & Sabrina Staedt). ## 3.1.7 * Fix for compatibility with Sass 3.2.x. (thanks [Michael Westbom](https://github.com/totallymike)). ## 3.1.6 * In indented mode, don't reindent buffers that contain preserved tags, and provide a better workaround for Rails 3.2.3's textarea helpers. ## 3.1.5 * Respect Rails' `html_safe` flag when escaping attribute values (thanks to [Gerad Suyderhoud](https://github.com/gerad)). * Fix for Rails 3.2.3 textarea helpers (thanks to [James Coleman](https://github.com/jcoleman) and others). ## 3.1.4 * Fix the use of `FormBuilder#block` with a label in Haml. * Fix indentation after a self-closing tag with dynamic attributes. ## 3.1.3 * Stop partial layouts from being displayed twice. ## 3.1.2 * If the ActionView `#capture` helper is used in a Haml template but without any Haml being run in the block, return the value of the block rather than the captured buffer. * Don't throw errors when text is nested within comments. * Fix html2haml. * Fix an issue where destructive modification was sometimes performed on Rails SafeBuffers. * Use character code entities for attribute value replacements instead of named/keyword entities. ## 3.1.1 * Update the vendored Sass to version 3.1.0. ## 3.1.0 * Don't add a `type` attribute to ` is now transformed into: :javascript function foo() { return 12; } * `
    ` and `