using System.Text;
using System.Drawing;
using System.Collections.Generic;
namespace FastColoredTextBoxNS
{
///
/// Exports colored text as HTML
///
/// At this time only TextStyle renderer is supported. Other styles is not exported.
public class ExportToHTML
{
public string LineNumbersCSS = "";
///
/// Use nbsp; instead space
///
public bool UseNbsp { get; set; }
///
/// Use nbsp; instead space in beginning of line
///
public bool UseForwardNbsp { get; set; }
///
/// Use original font
///
public bool UseOriginalFont { get; set; }
///
/// Use style tag instead style attribute
///
public bool UseStyleTag { get; set; }
///
/// Use 'br' tag instead of '\n'
///
public bool UseBr { get; set; }
///
/// Includes line numbers
///
public bool IncludeLineNumbers { get; set; }
FastColoredTextBox tb;
public ExportToHTML()
{
UseNbsp = true;
UseOriginalFont = true;
UseStyleTag = true;
UseBr = true;
}
public string GetHtml(FastColoredTextBox tb)
{
this.tb = tb;
Range sel = new Range(tb);
sel.SelectAll();
return GetHtml(sel);
}
public string GetHtml(Range r)
{
this.tb = r.tb;
Dictionary styles = new Dictionary();
StringBuilder sb = new StringBuilder();
StringBuilder tempSB = new StringBuilder();
StyleIndex currentStyleId = StyleIndex.None;
r.Normalize();
int currentLine = r.Start.iLine;
styles[currentStyleId] = null;
//
if (UseOriginalFont)
sb.AppendFormat("",
r.tb.Font.Name, r.tb.Font.SizeInPoints, r.tb.CharHeight);
//
if (IncludeLineNumbers)
tempSB.AppendFormat("{0} ", currentLine + 1);
//
bool hasNonSpace = false;
foreach (Place p in r)
{
Char c = r.tb[p.iLine][p.iChar];
if (c.style != currentStyleId)
{
Flush(sb, tempSB, currentStyleId);
currentStyleId = c.style;
styles[currentStyleId] = null;
}
if (p.iLine != currentLine)
{
for (int i = currentLine; i < p.iLine; i++)
{
tempSB.Append(UseBr ? "
" : "\r\n");
if (IncludeLineNumbers)
tempSB.AppendFormat("{0} ", i + 2);
}
currentLine = p.iLine;
hasNonSpace = false;
}
switch (c.c)
{
case ' ':
if ((hasNonSpace || !UseForwardNbsp) && !UseNbsp)
goto default;
tempSB.Append(" ");
break;
case '<':
tempSB.Append("<");
break;
case '>':
tempSB.Append(">");
break;
case '&':
tempSB.Append("&");
break;
default:
hasNonSpace = true;
tempSB.Append(c.c);
break;
}
}
Flush(sb, tempSB, currentStyleId);
if (UseOriginalFont)
sb.Append("");
//build styles
if (UseStyleTag)
{
tempSB.Length = 0;
tempSB.Append("");
sb.Insert(0, tempSB.ToString());
}
if (IncludeLineNumbers)
sb.Insert(0, LineNumbersCSS);
return sb.ToString();
}
private string GetCss(StyleIndex styleIndex)
{
List