# $Id: wikitext.rb,v 1.38 2004/04/27 16:12:31 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'qwik/parser'
require 'qwik/formatter'
require 'qwik/interwiki'
require 'qwik/qxml'
require 'qwik/resolve'

class String
  def w
    Qwik::WikiText.new(self)
  end
end

module Qwik
  class WikiText < String
    def initialize(str)
      super(str)
      @xml = nil
    end

    def tokens()
      Hiki::QwikParser.new.parse(self)
    end

    def format()
      Hiki::HTMLFormatter.new(tokens()).to_s
    end

    def xml()
      if !@xml
	@xml = REXML::QDocument.new('<body>'+format()+'</body>')
      end
      @xml.deep_clone
    end

    def res(site=nil)
      Resolver.new(xml(), site).resolve
    end

    def tdiary_res(site=nil, suf=nil)
      TDiaryResolver.new(xml(), site).resolve
    end

    def html(site=nil)
      xml = res(site)
      str = ""
      xml.root.each {|x|
	str << x.to_xhtml
      }
      str.chomp
    end

    def html_p(site=nil)
      html(site).delete("\n").sub(/^<p>/, '').chomp.sub(%r|</p>$|, '').sub(%r|<p />$|, '').chomp
    end
  end
end
