haml-4.0.5/0000755000004100000410000000000012265646737012513 5ustar www-datawww-datahaml-4.0.5/FAQ.md0000644000004100000410000001147412265646737013453 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.5/Rakefile0000644000004100000410000000654712265646737014174 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.5/bin/0000755000004100000410000000000012265646737013263 5ustar www-datawww-datahaml-4.0.5/bin/haml0000755000004100000410000000027512265646737014136 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.5/MIT-LICENSE0000644000004100000410000000207412265646737014152 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.5/lib/0000755000004100000410000000000012265646737013261 5ustar www-datawww-datahaml-4.0.5/lib/haml.rb0000644000004100000410000000123112265646737014524 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.5/lib/haml/0000755000004100000410000000000012265646737014202 5ustar www-datawww-datahaml-4.0.5/lib/haml/buffer.rb0000644000004100000410000002617412265646737016012 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| )(.*?)(<\/\2>)/im input.gsub!(pattern) do |s| match = pattern.match(s) content = match[5] if match[4] == ' ' content.sub!(/\A /, ' ') else content.sub!(/\A[ ]*/, '') end "#{match[1]}<#{match[2]}#{match[3]}>\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.5/lib/haml/filters.rb0000644000004100000410000003427612265646737016213 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.5/lib/haml/temple.rb0000644000004100000410000000335012265646737016016 0ustar www-datawww-datarequire 'haml' require 'temple' module Haml module Temple module Expressions def on_plain [:static, "\n" + value[:text]] end def on_root [:multi] end def on_doctype [:html, :doctype, value[:version] || 5] end def on_tag exp = [:html, :tag, value[:name], [:html, :attrs]] if value[:value] && value[:value] != "" if value[:parse] exp.push << [:dynamic, value[:value]] else exp.push << [:static, value[:value]] end end if attribs = value[:attributes] attribs.each do |key, value| exp.last << [:html, :attr, key, [:static, value]] end end exp end end class Parser def initialize(*args) @options = Options.new end def call(haml) parser = ::Haml::Parser.new(haml, @options) tree = parser.parse.tap {|x| p x; puts '-' * 10} compile(tree).tap {|x| p x; puts '-' * 10} end private def compile(node) exp = node.to_temple return exp if node.children.empty? if node.children.length == 1 exp.push compile(node.children[0]) else exp.push [:multi, *node.children.map {|c| compile(c)}] end exp end end class Engine < ::Temple::Engine use ::Haml::Temple::Parser html :Pretty filter :ControlFlow generator :ArrayBuffer end end class Parser::ParseNode include ::Haml::Temple::Expressions def to_temple begin send "on_#{type}" end end end end Haml::Temple::Template = Temple::Templates::Tilt(Haml::Temple::Engine, :register_as => :haml)haml-4.0.5/lib/haml/parser.rb0000644000004100000410000006044312265646737016032 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.5/lib/haml/options.rb0000644000004100000410000002341212265646737016224 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.5/lib/haml/engine.rb0000644000004100000410000002176212265646737016004 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.5/lib/haml/exec.rb0000644000004100000410000002441012265646737015454 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.5/lib/haml/sass_rails_filter.rb0000644000004100000410000000205512265646737020241 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.5/lib/haml/helpers.rb0000755000004100000410000005030112265646737016173 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.5/lib/haml/version.rb0000644000004100000410000000004412265646737016212 0ustar www-datawww-datamodule Haml VERSION = "4.0.5" end haml-4.0.5/lib/haml/compiler.rb0000755000004100000410000004466112265646737016357 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.5/lib/haml/helpers/0000755000004100000410000000000012265646737015644 5ustar www-datawww-datahaml-4.0.5/lib/haml/helpers/safe_erubis_template.rb0000644000004100000410000000111112265646737022345 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.5/lib/haml/helpers/xss_mods.rb0000644000004100000410000000722712265646737020040 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.5/lib/haml/helpers/action_view_mods.rb0000644000004100000410000001134012265646737021521 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.5/lib/haml/helpers/action_view_extensions.rb0000644000004100000410000000367412265646737022771 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.5/lib/haml/helpers/action_view_xss_mods.rb0000644000004100000410000000344612265646737022426 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.5/lib/haml/error.rb0000644000004100000410000000606412265646737015666 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.5/lib/haml/util.rb0000755000004100000410000003274412265646737015521 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.5/lib/haml/railtie.rb0000644000004100000410000000105612265646737016162 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.5/lib/haml/template.rb0000644000004100000410000000164312265646737016346 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.5/REFERENCE.md0000644000004100000410000011005112265646737014331 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 me 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" 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.5/test/helper_test.rb0000644000004100000410000004320512265646737016341 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 assert_equal(<#{rails_form_opener}

    bar

    baz HTML = form_tag 'foo' do %p bar %strong baz HAML end def test_pre assert_equal(%(
    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 assert_equal(<#{rails_form_opener}bar HTML = wacky_form HAML 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.5/test/parser_test.rb0000644000004100000410000000612312265646737016354 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.5/.yardopts0000644000004100000410000000123212265646737014357 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.5/CHANGELOG.md0000644000004100000410000012607612265646737014340 0ustar www-datawww-data# Haml Changelog ======= ## 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 `