Module: ANSI::BBCode

### Home Classes Methods

### In Files

- lib/ansi/bbcode.rb

### Methods

- ::ansi
- ::ansi_to_bbcode
- ::ansi_to_html
- ::bbcode_to_ansi
- ::bbcode_to_html
- ::html_to_ansi
- ::html_to_bbcode
- ::strip_bbcode

### Files

- COPYING.rdoc
- DEMO.rdoc
- HISTORY.rdoc
- README.rdoc

### Class/Module Index

Quicksearch

- ANSI
- ANSI::BBCode
- ANSI::Chain
- ANSI::Code
- ANSI::Columns
- ANSI::Constants
- ANSI::Diff
- ANSI::HexDump
- ANSI::Logger
- ANSI::Mixin
- ANSI::ProgressBar
- ANSI::String
- ANSI::Table
- ANSI::Terminal
- Object
- String

No matching classes.

# ANSI::BBCode

The BBCode module helps ease the separation of core and frontend with the core (or submodules) being still able to say, what colors shall be used in it's responses. This is achieved by encoding formatting information using the BBCode tokens. This enables you to "pipe" layout information such as colors, style, font, size and alignment through the core to the frontend.

Additionally it converts markups/codes between ANSI, HTML and BBCode almost freely ;)

    # Converting a bbcode string to ANSI and XHTML
    str = "this is [COLOR=red]red[/COLOR], this is [B]bold[/B]"
    print( BBCode.bbcode_to_ansi(str) )
    print( BBCode.bbcode_to_html(str) )

### Constants

ANSINAME2BBCODE

  ANSInames => BBCode LUT

ANSINAME2CODE

  ANSIname => ANSIcode LUT

BBCOLOR2ANSI

  BBColor => ANSIname LUT

### Public Class Methods

ansi(colorname) click to toggle source

Returns the ANSI sequence for given color, if existant

    # File lib/ansi/bbcode.rb, line 88
    def BBCode.ansi(colorname)
        colorname.strip!
        return ANSINAME2CODE[ colorname.downcase ]
    end

ansi_to_bbcode(string) click to toggle source

