Method: MaRuKu::Out::HTML#to_html_code

Defined in:
lib/maruku/output/to_html.rb

#to_html_codeObject



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/maruku/output/to_html.rb', line 519

def to_html_code
  source = self.raw_code

  code_lang = self.lang || self.attributes[:lang] || @doc.attributes[:code_lang]

  code_lang = 'xml' if code_lang == 'html'
  code_lang = 'css21' if code_lang == 'css'

  use_syntax = get_setting :html_use_syntax

  element =
    if use_syntax && code_lang
      begin
        unless $syntax_loaded
          require 'rubygems'
          require 'syntax'
          require 'syntax/convertors/html'
          $syntax_loaded = true
        end
        convertor = Syntax::Convertors::HTML.for_syntax code_lang

        # eliminate trailing newlines otherwise Syntax crashes
        source = source.sub(/\n*\z/, '')

        html = convertor.convert(source)

        html.gsub!(/\'|'/,''') # IE bug

        d = MaRuKu::HTMLFragment.new(html)
        highlighted = d.to_html.sub(/\A<pre>(.*)<\/pre>\z/m, '\1')
        code = HTMLElement.new('code', { :class => code_lang }, highlighted)

        pre = xelem('pre')
        # add a class here, too, for compatibility with existing implementations
        pre['class'] = code_lang
        pre << code
        pre
      rescue LoadError => e
        maruku_error "Could not load package 'syntax'.\n" +
          "Please install it, for example using 'gem install syntax'."
        to_html_code_using_pre(source, code_lang)
      rescue => e
        maruku_error "Error while using the syntax library for code:\n#{source.inspect}" +
          "Lang is #{code_lang} object is: \n" +
          self.inspect +
          "\nException: #{e.class}: #{e.message}"

        tell_user("Using normal PRE because the syntax library did not work.")
        to_html_code_using_pre(source, code_lang)
      end
    else
      to_html_code_using_pre(source, code_lang)
    end

  color = get_setting(:code_background_color)
  if color != MaRuKu::Globals[:code_background_color]
    element['style'] = "background-color: #{color};"
  end

  add_ws element
end