Mega Code Archive

 
Categories / Delphi / Activex OLE
 

Exporting Syntax Highlighted text to HTML

Title: Exporting Syntax Highlighted text to HTML Question: In the past there have been requests on this already... now there is a new one. I really thing for this topic there should be a sourcecode available for all the folks in the DELPHI COMMUNITY. The job is simple... take a delphi-, java, C#, VB, C++ (to name the most wanted ones) sourcefile and create a HTML file where the syntax is highlighted. Answer: There is an easy way to make a Syntax Highlighter that exports HTML: Using SynEdit (a free component colection with full sourcecode). SynEdit comes with many highlighters for many languages: Delphi, VB, C++, Perl, Sql, Java and many more. And it also includes a class named TSynExporterHTML, that exports any highlighted text to HTML. Get SynEdit in its WebSite: http://synedit.sourceforge.net. Here is an example of how to use TSynExporterHTML: {$APPTYPE CONSOLE} program pas2html; {$I SynEdit.inc} uses Windows, Classes, Clipbrd, SynHighlighterPas, SynExportHTML; var ALines: TStringList; Syn: TSynPasSyn; Exp: TSynExporterHTML; begin if Clipboard.HasFormat(CF_TEXT) then begin ALines := TStringList.Create; try Syn := TSynPasSyn.Create(nil); try // get syntax highlighter settings Syn.EnumUserSettings(ALines); if ALines.Count 0 then Syn.UseUserSettings(ALines.Count - 1); // load text from clipboard ALines.Text := Clipboard.AsText; // export ALines to HTML, as HTML fragment in text format Exp := TSynExporterHTML.Create(nil); try Exp.Highlighter := Syn; Exp.ExportAsText := TRUE; Exp.CreateHTMLFragment := TRUE; Exp.ExportAll(ALines); Exp.CopyToClipboard; finally Exp.Free; end; finally Syn.Free; end; finally ALines.Free; end; end; end. This example just get some source code from the clipboard, highlight it (as Object Pascal source) and copy it into the clipboard as HTML (then you can paste it on a HTML editor). As you can see the source uses a TStringList, so if you want to use a file just use: ALines.LoadFromFile('C:\Somefile.pas'). The syntax highlighted text above was created with SynEdit...