Returns the string with all ansi escape sequences converted to BBCodes

    # File lib/ansi/bbcode.rb, line 101
    def BBCode.ansi_to_bbcode(string)
        return "" if string.nil? || string.to_s.strip.empty?
        result = ""
        tagstack = []

        ## Iterate over input lines
        string.split("\n").each do |line|
            ## Iterate over found ansi sequences
            line.scan(/\e\[[0-9;]+m/).each do |seq|
                ansiname = ANSINAME2CODE.invert["#{seq}"]

                ## Pop last tag and form closing tag
                if ansiname == "reset"
                    lasttag = tagstack.pop
                    bbname = "/" + String.new( lasttag.split("=")[0] )

                ## Get corresponding BBCode tag + Push to stack
                else
                    bbname   = ANSINAME2BBCODE[ansiname]
                    tagstack.push(bbname)
                end

                ## Replace ansi sequence by BBCode tag
                replace = sprintf("[%s]", bbname)
                line.sub!(seq, replace)
            end

            ## Append converted line
            result << sprintf("%s\n", line)
        end

        ## Some tags are unclosed
        while !tagstack.empty?
            result << sprintf("[/%s]", String.new(tagstack.pop.split("=")[0])  )
        end

        return result
    end

ansi_to_html(string) click to toggle source

Converts an ANSI string to one with HTML markup. Returns the string with ANSI code sequences converted to XHTML markup.

    # File lib/ansi/bbcode.rb, line 316
    def BBCode.ansi_to_html(string)
        bbcoded = BBCode.ansi_to_bbcode(string )
        htmled  = BBCode.bbcode_to_html(bbcoded)

        return htmled
    end

bbcode_to_ansi(string, usecolors = true) click to toggle source

Converts a BBCode string to one with ANSI sequences. Returns the string with all formatting instructions in BBCodes converted to ANSI code sequences / aligned with spaces to specified width.

    # File lib/ansi/bbcode.rb, line 144
    def BBCode.bbcode_to_ansi(string, usecolors = true)
        return "" if string.nil? || string.to_s.strip.empty?
        result = ""

        return BBCode.strip_bbcode(string) if !usecolors

        ## Iterate over lines
        string.split("\n").each do |line|

            ## TODO: stacking? other styles!
            ANSINAME2BBCODE.each do |key,val|
                line.gsub!(/\[#{val}\]/, ANSINAME2CODE[key])
                line.gsub!(/\[\/#{val}\]/, ANSINAME2CODE["reset"])
            end

            ## Fonttypes and sizes not available
            line.gsub!(/\[SIZE=\d\]/, "")
            line.gsub!(/\[\/SIZE\]/, "")
            line.gsub!(/\[FONT=[^\]]*\]/, "")
            line.gsub!(/\[\/FONT\]/, "")

            ## Color-mapping
            colors = line.scan(/\[COLOR=(.*?)\]/)
            colors = colors.collect{|s|  s[0].to_s} if !colors.nil?
            colors.each do |col|
                name = BBCOLOR2ANSI[col.downcase]
                name = BBCOLOR2ANSI["white"] if name.nil?
                code = ANSINAME2CODE[name]

                line.gsub!(/\[COLOR=#{col}\]/, code)
            end
            line.gsub!(/\[\/COLOR\]/, ANSINAME2CODE["reset"])

            ## TODO: Alignment
            ## TODO: IMGs
            ## TODO: EMAILs
            ## TODO: URLs
            ## TODO: QUOTEs
            ## TODO: LISTs

            result << sprintf("%s\n", line)
        end

        return result
    end

bbcode_to_html(string) click to toggle source

Converts a BBCode string to one with HTML markup. Returns the string with all formatting instructions in BBCodes converted to XHTML markups.

    # File lib/ansi/bbcode.rb, line 251
    def BBCode.bbcode_to_html(string)
        return "" if string.nil? || string.to_s.strip.empty?
        result = ""
        quote = 0

        ## Iterate over lines
        string.split("\n").each do |line|
            styles = { "b" => "strong", "i" => "em", "u" => "u" }

            ## preserve B, I, U
            styles.each do |code,html|
                line.gsub!(/\[#{code}\]/, "<#{html}>")
                line.gsub!(/\[\/#{code}\]/, "</#{html}>")
            end

            ## COLOR => font color=... (TODO: should be numeric!)
            line.gsub!(/\[COLOR=(.*?)\]/, "<font color=\"\\1\">")
            line.gsub!(/\[\/COLOR\]/,     "</font>")

            ## SIZE => font size=...
            line.gsub!(/\[SIZE=(.*?)\]/, "<font size=\"\\1\">")
            line.gsub!(/\[\/SIZE\]/,     "</font>")

            ## URL
            line.gsub!(/\[URL\]([^\[]+?)\[\/URL\]/, "<a href=\"\\1\">\\1</a>")
            line.gsub!(/\[URL=(.*?)\](.+?)\[\/URL\]/, "<a href=\"\\1\">\\2</a>")

            ## IMG
            line.gsub!(/\[IMG=(.*?)\]/, "<img src=\"\\1\" />")

            ## ALIGN=center (TODO: right, left)
            line.gsub!(/\[ALIGN=center\]/, "<center>")
            line.gsub!(/\[ALIGN=right\]/,  "<center>")
            line.gsub!(/\[ALIGN=left\]/,   "<center>")
            line.gsub!(/\[\/ALIGN\]/,      "</center>")

            ## QUOTE
            quote+=1 if line =~ /\[QUOTE\]/
            quote-=1 if (line =~ /\[\/QUOTE\]/) && (quote > -1)
            line.gsub!(/\[QUOTE\]/,   "<pre>\n")
            line.gsub!(/\[\/QUOTE\]/, "</pre>\n")
            line.gsub!(/^/, "&#62;"*quote) if quote > 0

            ## EMAIL
            line.gsub!(/\[EMAIL\](.*?)\[\/EMAIL\]/, "<a href=\"mailto:\\1\">\\1</a>")

            ## LIST (TODO: LIST=1, LIST=A)
            line.gsub!(/\[LIST(?:=(.*?))?\]/, "\n<ul>\n")
            line.gsub!(/\[\/LIST\]/,          "\n</ul>\n")
            line.gsub!(/\[\*\]/,              "\n<li />")

            ## FONT => font ??????
            ## ?BLUR?, FADE?

            result << sprintf("%s<br />\n", line)
        end

        return result
    end

html_to_ansi(string) click to toggle source

Returns the (X)HTML markup code as ANSI sequences

    # File lib/ansi/bbcode.rb, line 324
    def BBCode.html_to_ansi(string)
        bbcoded = BBCode.html_to_bbcode(string )
        ansied  = BBCode.bbcode_to_ansi(bbcoded)

        return ansied
    end

html_to_bbcode(string) click to toggle source

Converts a HTML string into one with BBCode markup (TODO) Returns the (X)HTML markup string as BBCode

    # File lib/ansi/bbcode.rb, line 192
    def BBCode.html_to_bbcode(string)
        return "" if string.nil? || string.to_s.strip.empty?
        result = ""

        ## Iterate over lines
        string.split(/<br *\/?>/).each do |line|
            styles = { "strong" => "b", "b" => "b",
                        "em"     => "i", "i" => "i",
                        "u"      => "u" }

            ## preserve B, I, U
            styles.each do |html,code|
                line.gsub!(/<#{html}>/, "[#{code.upcase}]")
                line.gsub!(/<\/#{html}>/, "[/#{code.upcase}]")
            end

            ## TODO: COLORs
            ## TODO: SIZEs
            ## TODO: FONTs

            ## EMAIL
            line.gsub!(/<a +href *= *\"mailto:(.*?)\".*?>.*?<\/a>/, "[EMAIL]\\1[/EMAIL]")

            ## URL
            line.gsub!(/<a +href *= *\"((?:https?|ftp):\/\/.*?)\".*?>(.*?)<\/a>/, "[URL=\\1]\\2[/URL]")

            ## Other refs + closing tags => throw away
            line.gsub!(/<a +href *= *\".*?\".*?>/, "")
            line.gsub!(/<\/a>/,            "")

            ## IMG
            #line.gsub!(/<img +src *= *\"(.*?)\".*?\/?>/i, "[IMG=\\1]")
            line.gsub!(/<img +src *= *\"(.*?)\".*?\/?>/, "[IMG]\\1[/IMG]")

            ## CENTER (right/left??)
            line.gsub!(/<center>/,   "[ALIGN=center]")
            line.gsub!(/<\/center>/, "[/ALIGN]")

            ## QUOTE
            line.gsub!(/<(?:xmp|pre)>/,   "[QUOTE]")
            line.gsub!(/<\/(?:xmp|pre)>/, "[/QUOTE]")

            ## LIST
            line.gsub!(/<ul>/,      "\n[LIST]\n")
            line.gsub!(/<\/ul>/,    "\n[/LIST]\n")
            line.gsub!(/<li *\/?> */, "\n[*] ")

            ## Unkown tags => throw away
            line.gsub!(/<.*? *\/?>/, "")

            result << sprintf("%s<br />\n", line)
        end

        return result.gsub!(/<br *\/?>/, "\n")
    end

strip_bbcode(string) click to toggle source

--- strip_bbcode( string ) Will strip any BBCode tags from the given string.

    # File lib/ansi/bbcode.rb, line 95
    def BBCode.strip_bbcode(string)
        string.strip!
        return string.gsub(/\[[A-Za-z0-9\/=]+\]/, "")
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.